示例#1
0
 def test_time_left_2(self):
     # add game, moves and check them
     game = Game.create(white='123',
                        black='456',
                        state='Ke1,ke8',
                        type_game=TYPE_SLOW,
                        time_limit=10)
     Move.create(game=game,
                 number=1,
                 figure='K',
                 move='e1-e2',
                 time_move=9,
                 color=WHITE)
     Move.create(game=game,
                 number=2,
                 figure='k',
                 move='e8-e7',
                 time_move=3,
                 color=BLACK)
     Move.create(game=game,
                 number=3,
                 figure='K',
                 move='e2-e3',
                 time_move=5,
                 color=WHITE)
     Move.create(game=game,
                 number=4,
                 figure='k',
                 move='e7-e8',
                 time_move=6,
                 color=BLACK)
     self.assertFalse(game.ended)
     self.assertAlmostEqual(game.time_left(WHITE), 10, places=1)
     self.assertAlmostEqual(game.time_left(BLACK), 10, places=1)
     # shift date_state in limit
     self.assertFalse(game.is_time_over())
     game.date_state = datetime.now() - timedelta(seconds=3)
     self.assertAlmostEqual(game.time_left(WHITE), 7, places=1)
     self.assertAlmostEqual(game.time_left(BLACK), 10, places=1)
     self.assertFalse(game.is_time_over())
     # shift date_state out limit
     game.date_state = datetime.now() - timedelta(seconds=10)
     self.assertTrue(game.is_time_over())
     self.assertTrue(game.ended)
     self.assertEqual(game.winner, BLACK)
     self.assertFalse(game.is_time_over())
示例#2
0
 def test_time_left_3(self):
     # add game, moves and check them
     game = Game.create(white='123',
                        black='456',
                        state='Ke1,ke8',
                        time_limit=10)
     Move.create(game=game,
                 number=1,
                 figure='K',
                 move='e1-e2',
                 time_move=9,
                 color=WHITE)
     Move.create(game=game,
                 number=2,
                 figure='k',
                 move='e8-e7',
                 time_move=3,
                 color=BLACK)
     Move.create(game=game,
                 number=3,
                 figure='K',
                 move='e2-e3',
                 time_move=5,
                 color=WHITE)
     Move.create(game=game,
                 number=4,
                 figure='k',
                 move='e7-e8',
                 time_move=6,
                 color=BLACK)
     self.assertFalse(game.ended)
     self.assertIsNone(game.time_left(WHITE))
     self.assertIsNone(game.time_left(BLACK))
     self.assertFalse(game.is_time_over())
     # shift date_state out limit
     game.date_state = datetime.now() - timedelta(days=1000)
     self.assertIsNone(game.time_left(WHITE))
     self.assertIsNone(game.time_left(BLACK))
     self.assertFalse(game.is_time_over())
     self.assertIsNone(game.winner)
示例#3
0
文件: api.py 项目: rastaehli/wordwars
class WordWarsApi(remote.Service):
    """Google endpoints API for WordWars game service."""

    def __init__(self):
        """initialize objects available to all api endpoint methods"""
        self.games = GameStateRepository()
        self.users = UserRepository()
        self.moves = MoveRepository()

    @endpoints.method(request_message=NEW_USER_REQUEST,
                      response_message=StringMessage,
                      path='user',
                      name='create_user',
                      http_method='POST')
    def create_user(self, request):
        """Create a User. Requires a unique username"""
        if self.users.findByName(request.user_name):
            raise endpoints.ConflictException(
                'A User with that name already exists!')
        if not EMAIL_REGEX.match(request.email):
            raise endpoints.BadRequestException(
                'Email address is not valid: {}'.format(request.email))
        user = User.create(request.user_name, request.email)
        self.users.register(user)
        return StringMessage(message='User {} created!'.format(request.user_name))

    @endpoints.method(request_message=USERNAME_REQUEST,
                      response_message=StringList,
                      path='user/{user_name}/games',
                      name='get_user_games',
                      http_method='GET')
    def get_user_games(self, request):
        """Return id values for all games where this user is a player."""
        user = self.userByName(request.user_name)
        idList = []
        for p in PlayerStateRepository().findByUser(user):
            idList.append(self.games.id(p.game))
        gameIds = StringList()
        gameIds.strings = idList
        return gameIds

    @endpoints.method(request_message=PLAIN_REQUEST,
                      response_message=IdForm,
                      path='game/new',
                      name='new_unstarted_game',
                      http_method='POST')
    def new_unstarted_game(self, request):
        """Create a new game with no users and return its ID."""
        game = GameState.create()
        # "register" on next line sets "board" and other persistent variables
        self.games.register(game)
        # TODO: JSON response
        next = game.nextPlayer()
        return IdForm(urlsafe_key=self.games.id(game))

    @endpoints.method(request_message=GAME_ID_REQUEST,
                      response_message=GameForm,
                      path='game/{gameid}',
                      name='get_game',
                      http_method='GET')
    def get_game(self, request):
        """Return game state for requested ID."""
        game = self.gameById(request.gameid)
        return self.gameFormFrom(game, '')

    @endpoints.method(request_message=ADD_USER_REQUEST,
                      response_message=StringMessage,
                      path='game/{gameid}/add_user',
                      name='add_user',
                      http_method='PUT')
    def add_user(self, request):
        """Add user to requested game."""
        game = self.gameById(request.gameid)
        if game.started():
            raise endpoints.BadRequestException(
                'Can''t add user after game is started.')
        user = self.userByName(request.user_name)
        game.addPlayer(user)
        self.games.update(game)
        return StringMessage(message='User {} added!'.format(request.user_name))

    @endpoints.method(request_message=GAME_ID_REQUEST,
                      response_message=GameForm,
                      path='game/{gameid}/start',
                      name='start_game',
                      http_method='PUT')
    def start_game(self, request):
        """Start requested game (no more players may be added)."""
        game = self.gameById(request.gameid)
        if len(game.players) <= 0:
            raise endpoints.BadRequestException(
                'Must add players before starting.')
        self.validateNotOver(game)
        self.validateNotCancelled(game)
        game.start()
        self.games.update(game)
        return self.gameFormFrom(game, '')

    @endpoints.method(request_message=MAKE_MOVE_REQUEST,
                      response_message=GameForm,
                      path='game/{gameid}/move',
                      name='make_move',
                      http_method='PUT')
    def make_move(self, request):
        """Add requested word to the board at x,y, across or not."""
        game = self.gameById(request.gameid)
        self.validateStarted(game)
        self.validateNotOver(game)
        self.validateNotCancelled(game)
        if game.nextPlayer().player.name != request.user_name:
            raise endpoints.BadRequestException(
                'Not turn yet for {}'.format(request.user_name))
        user = self.users.findByName(request.user_name)
        word = request.word
        across = request.across
        x = request.x
        y = request.y
        scoreBefore = game.scoreForUser(user)
        if len(request.word) <= 0:
            game.skipTurn(user)
        else:
            try:
                game.playWord(user, x, y, across, word)
            except Exception, e:
                raise endpoints.BadRequestException(
                    'Illegal move: {}'.format(e.message))
        scoreAfter = game.scoreForUser(user)
        playScore = scoreAfter - scoreBefore
        self.games.update(game)
        # keep history of moves
        self.moves.register(
            Move.create(game, user, word, across, x, y, playScore))
        return self.gameFormFrom(
            game, self.lastPlayDescription(scoreBefore, scoreAfter))