当前位置: 首页>>代码示例>>Python>>正文


Python Player.query方法代码示例

本文整理汇总了Python中models.Player.query方法的典型用法代码示例。如果您正苦于以下问题:Python Player.query方法的具体用法?Python Player.query怎么用?Python Player.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Player的用法示例。


在下文中一共展示了Player.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_player

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def create_player(self, request):
        """Creates a new player.

        This function creates a new player. It will also make sure
        that the chosen username is not yet taken.
        (NB: Currently this function does not implement any validity checks
        on the email address, such as a regex etc.)

        Returns:
            StringMessage -- confirmation of player creation

        Raises:
            ConflictException -- if username or email address is taken already
        """
        # Check username and email address for conflicts
        if Player.query(Player.email_address == request.email_address).get():
            raise endpoints.ConflictException(
                    'A Player with that email address already exists.')
        if Player.query(Player.user_name == request.user_name).get():
            raise endpoints.ConflictException(
                    'A Player with that name already exists.')

        # Create player
        player = Player(user_name=request.user_name,
                        email_address=request.email_address)
        player.put()

        # Return confirmation of player creation
        return StringMessage(message='Player successfully created.')
开发者ID:zebralove79,项目名称:fsd_p4g,代码行数:31,代码来源:api.py

示例2: new_game

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
 def new_game(self, request):
     """Creates new game. Tipp: You need the urlsafe_key later"""
     player1 = Player.query(Player.name == request.player1).get()
     player2 = Player.query(Player.name == request.player2).get()
     if not (player1 and player2):
         raise endpoints.NotFoundException('No user with this name in the database')
     game = Game.new_game(player1.key, player2.key)
     # player.key gives a specific entity from the kind (Player)
     # and inputs this to new_game
     return Game.to_form(game, 'Good luck playing TICTACTOE!')
开发者ID:NojNo,项目名称:Project4,代码行数:12,代码来源:tictactoe.py

示例3: get

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
 def get(self):
     #get the roster
     MRoster = Player.query(Player.club == 'mens').fetch(50)
     WRoster = Player.query(Player.club == 'womens').fetch(50)
     print MRoster[0].first
     print MRoster[0].last
     print 'asf'
     params = {
             'Mroster': MRoster,
             'Wroster': WRoster,
             'MRosterindex' : range(len(MRoster)),
             'WRosterindex' : range(len(WRoster))
              }
     return self.render_template('roster.html', **params)
开发者ID:cdknorow,项目名称:ISUSoccerClub,代码行数:16,代码来源:handlers.py

示例4: _validate_has_not_player_already

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
 def _validate_has_not_player_already(self, user):
     player_key = ndb.Key(Player, user.user_id())
     if Player.query(Player.key == player_key).count() > 0:
         error_400(self.response, "ERROR_HAS_PLAYER", "You can only register 1 player")
         return False
     else:
         return True
开发者ID:Andrioden,项目名称:dotacareer,代码行数:9,代码来源:players.py

示例5: post

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def post(self):
        request_data = json.loads(self.request.body)
        logging.info(request_data)
        user = users.get_current_user()

        # VALIDATION
        if not validate_request_data(self.response, request_data, ['nick', 'player_class']):
            return
        if not validate_logged_inn(self.response):
            return
        if not self._validate_has_not_player_already(user):
            return
        if Player.query(Player.nick_lower == request_data['nick'].lower()).count() > 0:
            error_400(self.response, "ERROR_NICK_TAKEN", "The nickname %s is already taken" % request_data['nick'])
            return
        if not is_valid_player_class_name(request_data['player_class']):
            error_400(self.response, "ERROR_BAD_PLAYER_CLASS", "Player class ' %s ' is not valid." % request_data['player_class'])
            return

        # REGISTER PLAYER
        new_player = Player(
            id=user.user_id(),
            nick=request_data['nick']
        )

        for player_class in player_class_metrics:
            if player_class['name'] == request_data['player_class']:
                logging.info(player_class['stat_modifiers'])
                for stat_name, stat_value in player_class['stat_modifiers'].iteritems():
                    current_stat_value = getattr(new_player, stat_name)
                    new_stat_value = current_stat_value + stat_value
                    setattr(new_player, stat_name, new_stat_value)

        new_player.put().get()
        set_json_response(self.response, new_player.get_data("full"))
开发者ID:Andrioden,项目名称:dotacareer,代码行数:37,代码来源:players.py

