コード例 #1
0
    def _createOthelloPlayerObject(self, request):
        if User.query(User.name == request.user_name).get():
            print "Found in User"
        else:
            # user not found, adding both to User
            user_key = ndb.Key(User, request.user_name)
            user = User(key=user_key, name=request.user_name,
                        email=request.email)
            user.put()
            print "Added to User"
        u_key = ndb.Key(User, request.user_name)
        # check if it's OthelloPlayer
        if OthelloPlayer.query(ancestor=u_key).get():
            raise endpoints.ConflictException(
                'An Othello user with that name already exists!')

        # use user_name as key to get game date using creator user_name
        ou_key = ndb.Key(OthelloPlayer, request.user_name, parent=u_key)
        print "Got new key for othello player"
        data = {}
        data['key'] = ou_key
        # adding scoreboard entry
        sc_id = OthelloGame.allocate_ids(size=1, parent=ou_key)[0]
        sc_key = ndb.Key(OthelloScoreBoardEntry, sc_id, parent=ou_key)
        player_score_entry = OthelloScoreBoardEntry(
                key=sc_key,
                points=0,
                wins=0,
                winning_streak=0,
                score_difference_average=0)

        # Adding entities to datastore
        # Added to OthelloPlayer
        OthelloPlayer(**data).put()
        # Added to ScoreBoardEntry
        player_score_entry.put()

        return SimpleMessage(message='User {} created!'.format(
                request.user_name))
コード例 #2
0
 def get_high_scores(self, request):
     """ Get top MAX_TOP_SCORERS high scores from all users,
     sorted by score, descending """
     scores = OthelloScoreBoardEntry.query()
     if scores.count() > 0:
         print 'Found some scores', scores
         for i in scores:
             print "score:", i
         scores = scores.order(-OthelloScoreBoardEntry.wins)
         scores = scores.order(-OthelloScoreBoardEntry.points)
         scores = scores.fetch(MAX_TOP_SCORERS)
         return OthelloHighScoreForm(
                 message="Top {0} scores".format(MAX_TOP_SCORERS),
                 scoreboardentry=[self._copyHighScoreEntryToForm(
                     hse) for hse in scores])
     else:
         return OthelloHighScoreForm(
             message='No scores yet! Play some games.')
コード例 #3
0
    def get_user_rankings(self, request):
        """ User ranking based on the sum of wins + winning streak +
        average win score difference / 10 """

        ranking = OthelloScoreBoardEntry.query()
        if ranking.count() > 0:
            print 'Found some ranked users'
            ranking = ranking.order(-OthelloScoreBoardEntry.performance_index)
            ranking = ranking.fetch(MAX_TOP_SCORERS)
            return OthelloPlayerRankingForm(
                    entries=[self._copyRankingEntryToForm(
                        ref) for ref in ranking],
                    explanation='This ranking is computed as the sum of'
                    ' winning streak + games won + '
                    'winning score difference average / 10')
        else:
            return OthelloPlayerRankingForm(
                explanation='No rankings available yet! Play some games.')
