本文整理汇总了Python中models.Game类的典型用法代码示例。如果您正苦于以下问题:Python Game类的具体用法?Python Game怎么用?Python Game使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Game类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
def post(self):
"""
CREATE a new Game entity
"""
self.record_usage()
namespace_manager.set_namespace(users.get_current_user().user_id())
param_map = {}
param_map['player_faction'] = self.request.get('player_faction')
param_map['player_warcaster'] = self.request.get('player_warcaster')
param_map['opponent_name'] = self.request.get('opponent_name', '')
param_map['opponent_faction'] = self.request.get('opponent_faction')
param_map['opponent_warcaster'] = self.request.get('opponent_warcaster')
param_map['result'] = self.request.get('result')
param_map['size'] = int(self.request.get('size', 0))
param_map['won'] = self.request.get('won') == 'true'
param_map['draw'] = self.request.get('draw') == 'true'
param_map['teaching'] = self.request.get('teaching') == 'true'
param_map['location'] = self.request.get('location', '')
param_map['game_type'] = self.request.get('game_type', '')
date = self.request.get('date')
try:
real_date = datetime.datetime.strptime(date,'%m/%d/%Y')
except (ValueError):
real_date = datetime.datetime.strptime(date,'%Y-%m-%d')
param_map['date'] = real_date
param_map['created_at'] = datetime.datetime.now()
logging.error(param_map)
game = Game(**param_map)
game.put()
self.response.out.write(game.key.urlsafe())
示例2: startGame
def startGame(session):
"""
Starts the new game in one of the sessions.
"""
game = Game()
game.session = session
示例3: get_sendable_board
def get_sendable_board(game, side):
board = game.get_board()
# Only continue if the game hasn't finished
if game.has_ended():
if side == 1:
return Game.reverse_board(board)
else:
return board
if side == 0 and not game.blue_setup:
board[0] = unknown_row(side)
board[1] = unknown_row(side)
board[2] = unknown_row(side)
board[3] = unknown_row(side)
return board
else:
hidden_side_board = hide_side(board, side)
if side == 1:
return Game.reverse_board(hidden_side_board)
else:
return hidden_side_board
示例4: post
def post(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url("/"))
return
game_name = self.request.get("game_name")
if not game_name:
self.response.write("No game name specified")
return
game_key = db.Key.from_path("Game", game_name)
game = db.get(game_key)
if not game:
game = Game(key_name=game_name)
game.put()
logging.info("Game: {0}".format(game))
player = Player(user=user, parent=game)
player.put()
token = channel.create_channel("{0}:{1}".format(game_name, user.user_id()))
logging.info("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
self.redirect("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
示例5: open_or_new_games
def open_or_new_games(request):
if not request.COOKIES.get('nickname', ''):
return HttpResponseRedirect(reverse(set_nickname))
if request.method == 'POST':
form = NewGameForm(request.POST)
if form.is_valid():
nickname = re.sub(r'\W', '', request.COOKIES.get('nickname', ''))
num_players = form.cleaned_data['number_of_players']
game = Game(name=nickname, num_players=num_players)
game.save()
try:
player = game.add_player(nickname, True)
request.session['player_id'] = player.id
request.session['game_id'] = game.id
except Game.InvalidPlayer as x:
pass
#TODO: add session error message
return HttpResponseRedirect(reverse(current_game))
else:
form = NewGameForm()
return direct_to_template(request,
'open_or_new_games.html', {'form': form })
示例6: cancel_game
def cancel_game(self, request):
"""
Cancels a Blackjack Marathon game based on key.
"""
profile_key = Profile.get_profile_from_user().key
Game.cancel_game(profile_key, request.urlsafe_game_key)
return StringMessage(message='Game cancelled successfully.')
示例7: test_make_deck_shuffle_hit
def test_make_deck_shuffle_hit(self):
# setup
player = Player('cory', 'password')
game = Game('Blackjack')
game.players.append(player)
h = Hand()
h2 = Hand()
game.hands.append(h)
player.hands.append(h2)
cards = piece_maker(suits, card_values, 1)
h.cards.extend(cards)
cards_app.session.commit()
# end of setup
# deck is made in setUp() with piece_maker() ha
game.deck = h
game.hands.append(h2)
deck = game.deck
hand2 = h2
cards_app.session.flush()
assert deck.cards != shuffle(deck)
hand_before_hit = len(hand2.cards)
deck_before_hit = len(deck.cards)
hit(hand2, 1)
cards_app.session.commit()
# do we still have 52 cards after hitting?
assert len(set(deck.cards)) + len(set(hand2.cards)) == 52
assert len(deck.cards) == deck_before_hit-1
assert len(hand2.cards) == hand_before_hit+1
示例8: post
def post(self):
game = Game()
#Check logged in
user = users.get_current_user()
if not user:
self.response.write(json.dumps(dict(error="Dude, you gotta be logged in! Try reloading this page.")))
return
this_player = game.selectOne(config.JIVE_PROFILE_TBL, "fullname, title, picture_binary, id", "`email` = {}", [user.email()])
if this_player is None:
logging.info("couldn't find player in jive_profile table (email: '{0}')".format(email))
self.response.write(json.dumps({"result":"refresh"}))
return
#Get the json passed from the client page
jsonstring = self.request.body
jsdict = json.loads(jsonstring)
if 'filterchange' not in jsdict:
ret = self.choice_picked(game, this_player, jsdict)
else:
ret = self.new_filter(game, this_player, jsdict)
self.response.write(json.dumps(ret))
示例9: createGame
def createGame(self, request):
"""
a player creates a game of a unique name
"""
if request.game_name is None:
raise endpoints.UnauthorizedException(
'game_name is required to create a game')
player = Player.query(Player.displayName == request.player_name).get()
if not player:
raise endpoints.NotFoundException(
'No player found with name: {}' .format(request.player_name))
elif Game.query(Game.name == request.game_name).get():
raise endpoints.ConflictException(
'A Game with that name already exists!')
else:
# allocate new Game ID with Player key as parent
# allocate_ids(size=None, max=None, parent=None, **ctx_options)
# returns a tuple with (start, end) for the allocated range,
# inclusive.
p_key = player.key
g_id = Game.allocate_ids(size=1, parent=p_key)[0]
# make Game key from ID; assign initial values to the game entity
g_key = ndb.Key(Game, g_id, parent=p_key)
data = {} # is a dict
data['key'] = g_key
data['name'] = request.game_name
data['board'] = ['' for _ in range(9)]
Game(**data).put()
taskqueue.add(params={'email': player.mainEmail,
'gameInfo': repr(request)},
url='/tasks/send_confirmation_email')
game = g_key.get()
return game._copyGameToForm
示例10: create_game
def create_game(self, request) :
"""Create new conference."""
#get the user ID first and make sure they're authorised
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
#now create the game entity and insert it
game = Game(owner=user_id,
player1=GameMiniForm.get('player1'),
player2=GameMiniForm.get('player2'),
name=GameMiniForm.get('name'))
playerTurn = 1
#set the player turn randomly
if bool(random.getrandbits(1)) :
playerTurn = 1
else :
playerTurn = 2
game.playerTurn = playerTurn
game_key = game.put()
url_key = game_key.urlsafe()
#return all of the game details, including a game key
return GameForm(id=url_key, owner=user_id,
player1=game.player1,
player2=game.player2,
name=game.name)
示例11: _get_team_win_loss
def _get_team_win_loss(team):
team_a_count = Game.query().filter(Game.team_a == team.name).count()
team_b_count = Game.query().filter(Game.team_b == team.name).count()
game_count = team_b_count + team_a_count
win_count = Game.query().filter(Game.winner == team.name).count()
per = round(100 * float(win_count)/game_count)
return [_get_team_name_link(team.name), team.elo, game_count, win_count, per]
示例12: _get_team_map_win_loss
def _get_team_map_win_loss(team, map):
team_a_count = Game.query().filter(Game.map == map).filter(Game.team_a == team.name).count()
team_b_count = Game.query().filter(Game.map == map).filter(Game.team_b == team.name).count()
win_count = Game.query().filter(Game.map == map).filter(Game.winner == team.name).count()
game_count = team_b_count + team_a_count
per = 0 if not game_count else round(100 * float(win_count)/game_count)
return [map, game_count, win_count, per]
示例13: get
def get(self):
# Can't provide an ordering here in case inequality filters are used.
base_query = Game.all()
count = base_query.count()
results = base_query.fetch(count)
#db.delete(results)
# for game in results:
# resultsobj = resultsobj + simplejson.dumps({"latitude":game.location.lat,"longitude":game.location.lon,"name":game.name,"type":game.game_type})
# objs = simplejson.dumps(resultsobj)
public_attrs = Game.public_attributes()
results_obj = [
_merge_dicts({
'lat': result.location.lat,
'lng': result.location.lon,
},
dict([(attr, getattr(result, attr))
for attr in public_attrs]))
for result in results]
#for song in results:
#print song.type
# for result in query:
# resultsobj.push( "Title: " + result.address
self.response.out.write(simplejson.dumps({
'status': 'success',
'count': count,
'results': results_obj
}))
示例14: GameView
class GameView(TemplateView):
template_name = 'gameshow/game.html'
def _start_game(self):
player = Player.objects.create(name="Some Name", score=0)
self.thegame = Game()
self.thegame.players = player
self.thegame.title = 'My Game Title'
self.thegame.description = "Blah Blah Blah"
self.thegame.save()
def post(self, request, *args, **kwargs):
form = GameScore(request.POST)
if form.is_valid():
messages.add_message(self.request, messages.INFO, message="Enjoy your game!")
return redirect('game_main')
else:
return self.get(request, form=form)
def get_context_data(self, **kwargs):
self._start_game()
return {
'form': GameScore() if not kwargs.get('form') else kwargs['form'],
'game': self.thegame,
}
示例15: test_blackjack_player_wins
def test_blackjack_player_wins(self):
player = Player('cory','password')
game = Game('Blackjack')
hand = Hand()
player.bank = 100
player.hands.append(hand)
game.hands.append(hand)
game.players.append(player)
bank_before_bet = player.bank
# cards_app.session.commit()
cards_app.session.flush()
bet(hand, 50)
cards = [Card(sequence=1), Card(sequence=10)]
hand.cards.extend(cards)
count_blackjack(hand)
evaluate_hit(hand)
# player wins with nautral evaluate_hit
assert player.bank == bank_before_bet - 50
# player stands on 18, dealer stands on 17
hand.cards = [Card(sequence=10), Card(sequence=8)]
bet(hand, 50)
game.dealer = Player('cory','password')
dealer = game.dealer
dealer.cards = [Card(sequence=10), Card(sequence=17)]
dealer_hand = Hand()
dealer_hand.cards = dealer.cards