示例6: get

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def get(self):
        # find all players who have set an email and have recently lost

        # LATER - add query index to allow searching for non-null emails
        # ref https://cloud.google.com/appengine/docs/python/ndb/queries
        losers = Player.query(Player.needs_taunted == True)

        for loser in losers:
            if loser.player_email is None:
                continue

            name=loser.player_name
            email=loser.player_email

            if name is None:
                name=""

            subject="Hello {} ".format(name)

            body="It's HIGH NOON"
            body=body + '<hr />'
            body=body + '<img src = "http://img.ifcdn.com/images/8b3e2b0811fd853e566f1c06b54de1368dc8efb5faba84144f4839ed41e64cdc_1.jpg" alt="highnoon.gif" >'
            # This will send test emails, the arguments to send_mail are:
            # from, to, subject, body
            mail.send_mail('[email protected]{}.appspotmail.com'.format(app_identity.get_application_id()),
                           email,
                           subject,
                           body)

            loser.needs_taunted=False

        # return success
        self.response.set_status(204)
开发者ID:bschmoker,项目名称:highnoon,代码行数:35,代码来源:main.py

示例7: get_dice

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
 def get_dice(self, request):
     """Returns a player's dice."""
     # Can still use if game is over or cancelled for historical purposes
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     user = User.query(User.user_name == request.user_name).get()
     if game:
         player = Player.query(
             Player.game == game.key,
             Player.user == user.key)
         if user:
             if player:
                 if user.password != request.password:
                     raise endpoints.UnauthorizedException(
                         'Invalid password!')
                 else:
                     # For those using themselves to test
                     ids = []
                     for row in player:
                         ids.append(row.key)
                     dice = (Dice.query(Dice.player.IN(ids))
                                 .order(Dice.player).order(Dice.face))
                     return Dice.to_form(dice)
             else:
                 raise endpoints.NotFoundException('Player not found!')
         else:
             raise endpoints.NotFoundException(
                 'A User with the name %s does not exist!'
                 % (user.replace("'", "''")))
     else:
         raise endpoints.NotFoundException('Game not found!')
开发者ID:danideter,项目名称:Udacity,代码行数:32,代码来源:api.py

示例8: get

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def get(self):
        game, err_msg = get_game(self.request.get('game_id'))
        if game is None:
            logger.error("no game found. err_msg={}".format(err_msg))
            render_error_template(self.response, err_msg)
            return
        game_over = False
        curr_turn = find_curr_turn(game)
        if curr_turn >= game.max_turns:
            game_over = True
        if game.winner_name:
            game_over = True
        players_query = Player.query(ancestor=game.key).order(-Player.date)
        players = players_query.fetch(PLAYERS_PER_GAME)
        num_players = len(players)
        extended_players = []
        for player in players:
            extended_player = dict(player=player)
            extended_player['turns'] = get_turns(player.key)
            extended_players.append(extended_player)

        template_values = {
            'game': game,
            'game_over': game_over,
            'num_players': num_players,
            'expected_players': PLAYERS_PER_GAME,
            'players': extended_players,
        }
        render_template(self.response, 'status.html', template_values)
开发者ID:rancho124,项目名称:guesser,代码行数:31,代码来源:views.py

示例9: get_user_games

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def get_user_games(self, request):
        """Returns games for a specific user."""
        user = User.query(User.user_name == request.user_name).get()

        if user:
            if user.password != request.password:
                raise endpoints.UnauthorizedException(
                            'Invalid password!')

            user_plays = Player.query(Player.user == user.key)

            if user_plays:
                games = []
                for play in user_plays:
                    game = play.game.get()
                    if not game.game_over and not game.cancelled:
                        game_number = len(games)
                        games.append(
                            game.to_form('Game number %d.' % (game_number)))
                if len(games) != 0:
                    forms = GameForms()
                    forms.games = games
                    return forms
                else:
                    raise endpoints.NotFoundException(
                        'No active games found.')
            else:
                raise endpoints.NotFoundException('No games found.')
        else:
            raise endpoints.NotFoundException('User not found.')
开发者ID:danideter,项目名称:Udacity,代码行数:32,代码来源:api.py

