def post(self): """ Send a reminder email to player (if email address on file) each time the opponent in a game completes a move. Email body provides urlsafe key, player's hand, visible draw_card and instructions. Uses appEngine Push Queue """ app_id = app_identity.get_application_id() user = get_by_urlsafe(self.request.get('user_key'), User) game = get_by_urlsafe(self.request.get('game_key'), Game) # Get hand of current player if game.active_player == game.player_one: hand = game.hand_one else: hand = game.hand_two # Format game data for e-mail sorted_hand = sorted(hand) string_hand = ' '.join(str(card) for card in sorted_hand) string_card = ' '.join(game.draw_card) # Prepare e-mail subject = 'Your turn!' body = "Hello {}: Your opponent just moved, so it's your turn." \ " Your hand is {}. The visible card is {}." \ " When you go to start_move, enter 1 to take visible card" \ " or 2 to draw from pile. The game key is {}.". \ format(user.name, string_hand, string_card, game.key.urlsafe()) logging.debug(body) # Arguments to send_mail are: from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), user.email, subject, body)
def get_trivia_game(self, request): """Return the current game state. Requires urlsafe_trivia_game_key""" game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame) if game: user_key = game.user question_key = game.get_question_from_pool() if question_key: if len(game.turn_keys) == 0: # Create a new turn turn = Turn.new_turn(game.key, user_key, question_key) game.remove_question_from_pool(question_key) game.register_turn(turn.key) # Get a question object question = get_by_urlsafe(question_key.urlsafe(), Question) return game.to_form(question.question, question.answers.values()) else: game.clear_game() g_form = game.to_form('No available questions, Game aborted!') game.key.delete() return g_form else: raise endpoints.NotFoundException('Game not found!')
def game_history(self, request): """ Gets the complete game history for a game. """ game = get_by_urlsafe(request.urlsafe_game_key, Game) return GameHistoryForms( items=[get_by_urlsafe(gh, GameHistory).to_form() for gh in game.history])
def post(self): user = get_by_urlsafe(self.request.get('user_key'), User) game = get_by_urlsafe(self.request.get('game_key'), Game) subject = 'Its your turn' body = 'Hello {}, its your turn now to play BattleShip Game. '\ 'The game key is: {}'.format(user.name, game.key.urlsafe()) mail.send_mail('noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), user.email, subject, body)
def take_turn(self, request): """ Take turn by answering a question in the triviagame. Requires urlsafe_trivia_game_key and answer.""" # Get the game in question game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame) if game.game_over: return game.to_form('Game already over!') game.rounds_remaining -= 1 turn_key = game.get_latest_turn() if not turn_key: return game.to_form('Please get a game before taking a turn!') turn = get_by_urlsafe(turn_key.urlsafe(), Turn) question = get_by_urlsafe(turn.question_key.urlsafe(), Question) if question.is_correct_answer(request.ans): result = "You are correct. " turn.set_correct_answer() points = question.value if turn.clues_used != 0: points -= 2**turn.clues_used turn.set_points(points) game.update_current_score(points) else: result = "You are not correct. " turn.set_answer_given(request.ans) turn.set_finished() turn.put() if game.rounds_remaining < 1: game.end_game() return game.to_form(result + ' Game over!') else: user_key = game.user question_key = game.get_question_from_pool() if question_key: # Create a new turn turn = Turn.new_turn(game.key, user_key, question_key) game.remove_question_from_pool(question_key) game.register_turn(turn.key) # Get a question object question = get_by_urlsafe(question_key.urlsafe(), Question) game.put() message = result + question.question return game.to_form(message, question.answers.values()) else: game.end_game() return game.to_form(result + ' No more questions, Game Over!')
def post(self): """Send an email to a User that it is their turn""" user = get_by_urlsafe(self.request.get('user_key'), User) game = get_by_urlsafe(self.request.get('game_key'), Game) subject = 'It\'s your turn!' body = '{}, It\'s your turn to play Battleships! The game key is: {}'. \ format(user.name, game.key.urlsafe()) logging.debug(body) mail.send_mail('noreply@{}.appspotmail.com'. format(app_identity.get_application_id()), user.email, subject, body)
def post(self): """Send email to the winning player comparing their score to average.""" user = get_by_urlsafe(self.request.get('user_key'), User) game = get_by_urlsafe(self.request.get('game_key'), Game) subject = 'Congratulations' body = 'Congratulations {}, for completing the game {}. '\ 'Your current score is now {}. The average score is {}. '\ 'Keep it up!'.format(user.name, game.key.urlsafe(), user.score, MemoryGameAPI._get_average_score()) logging.debug(body) mail.send_mail('noreply@{}.appspotmail.com'. format(app_identity.get_application_id()), user.email, subject, body)
def get_game(self, request): """Return the current game state.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return game.to_form('Time to make a move!') else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancel a non-completed game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) # user is needed for updating user rank user = game.key.parent().get().key if game.game_over is not True and game.cancelled is not True: game.cancelled = True # note in the game history that the game has been cancelled game.game_history.append("('guess': 'None', \ 'result': 'Game Cancelled', \ 'remaining': %d)" % game.attempts_remaining) game.put() # update user's rank - might be affected if % of cancelled games # goes over 10% difficulty = game.convert_int_to_difficulty(game.attempts_allowed) UserRank.set_user_rank(user, difficulty) return StringMessage(message="Game cancelled.") elif game.game_over is True: raise endpoints.BadRequestException( "You cannot cancel a game that is over." ) return StringMessage( message="You cannot cancel a game that is over." ) elif game.cancelled is True: raise endpoints.BadRequestException( "This game is already cancelled!" ) return StringMessage(message="This game is already cancelled!") else: return StringMessage(message="Something odd happened!")
def get_game_history(self, request): """Return the historical game moves.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return game.to_history_form() else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancel a game currently in progress""" current_user = self._getUser() game = get_by_urlsafe(request.urlsafe_game_key, Game) logging.info(game.player2) if not game.player2: if current_user.name != game.player1.get().name: raise endpoints.UnauthorizedException( "You are not a member of this game, you can't cancel it!") else: if current_user.name != game.player1.get().name and\ current_user.name != game.player2.get().name: raise endpoints.UnauthorizedException( "You are not a member of this game, you can't cancel it!") if game.game_over: raise endpoints.ConflictException( "This game is already over! It can't be cancelled!") game.cancelled = True game.game_over = True game.player1.get().gameKeysPlaying.remove(game.key.urlsafe()) game.player1.get().put() if game.player2: game.player2.get().gameKeysPlaying.remove(game.key.urlsafe()) game.player2.get().put() game.put() return game.to_form("Game Cancelled!")
def get_game_history(self, request): """Get game history""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return game.to_form('Game history') else: raise endpoints.NotFoundException('Game not found!')
def post(self, urlsafe_game_key, urlsafe_user_key): """Send a notification to player to play next.""" user = get_by_urlsafe(urlsafe_user_key, User) if user: send_turn_reminder_email(user, urlsafe_game_key)
def get_game_history(self, request): """Return user's move history for the game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return GameHistory(move=str(game.move_histories)) else: raise endpoints.NotFoundException('Game not Found!')
def cancel_game(self, request): """Cancels a Game entity and its children Turn entities. User can only cancel games in progress. This API operates under the assumpion that it's better to just cancel games outright instead of somehow marking them as deleted in the database. :param urlsafe_key (req): The state token for a game of Shut The Box. :type urlsafe_key: string :returns cancelled: True if the game entity and Turn entities are deleted from the datastore; False if the game entity in question is completed. :rtype cancelled: boolean :returns error: Helpful error message. :rtype error: string :raises: BadRequestException, ValueError""" game = get_by_urlsafe(request.urlsafe_key, Game) if game.game_over: return CancelResultForm( cancelled=False, error="Can't cancel games that are already completed.") # This deletes both the parent game and the children turns ndb.delete_multi(ndb.Query(ancestor=game.key).iter(keys_only=True)) return CancelResultForm(cancelled=True)
def get_game_history(self,request): """Get full game move history by urlsafe game key""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return StringMessage(message=str(game.move_history)) else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancel a user's active game. Checks to make sure the game is not already over or cancelled (deleted). Ensures users cannot delete a game that is not their own.""" user = User.query(User.name == request.user_name).get() game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.game_over: return game.to_form('This game is already over!') else: raise endpoints.NotFoundException( 'Game not found or game already cancelled') if not user: raise endpoints.NotFoundException( 'A user with that name does not exist!') if user.key != game.user: raise endpoints.ForbiddenException( 'You cannot cancel a game that is not your own!') else: # Cancelled games can't be high on the 'leaderboard'. game.end_game(False) game.key.delete() return game.to_form('This game has been canceled.')
def get_game_by_key(self, request): """Return one game by urlsafe_game_key.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') # Add a descriptive message to response. if game.game_result == 'win': msg = "You won!" elif game.game_result == 'lose': msg = "Sorry, the virtual player won this round." elif game.game_result == 'draw': msg = "The game was a draw." else: msg = "Unknown result. Perhaps you chose a weapon we don't " \ "know about." u_key = game.user user = u_key.get() return game.to_form('{} chose {} and the ' 'virtual player chose ' '{}. {}'.format(user.name, game.player_weapon, game.opponent_weapon, msg))
def get_game_history(self, request): """Return Game History""" game = get_by_urlsafe(request.urlsafe_game_key, Game) return GameHistoryForm(history=game.history) for u in users: scores = Score.query(Score.user == u.key).fetch tot_guesses = sum([score.guesses for score in scores])
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 ] )
def make_move(self, request): """Make a move. Return new game state""" game = get_by_urlsafe(request.urlsafe_game_key,Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: return game.to_form('Game already over!') if game.gameboard_fliped[request.first_card] or game.gameboard_fliped[request.second_card]: game.historys.append(History(card1=request.first_card, card2=request.second_card, result='Can not choose a fliped card.')) return game.to_form('Can not choose a fliped card.') game.steps += 1 if abs(game.gameboard_values[request.first_card] - game.gameboard_values[request.second_card]) == CORRECT_PAIR: game.pairs += 1 game.gameboard_fliped[request.first_card] = True game.gameboard_fliped[request.second_card] = True if game.pairs == NUMBER_OF_PAIRS: game.end_game(datetime.datetime.now()) msg = "You win!" else: msg = "Correct pairs!" else: msg = "Incorrect pairs!" game.historys.append(History(card1=game.gameboard_values[request.first_card], card2=game.gameboard_values[request.second_card], result=msg)) game.put() return game.to_form(msg)
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)
def get_game_history(self, request): """Get all history moves of a game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') return HistoryForms(items=[history.to_form() for history in game.historys])
def get_game(self, request): """Return the current game state.""" current_user = self._getUser() game = get_by_urlsafe(request.urlsafe_game_key, Game) logging.info(game) logging.info(str(current_user)) logging.info(game.player1) logging.info(game.player2) if game: if current_user.name == game.player1.get( ).name or current_user.name == game.player2.get().name: if game.isPlayer1_turn: return game.to_form( 'Game Found! Its your move: ' + game.player1.get().name) else: if game.player2: return game.to_form( 'Game Found! Its your move: ' + game.player2.get().name) else: return game.to_form( 'Still waiting for second player to join.') else: raise endpoints.UnauthorizedException( '''You are not a member of this game. You cannot pull its details.''') else: raise endpoints.NotFoundException('Game not found!')
def get_game_history(self, request): """Returns a summary of a game's guesses.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') return StringMessage(message=str(game.history))
def get_game_history(self, request): """Gets history of moves for a game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_status == 'Playing': return game.to_form('Game has not finished!') # initialize variables guesses = game.letters_guessed count = 1 forms = [] # go through all letters guessed except last one for letter in guesses: form = HistoryForm() if ''.join(game.word).find(letter) is -1: form.guess_status = 'Incorrect' else: form.guess_status = 'Correct' form.letter_guessed = letter form.attempt_number = count count = count + 1 forms.append(form) # attach game status to last move/form forms[-1].game_status = game.game_status return GameHistoryForm(items = forms)
def get_user_games(self, request): """Return the a list of game states for a user.""" user = get_by_urlsafe(request.urlsafe_user_key, User) if user is not None: print user.games games_list = [] for index, key in enumerate(user.games): try: game = key.get() except TypeError as e: print "Type error on index {}: {} ".format(index, e) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print exc_type, exc_obj else: if not game.game_over: games_list.append(game) return UserGameForms( user=user.to_form(), games=[game.to_form( '{name} is a player in this active game'. format(name=user.name)) for game in games_list] ) else: raise endpoints.NotFoundException('User not found!')
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') pos = 0 found = False game.letters_guessed += request.guess partial_word = list(game.partial_word_guessed) for l in list(game.target_word): if l == request.guess: found = True partial_word[pos]=l pos += 1 msg = '' if found: game.partial_word_guessed = ''.join(partial_word) game.guess_results += '1' if game.partial_word_guessed.find('.') <0: game.end_game(True) return game.to_form('You win!') msg = 'Good guess! word has a ' + request.guess else: game.guess_results += '0' game.attempts_remaining -= 1 msg = 'No {}\'s in this word'.format(request.guess) if game.attempts_remaining < 1: game.end_game(False) return game.to_form(msg + ' Game over!' + game.target_word) else: game.put() return game.to_form(msg)
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') """code added to check letter has not already been guessed""" if request.guess in game.lettersguessed: raise endpoints.BadRequestException('repeated letter') game.lettersguessed += request.guess hangmanprogress = '' failed = 0 for char in game.secret: if char not in game.lettersguessed: failed +=1 if failed == 0: game.end_game(True) return game.to_form('You win!') if request.guess in game.secret: msg = 'Your letter is in the secret word' game.history.append((request.guess," found")) """ append the move to the game history""" else: game.attempts_remaining -= 1 game.history.append((request.guess,"not in word")) """ appned the move to the game history""" msg = 'letter not there, another piece to the hangman' if game.attempts_remaining ==0: game.end_game(False) return game.to_form(msg + ' Game over!') else: game.put() return game.to_form(msg)
def get_game_history(self, request): """Retrieves an individual game history""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return HistoryForm(items=game.history) else: raise endpoints.NotFoundException('Game not found!')
def make_guess(self, request): """Makes a guess. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') if (request.guess1 < 0 or request.guess1 > std_num_pairs * 2 - 1) or\ (request.guess2 < 0 or request.guess2 > std_num_pairs * 2 -1): return game.to_form('Card numbers needs to be between 0 and %s' % (2 * game.num_pairs - 1)) if request.guess1 == request.guess2: return game.to_form('Two guesses need to be for different cards') return game.make_guess(request.guess1, request.guess2)
def cancel_game(self, request): """Cancel a game in progress""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game and not game.game_over: game.end_game(won=False) game.key.delete() return StringMessage( message='Game {} has been cancelled'.format( request.urlsafe_game_key)) elif game and game.game_over: return StringMessage( message='Game {} is already over!'.format( request.urlsafe_game_key)) else: raise endpoints.NotFoundException('Game not found.')
def get_game_history(self, request): """Return user's move history for the game. Args: request: The GET_GAME_REQUEST object, which includes the game's urlsafe_game_key. Returns: GameHistory: The list of moves with the results for each move. Raises: endpoints.NotFoundException: If no game is found for the urlsafe_game_key. """ game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return GameHistory(move=str(game.move_history)) else: raise endpoints.NotFoundException('Game not Found!')
def get_game(self, request): """Return the current game state.""" try: game = get_by_urlsafe(request.urlsafe_game_key, Game) is_game_over = game.game_over if is_game_over: return game.to_form('Game Over!') elif not is_game_over: return game.to_form('Time to make a move!') else: raise endpoints.NotFoundException('Game not found!') except Exception: raise endpoints.BadRequestException( 'Invalid key, please try a real key.')
def cancel_game(self, request): """Cancel an active game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.game_over == False: # Cancel game game.game_over = True game.attempts_remaining = 0 game.put() return StringMessage(message='Game successfully cancelled!') else: raise endpoints.BadRequestException('Game is already over.') else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Return the current game state.""" try: game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over is False: delete_confirmation = game.deleted_game_form( message='Game cancelled!') game.key.delete() return delete_confirmation else: return game.deleted_game_form(message='Game is already over.' \ ' Cannot cancel.') except Exception: raise endpoints.BadRequestException( 'Invalid key, please try a real key.')
def get_match_history(self, request): """Return list of Game plays in Match""" match = get_by_urlsafe(request.match_key, Match) if not match: raise endpoints.ConflictException( 'Cannot find match with key {}'.format(request.match_key)) games = Game.query(ancestor=match.key).order(Game.start_time) return StringMessages(message=[ '{}:{}, {}:{}. {}'.format(match.player_1_name, game.player_1_move, match.player_2_name, game.player_2_move, game.result) for game in games ])
def delete_game(self, request): """Via urlsafe_game_key you can delete in here""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.finished_status == False: game.key.delete() return StringMessage( message='Game with the following urlsafe key is deleted: {}' .format(request.urlsafe_game_key)) else: raise endpoints.NotFoundException( 'Game is over and cannot be deleted') else: raise endpoints.NotFoundException( 'Game not found! Cannot be deleted!')
def cancel_game(self,request): """Cancel unfinished game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.game_over: return Message(message = "Completed Game cannot be deleted.") else: try: game.key.delete() except Exception: raise endpoints.InternalServerErrorException( 'Error in cencelling the game') return Message(message = "Game Deleted") else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancel an active game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game and not game.game_over: game.canceled_game() game.key.delete() return StringMessage(message='Game with key: {} deleted.'.format( request.urlsafe_game_key)) elif game and game.game_over: raise endpoints.BadRequestException( 'Cannot cancel a completed game!') else: raise endpoints.NotFoundException('That game does not exist!')
def get_player_hand(self, request): """Get players hand""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: raise endpoints.ForbiddenException( 'Illegal action: Game is already over.') player = get_player_by_game(request.username, game) if player: return PlayerHandForm(hand=str(player.hand), matches=str(player.matches)) else: raise endpoints.NotFoundException('Player not found!')
def make_move(self, request): """Make a move and return a game state with message.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.status != 'NEW': raise endpoints.ForbiddenException( 'Illegal action: Game is already over.') if request.guess == game.who_says: game.do_move() return game.to_form('You win!') else: game.status = 'LOST' game.put() return game.to_form('You lost.')
def get_game_history(self, request): """Return a list of guesses made throughout the course of a completed game as well as the end result of the game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.game_over: return game.to_form_game_history( 'Thanks for playing, Pelmanism.') elif game.cancelled: return game.to_form_game_history( 'The game has been cancelled!') else: return game.to_form_game_history('The game is not over yet!') else: raise endpoints.NotFoundException('Game not found!')
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') if game.game_over: raise endpoints.NotFoundException('Game already over') user = User.get_user_by_name(request.user_name) if user.key != game.next_move: raise endpoints.BadRequestException('It\'s not your turn!') # Just a dummy signifier, what type of symbol is going down x = True if user.key == game.user_x else False move = request.move # Verify move is valid size = game.board_size * game.board_size - 1 if move < 0 or move > size: raise endpoints.BadRequestException('Invalid move! Must be between' '0 and %s ' % size) if game.board[move] != '': raise endpoints.BadRequestException('Invalid move!') game.board[move] = 'X' if x else 'O' # Append a move to the history game.history.append(('X' if x else 'O', move)) game.next_move = game.user_o if x else game.user_x # Check if there's a winner winner = check_winner(game.board, game.board_size) # If there's winner end game if winner: game.end_game(user.key) else: # If there's no winner and game board is full end game with tie if check_full(game.board): # Game tied game.end_game() else: # If game is still ongoing, send remainder email to player taskqueue.add(url='/tasks/send_move_email', params={'user_key': game.next_move.urlsafe(), 'game_key': game.key.urlsafe()}) game.put() # If game is over, update memcache if game.game_over: taskqueue.add(url='/tasks/update_finished_games') return game.to_form()
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: if game.user1_won: return game.to_form('Game already over! Player 1 Won') elif game.user2_won: return game.to_form('Game already over! Player 2 Won') else: return game.to_form('Game already over! It is a draw') previous_board_position = game.board_position.split(',') new_board_position = request.move.split(',') validation = TicTacToeApi._validate_board_position( new_board_position, previous_board_position) if validation.valid == False: return game.to_form(validation.message) response_message = validation.message if TicTacToeApi._check_for_win(new_board_position, 'X'): response_message = "Player 1 won!" game.end_game(user1_won=True, user2_won=False, user1_lost=False, user2_lost=True) elif TicTacToeApi._check_for_win(new_board_position, 'O'): response_message = "Player 2 won!" game.end_game(user1_won=False, user2_won=True, user1_lost=True, user2_lost=False) elif game.moves == 9: response_message = "It is a draw!" game.end_game(user1_won=False, user2_won=False, user1_lost=False, user2_lost=False) game.board_position = request.move game.moves = game.moves + 1 game.put() if game.game_over: taskqueue.add(url='/tasks/cache_average_moves_per_game') return game.to_form(response_message)
def cancel_game(self, request): """Cancel a game""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A user with that name does not exist!') game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: raise endpoints.BadRequestException( 'Sorry, you can\'t delete a completed game.') if user.key != game.user: raise endpoints.BadRequestException( 'Sorry, you\'re not authorized to cancel this game.') game.cancelled = True game.put() return game.to_form('Game cancelled')
def make_game_easier(self, request): """Given a number, automatically match same count of pairs and return match histories""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: raise endpoints.ForbiddenException('Illegal action: Game is already over.') hint_num = request.hint_num if hint_num <= 0: raise endpoints.ForbiddenException('Illegal action: Can not receive a negative number.') if hint_num * 2 >= 52 - game.matched: raise endpoints.ForbiddenException('Illegal action: Can not use hint to win, try a smaller number.') hint_histories = GameLogic.make_game_easier(game=game, hint_num=hint_num) return HistoryForms(items=[h.to_form() for h in hint_histories])
def get_game_history(self, request): """Return a Game's move history""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') return StringMessage(message=str("Player1 total moves: " + str(game.player1_letter_guess) + " Player1 guessed these letters correctly: " + str(game.player1_word_right) + " Correct word to guess was: " + str(game.player2_word) + " Player2 total moves: " + str(game.player2_letter_guess) + " Player2 guessed these letters correctly: " + str(game.player1_word_right) + " Correct word to guess was: " + str(game.player1_word)))
def show_board(self, request): """Display a board state""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') board_key = getattr(game, request.board) board = board_key.get() board_form = board.to_form() board_list = [ board_form.row_0, board_form.row_1, board_form.row_2, board_form.row_3, board_form.row_4, board_form.row_5, board_form.row_6, board_form.row_7, board_form.row_8, board_form.row_9 ] return StringMessages(items=[str(i) + \ ": " + board_list[i] for i in range(len(board_list))])
def cancel_game(self, request): """Cancels a game if not finished and user is a game member""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') game = get_by_urlsafe(request.urlsafe_game_key, Game) if user.key == game.user_name_x or user.key == game.user_name_o: if not game.game_over: game.key.delete() return game.to_form("Game cancelled!") else: return game.to_form("Sorry, this game is fnished!") else: return game.to_form("Sorry, {} can't cancel this game".format( user.name))
def make_connect_four_move(self, request): """player makes a connect four move""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over == True: return StringMessage(message="Game is over") if game.connect_4_turn == False: return StringMessage(message="Guess a word!") # Player makes connect four move, move is logged game.player_move([request.row, request.slot], "player_1") game.moves.append(str(request.row) + " " + str(request.slot)) game.move_count += 1 game.connect_4_turn = False game.put() return StringMessage(message=game.connect_four_response)
def cancel_match(self, request): """Cancel an active match""" match = get_by_urlsafe(request.match_key, Match) if not match: raise endpoints.ConflictException( 'Cannot find match with key {}'.format(request.match_key)) if not match.is_active: raise endpoints.ConflictException('Match already inactive') match.games_remaining = 0 match.is_active = False match.put() return StringMessage( message='Match {} cancelled'.format(request.match_key))
def get_game_history(self, request): """Return list of moves play in Game""" game = get_by_urlsafe(request.game_key, Game) # check game key if not game: raise endpoints.ConflictException( 'Cannot find game (key={})'.format(request.game_key)) moves = PlayerMoves.query(ancestor=game.key).order(PlayerMoves.round) return StringMessages(message=[ 'Round {}, {}:{}, {}:{}.'.format( move.round, game.player_1_name, move.player_1_move, game.player_2_name, move.player_2_move) for move in moves ])
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return endpoints.BadRequestException('Game is already over!') letterInWord = False if request.guess.isalpha(): if request.guess == game.target: msg = 'You win! Word was %s' % game.target updateHistory(game, request.guess, msg) game.end_game(True) return game.to_form(msg) else: if len(request.guess) == 1: for i, c in enumerate(game.target): if request.guess.upper( ) == c and i not in game.guessed_letters: game.guessed_letters.append(i) letterInWord = True else: raise endpoints.BadRequestException( 'Guess must be a single character or the word!') else: raise endpoints.BadRequestException('Guess must be all letters!') if len(game.guessed_letters) == len(game.target): msg = 'You win! Word was %s' % game.word_progress() updateHistory(game, request.guess, msg) game.end_game(True) return game.to_form(msg) if letterInWord: msg = 'Letter was in the word! Word progress: %s' else: msg = 'Letter was not in the word! Word progress: %s' game.attempts_remaining -= 1 if game.attempts_remaining < 1: msg = 'Game over!' updateHistory(game, request.guess, msg) game.end_game(False) return game.to_form(msg) else: updateHistory(game, request.guess, msg % game.word_progress()) return game.to_form(msg % game.word_progress())
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) #user = User.query(User.name == request.user).get() user = User.get_user_by_name(request.user) if game.game_over: return game.to_form('Game already over!') elif game.game_cancelled: return game.to_form('This Game is cancelled') if game.user_o == user.key: letter = 'O' else: letter = 'X' if user.key != game.next_move: raise endpoints.BadRequestException('It\'s not your turn!') if request.move > 8: raise endpoints.BadRequestException( 'It\'s out or range. Your move should be in 0 to 8') if isSpaceFree(game.board, request.move): game.board[request.move] = letter #game.moves.insert(request.move, letter) game.history.append((letter, request.move)) game.next_move = game.user_x if (game.user_o == user.key) else game.user_o if isWinner(game.board, letter): game.end_game(user.key) return game.to_form('You won the Game') else: if isBoardFull(game.board): game.end_game(False) return game.to_form('Game Tie') else: game.put() return game.to_form( 'You have taken good position, let wait for the oponent' ) else: #return game.to_form('This is not a Free space to move') raise endpoints.BadRequestException( 'This is not a Free space to move')
def make_move(self, request): """Makes a move. Returns a game state with message. """ game = get_by_urlsafe(request.urlsafe_game_key, Game) #check if the game is over, update the score list if needed if evaluate(game.state): outcome = evaluate(game.state) if outcome == "O": msg = "Win" else: msg = "Lose" game.end_game(msg) game.game_over = True game.put() else: if "-" not in game.state: game.end_game("Draw") game.game_over = True if game.game_over: return game.to_form('Game already over!') #check if it is player's turn if game.player: if request.move not in range(0,9): raise endpoints.BadRequestException('Invalid Move') if game.state[request.move] != "-": raise endpoints.BadRequestException('Invalid Move') #update the board state board = list(game.state) board[request.move] = "O" game.state = ''.join(board) #update movecount game.movecount += 1 #evaluate the result if evaluate(game.state): game.end_game("Win") return game.to_form('You win!') if "-" not in game.state: game.end_game("Draw") return game.to_form('This is a Draw.') msg = "AI's turn" game.history() game.player = False game.put() return game.to_form(msg) else: msg = "This is not your turn" return game.to_form(msg)
def get_game_history(self, request): """Return game history.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: # logging.info(game.history) items = [] for history in game.history: items.append( HistoryForm(sequence=history['seq'], player=history['player'], move=history['move'], result=history['result'])) # logging.info(items) return HistoryForms(items=items) else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancels the specified game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.cancelled: raise endpoints.ConflictException( """This game has already been\ cancelled!""") if game.game_over: raise endpoints.ConflictException( """This game is already over.\ You cannot cancel it!""") game.cancelled = True game.end_game(True) return game.to_form('Game cancelled!') else: raise endpoints.NotFoundException('Game not found!')
def get_game_history(self, request): """ Get the move history for a game. Args: request: A GET_GAME_REQUEST object containing the URL safe game ID. Returns: TicTacToeGameHistoryForm: A form representation of the move history. Raises: endpoints.NotFoundException: If the game is not found. """ game = get_by_urlsafe(request.urlsafe_game_key, TicTacToeGame) if not game: raise endpoints.NotFoundException('Game not found!') return game.get_game_history_form()
def make_move(self, request): '''Makes a move. Returns a game state with message''' game = get_by_urlsafe(request.urlsafe_game_key, Game) logging.debug('make_move game %s', game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: return game.to_form() try: game.take_action(request.action) except NotImplementedError as e: raise endpoints.BadRequestException(e) return game.to_form()