コード例 #4
0
    def _make_move(self, request):
        """ Controller for movements. If game is SINGLE_PLAYER,
        CPU will take turn after player submits valid move.
        Otherwise, CPU waits for valid move or yield from player"""
        game = get_by_game_id(request.game_id)
        if not game:
            return False, "Game not found"
        print "Game status", game.status, type(game.status)
        if not game.status == "ACTIVE":
            return False, "This game is not active"

        if ndb.Key(OthelloPlayer, request.user_name,
                   parent=ndb.Key(User, request.user_name))\
                not in game.userKeys:
            return False, "Player {0} is not registered for this game".\
                    format(request.user_name)
        parent_keys = [p.parent() for p in game.userKeys]
        players = ndb.get_multi(parent_keys)
        print "Players in this game", players

        # load game logic object
        game_logic = load_game_logic(game.gamelogic)

        player_turn = 1 if players[0].name == request.user_name else 2
        isvalid, message = game_logic._make_move(player_turn, request.move)
        print message

        # load an update game history in memory
        game_history = OthelloGameHistory.query(ancestor=game.key).get()
        if not game_history.moves:
            moves = []
        else:
            moves = json.loads(game_history.moves)
        # append moves from user if move is valid
        if isvalid:
            moves.append([request.user_name, request.move])
            if game_logic.game_mode == TWO_PLAYER_MODE:
                # PUSH TASK QUEUE to notify opponent that move has been made
                taskqueue.add(params={'email': players[0].email if
                              player_turn == 2 else players[1].email,
                              'score': game_logic._getScore()},
                              url='/tasks/send_gameturn_notification_email')

        print "Whose turn is it?", game_logic.CP
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # CPU MOVE

        if isvalid and game_logic.game_mode == SINGLE_PLAYER_MODE:
            print "Calling CPU for move..."
            isvalid, cpu_move = game_logic._cpu_move()
            moves.append(['cpu', cpu_move])
            print message
            message = "Your move was valid. {0}".format(cpu_move)

        # updates game logic with values from OthelloLogic instance
        update_game_logic(game_logic, game.gamelogic)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # GAME OVER CONDITIONS

        if game_logic._isBoardFull():
            game.status = "ENDED_COMPLETE"
            message = "Game has ended. The board is full!"
        if request.move == '0':
            game.status = "ENDED_INCOMPLETE"
            # record last move 
            moves.append([players[0].name if player_turn == 1 else 
                players[1].name, request.move])
            message = "The user abandoned the game. "
            "Score will be accounted for"

        if not game.status == "ACTIVE":
            # get score
            score_player1, score_player2 = game_logic._getScore()
            score_diff = abs(score_player1-score_player2)
            player1_entry = OthelloScoreBoardEntry.query(
                    ancestor=game.userKeys[0]).get()
            # CHECK END OF TWO PLAYER GAME
            if game_logic.game_mode == TWO_PLAYER_MODE:
                player2_entry = OthelloScoreBoardEntry.query(
                        ancestor=game.userKeys[1]).get()
                if score_player1 > score_player2:
                    # PLAYER 1 WINS
                    message = "Player {0} wins!".format(
                            game.userKeys[0].parent().get().name)
                    player1_entry.points += score_player1
                    player1_entry.wins += 1
                    player1_entry.winning_streak += 1
                    # update score difference average - player 1
                    update_score_difference_ave(
                            player1_entry.score_difference_average,
                            score_diff)
                    player2_entry.winning_streak = 0
                elif score_player1 < score_player2:
                    # PLAYER 2 WINS
                    message = "Player {0} wins!".format(
                            game.userKeys[1].parent().get().name)
                    player2_entry.points += score_player2
                    player2_entry.wins += 1
                    player2_entry.winning_streak += 1
                    # update score difference average - player 2
                    update_score_difference_ave(
                            player2_entry.score_difference_average,
                            score_diff)
                    player1_entry.winning_streak = 0
                else:
                    # tie game
                    message = "This game is tied! No changes in scoreboard"
                # update players scoreboard entries in datastore
                ndb.put_multi([player1_entry, player2_entry])
            # CHECK END FOR SINGLE PLAYER GAME
            if game_logic.game_mode == SINGLE_PLAYER_MODE:
                if score_player1 > score_player2:
                    # PLAYER 1 WINS
                    message = "Player {0} wins!".format(
                            game.userKeys[0].parent().get().name)
                    player1_entry.points += score_player1
                    player1_entry.wins += 1
                    update_score_difference_ave(
                            player1_entry.score_difference_average,
                            score_diff)
                    player1_entry.winning_streak += 1
                elif score_player1 < score_player2:
                    message = "CPU wins."
                    player1_entry.winning_streak = 0
                player1_entry.put()

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        # UPDATE GAME AND HISTORY DATASTORE
        game.put()
        # UPDATE GAME HISTORY
        game_history.moves = json.dumps(moves)
        game_history.put()

        return True, message