コード例 #1
0
    def _newOthelloGame(self, request):
        """ Logic for creating a new Othello game.
        Create ndb types that will store the game
        logic using the OthelloLogic class
        implementation """

        # set game mode
        if request.player_two:
            playerNames = [ request.player_one, request.player_two ]
        else:
            playerNames = [ request.player_one ]

        if len(playerNames) == 1:
            game_mode = SINGLE_PLAYER_MODE
        else:
            game_mode = TWO_PLAYER_MODE

        # get OthelloPlayer keys for this game
        # assert : all keys have been verified to exist
        othello_players_keys = [ndb.Key(
            OthelloPlayer, name, parent=ndb.Key(
                User, name)) for name in playerNames]

        # initialize logic
        new_game_logic = OthelloLogic(game_mode=game_mode)
        # initialize game object with
        # explicit array name containers
        json_board = json.dumps(new_game_logic.B)
        json_array_x = json.dumps(new_game_logic.X)
        json_array_y = json.dumps(new_game_logic.Y)
        json_array_n = json.dumps(new_game_logic.N)
        json_array_move = json.dumps(new_game_logic.D)
        json_check_move = json.dumps(new_game_logic.C)
        game_logic = OthelloDatastoreLogic(
                board=json_board,
                player_turn=new_game_logic.CP,
                check_move=json_check_move,
                array_move=json_array_move,
                array_x=json_array_x,
                array_y=json_array_y,
                array_n=json_array_n,
                game_mode=new_game_logic.game_mode)

        new_game = OthelloGame(
                status="ACTIVE",
                starttime=datetime.today(),
                gamelogic=game_logic,
                userKeys=othello_players_keys)

        # link new game to creator, in this case, first user in player list
        g_id = OthelloGame.allocate_ids(size=1,
                                        parent=othello_players_keys[0])[0]
        g_key = ndb.Key('OthelloGame', g_id, parent=othello_players_keys[0])
        new_game.key = g_key
        # add generated id as game id
        new_game.game_id = g_id

        # create game history entity
        # adding scoreboard entry
        new_game.put()
        print "Game created"
        gh_id = OthelloGameHistory.allocate_ids(size=1, parent=g_key)[0]
        gh_key = ndb.Key(OthelloGameHistory, gh_id, parent=g_key)
        game_history = OthelloGameHistory(key=gh_key)

        game_history.put()

        # load OtheloPlayer entities
        players = ndb.get_multi(othello_players_keys)
        for p in players:
            p.gameKeys.append(g_key)
        ndb.put_multi(players)
        print "Added game to player game keys"

        return new_game.game_id