示例10: ai_move

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def ai_move(self, request):
        """Instruct the AI to make a move"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        game = get_by_urlsafe(request.game_key, Game)
        if not game:
            raise endpoints.NotFoundException("Game not found")

        player = Player.query(Player.email == user.email()).get()
        if not player or player.key != game.player:
            raise endpoints.UnauthorizedException(
                'You are not the player for the game')

        if game.state == 0:
            raise endpoints.ForbiddenException(
                'It is the player\'s turn')
        if game.state != 1:
            raise endpoints.ForbiddenException(
                'Game already over')

        board = Board(values=game.board_values)

        ai_won, origin, destination, captures = ai_move(board=board)

        origin_value = game.add_move(
            board, False, ai_won, origin, destination, captures)

        return game.get_play_result(
            origin_value, origin, destination, captures, game.state)
开发者ID:vssrcj,项目名称:hnefatafl-game,代码行数:33,代码来源:api.py

示例11: get_user_games

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def get_user_games(self, request):
        """Get games in progress and completed games for a specified player"""

        # check if player exists
        player = Player.query(Player.player_id == request.player_id).get()

        if player is None:
            raise endpoints.BadRequestException(
                'specified player_id not found')

        inprogress_games = []
        completed_games = []

        # find in progress games for this user
        results = Game.query(Game.player_id == request.player_id)

        if results is not None:
            for game in results:
                if game.won is None:
                    inprogress_games.append(game.game_id)
                else:
                    completed_games.append(game.game_id)

        return GameListMessage(
            completed_games=completed_games, inprogress_games=inprogress_games)
开发者ID:bschmoker,项目名称:highnoon,代码行数:27,代码来源:api.py

示例12: createGame

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    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
开发者ID:zhangtreefish,项目名称:Project-4-for-Full-Stack-Nanodegree-at-Udacity,代码行数:36,代码来源:api.py

示例13: _prepReminder

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
 def _prepReminder():
     games = Game.query(
         Game.gameCurrentMove < 9 and Game.gameCurrentMove > 0).fetch()
     remindees = ''
     if games:
         # If there are games ready for sign up,
         # format announcement and set it in memcache for each game
         for game in games:
             last_move = Move.query(
                 Move.moveNumber==game.gameCurrentMove-1).get()
             if last_move:
                 current_time = datetime.utcnow()
                 if last_move.moveTime and (current_time - last_move.moveTime > timedelta(days=5)):
                     next_player = Player.query(Player.displayName == game.nextPlayer).get()
                     if next_player.mainEmail:
                         print 'next_player.mainEmail', next_player.mainEmail
                         remindees.join(next_player.displayName)
                         mail.send_mail(
                             '[email protected]{}.appspotmail.com' .format(
                                 app_identity.get_application_id()),
                             next_player.mainEmail,
                             'Coming back to tic-tac-toe?',
                             'It has been 5 days since the last move on:\r\n\r\n{}' .format(
                                 game.name)
                         )
     return remindees
开发者ID:zhangtreefish,项目名称:Project-4-for-Full-Stack-Nanodegree-at-Udacity,代码行数:28,代码来源:api.py

示例14: game_history

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
    def game_history(self, request):
        """Get the history of a game, ranked from old to new"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        game = get_by_urlsafe(request.game_key, Game)
        if not game:
            raise endpoints.NotFoundException("Game not found")

        player = Player.query(Player.email == user.email()).get()
        if not player or player.key != game.player:
            raise endpoints.UnauthorizedException(
                'You are not the player for the game')

        return PlayResults(
            results=[
                PlayResult(
                    origin_value=move[0],
                    origin=str(move[1]),
                    destination=str(move[2]),
                    captures=str(move[3]),
                    game_state=move[4]
                ) for move in game.moves
            ]
        )
开发者ID:vssrcj,项目名称:hnefatafl-game,代码行数:28,代码来源:api.py

示例15: post

# 需要导入模块: from models import Player [as 别名]
# 或者: from models.Player import query [as 别名]
	def post(self):
		email = self.request.get('email')
		user = User.query(User.email == email).get()
		monsterlist = Monster.query(Monster.user == user.key).fetch()
		if user is not None and monsterlist is not None:
			playlist = []
			for monst in monsterlist:
				dbplay = Player.query(Player.monster == monst.key).get()
				if dbplay is not None:
					playlist.append(dbplay)
			pl = []
			logging.warning(playlist)
			for play in playlist:
				monster = Monster.query(Monster.key == play.monster).get()
				board = Board.get(play.board)
				if monster.properties is None:
					monster.properties = json.dumps({})
				pd = {'key': play.key.urlsafe(), 'monster': {'key': monster.key.urlsafe(), 'name': monster.name, 'properties': json.loads(monster.properties), 'date': str(monster.date)}, 'board': {'key': play.board.urlsafe()}}
				pl.append(pd)

			if user.gamelimit is None:
				user.gamelimit = 1
				user.put()
			logging.warning({'status': 1, 'games': pl, 'gamelimit': user.gamelimit})
			self.response.out.write(json.dumps({'status': 1, 'games': pl, 'gamelimit': user.gamelimit}))
		else:
			self.response.out.write(json.dumps({'status': -1, 'message': 'User not found.'}))
开发者ID:ThomasMarcel,项目名称:natural_selection,代码行数:29,代码来源:api.py


注:本文中的models.Player.query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。