Пример #1
0
def kill():
    try:
        msg = request.json["msg"].upper()
        killer = Player.all().filter('username ='******'game =', game)\
            .filter('killer =', killer)\
            .filter('is_complete =', False).get()
        if msg == old_game_history_success.confirm_msg:
            will_be_last_kill = None
            if GameHistory.all().filter("game =", game).filter("is_complete =", False).count() == 2:
                will_be_last_kill = True
            old_target = old_game_history_success.target
            old_game_history_success.is_complete = True
            old_game_history_success.put()
            old_game_history_failure = GameHistory.all()\
                .filter('game =', game)\
                .filter('killer =', old_target)\
                .filter('is_complete =', False).get()
            old_game_history_failure.is_complete = True
            old_game_history_failure.put()
            if will_be_last_kill:
                game_player = GamePlayer.all().filter('game =', game).filter('player =', killer).get()
                game_player.is_winner = True
                game_player.put()
                return jsonify({"success": True, "info": "Your enemy has been slain! "})
            new_target = old_game_history_failure.target
            GameHistory(killer=killer, target=new_target, game=game, is_complete=False, confirm_msg=msg_generator()).put()
            return jsonify({"success": True, "info": "Your enemy has been slain! "})
        else:
            return jsonify({"success": False, "info": "The message is incorrect. Are you trying to game the system?!"})
    except:  # TODO: please handle exceptions in a more proper way
        return jsonify({"success": False, "info": "Something is fundamentally wrong. ", "Data received by server": str(request.data)})
Пример #2
0
    def new_game(self, request):
        """Creates new game"""
        player_one = User.query(User.name == request.player_one_name).get()
        player_two = User.query(User.name == request.player_two_name).get()
        if not player_one:
            raise endpoints.NotFoundException('Player one "' +
                                              request.player_one_name +
                                              '" does not exist!')

        if not player_two:
            raise endpoints.NotFoundException('Player two "' +
                                              request.player_two_name +
                                              '" does not exist!')

        game = Game.new_game(player_one.key, player_two.key,
                             request.freak_factor)

        # Increment active count of games
        taskqueue.add(url='/tasks/increment_active_games')

        message = "Game created successfully"
        game_history = GameHistory(parent=game.key)
        game_history.history.append(game)
        game_history.messages.append(message)
        game_history.put()

        return game.to_form(message)
Пример #3
0
 def get_game_history(self, request):
     """Returns the move history for a specified game."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         game_history = (GameHistory.query(GameHistory.game == game.key)
                                    .order(GameHistory.turn))
         if game_history:
             return GameHistory.to_form(game_history)
         else:
             raise endpoints.NotFoundException(
                 'No bids have been raised for this game yet')
     else:
         raise endpoints.NotFoundException('Game not found!')
    def _capture_game_snapshot(game, char):
        # game history is per game, so parent should be game and not the user
        # game history id
        history_id = GameHistory.allocate_ids(size=1, parent=game.key)[0]

        # game history key generated using history_id and game as its ancestor
        history_key = ndb.Key(GameHistory, history_id, parent=game.key)

        game_history = GameHistory(key=history_key,
                                   step_char=char,
                                   game_snapshot=game)
        # save game history
        game_history.put()
Пример #5
0
    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!')

        if (game.whos_turn == 1 and
                game.player_one.get().name != request.player_name) or \
           (game.whos_turn == 2 and
                game.player_two.get().name != request.player_name):
            return game.to_form('Please wait your turn!')

        try:
            game.move(request.move_row, request.move_col)
            game.put()

        except ValueError as error:
            return game.to_form(error.message)

        if game.game_over is True:
            taskqueue.add(url='/tasks/decrement_active_games')
            message = "Thank you for playing. " + \
                      request.player_name + " has won the game."
        else:
            message = "Move accepted. Please wait for your next turn."

        game_history = GameHistory.query(ancestor=game.key).get()
        game_history.history.append(game)
        game_history.messages.append(message)
        game_history.put()

        return game.to_form(message)
Пример #6
0
    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!')
        
        """Hangman Game Logic"""
        
        word = list(request.guess)[0]
        target = list(game.target)
        miss = list(game.miss)
        current = list(game.current)
        valid = False
        inMissList = False
        message = ''
        game_history = GameHistory.query(GameHistory.game == game.key).get()

        """Check whether the input word is in miss list"""
        for index,t in enumerate(miss):
            if t == word:
                inMissList = True
                game.attempts_remaining -= 1
                message = 'You already guessed that letter and it is not right! Try again, but a new one this time.'
                break
        

        """Check whether the input word is in target list"""
        for index,t in enumerate(target):
            if word == t:
                valid = True
                message = 'Correct!'
                current[index] = word
                break

        game.current = ''.join(current)

        """Update miss list"""
        if valid == False and inMissList == False:
            game.attempts_remaining -= 1
            miss.append(word)
            game.miss =''.join(miss)
            game.put()
            message = 'Nice try! But it is not a valid word'

        """Compare between current and target"""

        if game.attempts_remaining < 1:
            game_history.addHistory(valid,word,'lose')
            game.end_game(False)
            message = 'Game over!'
        else:
            if target == current:
                game.end_game(True)
                game_history.addHistory(valid,word,'win')
                message = 'You Win!'
            else:
                game_history.addHistory(valid,word,'pending') 
            game.put()

        return game.to_form(message)
Пример #7
0
 def get_game_history(self,request):
     """Return game history for a specific game"""
     game = get_by_urlsafe(request.urlsafe_game_key,Game)
     if not game:
         raise endpoints.NotFoundException('Game not found!')
     gameHistory = GameHistory.query(GameHistory.game == game.key).get()
     return HistoryForms(items=[history.to_form() for history in gameHistory.histories])
Пример #8
0
    def cancel_game(self, request):
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found!')

        if game.game_over is True:
            raise endpoints.ForbiddenException(
                'You can not cancel this game as it is already over!')

        # Save the game.
        # A game with no winner and with game_over=True is a cancelled game.
        game.game_over = True
        game.put()

        # Decrement active games
        taskqueue.add(url='/tasks/decrement_active_games')

        message = "The game was cancelled successfuly."

        # Update game history
        game_history = GameHistory.query(ancestor=game.key).get()
        game_history.history.append(game)
        game_history.messages.append(message)
        game_history.put()

        return StringMessage(message=message)
Пример #9
0
 def get_game_history(self, request):
     """Return game history for a specific game"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.NotFoundException('Game not found!')
     gameHistory = GameHistory.query(GameHistory.game == game.key).get()
     return HistoryForms(
         items=[history.to_form() for history in gameHistory.histories])
Пример #10
0
    def new_game(self, request):
        """Creates new game"""
        user = User.query(User.name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                'A User with that name does not exist!')
        try:
            game = Game.new_game(user.key, request.word)
            GameHistory.new_game_history(game.key)
        except ValueError:
            raise endpoints.BadRequestException('Invalid word')

        # Use a task queue to update the average attempts remaining.
        # This operation is not needed to complete the creation of a new game
        # so it is performed out of sequence.
        taskqueue.add(url='/tasks/cache_average_attempts')
        return game.to_form('Good luck playing Hangman!')
Пример #11
0
    def new_game(self, request):
        """Creates new game"""
        user = User.query(User.name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                    'A User with that name does not exist!')
        try:
            game = Game.new_game(user.key, request.word)
            GameHistory.new_game_history(game.key)
        except ValueError:
            raise endpoints.BadRequestException('Invalid word')

        # Use a task queue to update the average attempts remaining.
        # This operation is not needed to complete the creation of a new game
        # so it is performed out of sequence.
        taskqueue.add(url='/tasks/cache_average_attempts')
        return game.to_form('Good luck playing Hangman!')
def get_game_history(game):
    # query by kind
    query = GameHistory.query(ancestor=game.key)

    # order by timestamp
    query.order(GameHistory.step_timestamp)

    return query.fetch()
Пример #13
0
 def get_game_history(self, request):
     """
     This function returns the chronological game history based on a url safe game key.
     The 'turn' value uses computer counting, so the first move done will have a turn value
     of 0.
     """
     histories = GameHistory.query(GameHistory.game_url_safekey ==
                                   request.urlsafe_game_key).order(GameHistory.turn).fetch()
     return GameHistories(items=[history.to_form() for history in histories])
Пример #14
0
class SolitaireAPI(remote.Service):

    @endpoints.method(request_message=USER_REQUEST,
                      response_message=StringMessage,
                      path='user',
                      name='create_user',
                      http_method='POST')
    def create_user(self, request):
        """Create a new user"""

        # Check that user already exists
        if User.query(User.user_name == request.user_name).get():
            raise endpoints.ConflictException(
                "A user with that name already exists")
        # Create a new user
        user = User(user_name=request.user_name, email=request.email)
        user.put()

        return StringMessage(
            message="User {} created!".format(request.user_name))

    @endpoints.method(request_message=NEW_GAME_REQUEST,
                      response_message=GameForm,
                      path='game',
                      name='new_game',
                      http_method='POST')
    def new_game(self, request):
        """Create a new game"""
        user = User.query(User.user_name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                "A user with that name does not exist")

        game = SolitaireGame(None, None, None, None, False)
        game.new_game()

        # Convert card stacks to JSON
        game_json = to_json(game)
        try:
            game_db = Game.new_game(user=user.key,
                                    piles=game_json['piles'],
                                    foundations=game_json['foundations'],
                                    deck=game_json['deck'],
                                    open_deck=game_json['open_deck'])
        except Exception, e:
            logging.error(str(e))

        # Save game history
        GameHistory.new_history(game=game_db.key,
                                sequence=game_db.moves,
                                game_over=game_db.game_over,
                                piles=game_db.piles,
                                foundations=game_db.foundations,
                                deck=game_db.deck,
                                open_deck=game_db.open_deck)

        return game_db.to_form('New game created!')
Пример #15
0
    def get_game_history(self, request):
        """Return every moves of the game"""
        game_histories = GameHistory.query(ancestor=ndb.Key(
            urlsafe=request.urlsafe_game_key)).fetch()
        if not game_histories:
            raise endpoints.NotFoundException("No Game Histories found")

        return GameHistoryForms(
            items=[history.to_form() for history in game_histories])
Пример #16
0
 def cancel_game(self, request):
     """This function delete a game.
     Input: Game safe url key"""
     game = utils.get_by_urlsafe(request.urlsafekey, Game)
     if game.status == "over":
         raise endpoints.ConflictException('Cannot delete a Game over')
     for hist in GameHistory.query(GameHistory.game == game.key):
         hist.key.delete()
     game.key.delete()
     return MessageForm(message=" Game cancelled")
Пример #17
0
    def getUserGameHistory(self, request):
      """ returns all moves made and corresponding game state per move for a given user """
      game_history = GameHistory.query(GameHistory.game_id == request.game_id, GameHistory.user_id == request.user_id).fetch()   
      game_history_forms = GameHistoryForms(moves = [ move.to_form() for move in game_history ])

      if len(game_history) == 0:
        game_history_forms = [GameHistoryForm(user_id="There's No Games For Selected User ID")]
        return GameHistoryForms(moves=game_history_forms)

      return game_history_forms 
Пример #18
0
def get_game(game_id):
    game = Game.get_by_id(int(game_id))
    if game is None:
        return jsonify({'success': False, 'info': None})
    info = to_dict(game)
    people = [game_player.player.username for game_player in game.players]
    info['success'] = True
    info['participants'] = str(people)
    game_history = GameHistory.all().filter('game =', game).filter('is_complete =', False)
    info['survivors'] = [record.killer.username for record in game_history]
    return jsonify({'success': True, 'info': info})  # does not render a page, just returns a Json
Пример #19
0
    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!')
        """Hangman Game Logic"""

        word = list(request.guess)[0]
        target = list(game.target)
        miss = list(game.miss)
        current = list(game.current)
        valid = False
        inMissList = False
        message = ''
        game_history = GameHistory.query(GameHistory.game == game.key).get()
        """Check whether the input word is in miss list"""
        for index, t in enumerate(miss):
            if t == word:
                inMissList = True
                game.attempts_remaining -= 1
                message = 'You already guessed that letter and it is not right! Try again, but a new one this time.'
                break
        """Check whether the input word is in target list"""
        for index, t in enumerate(target):
            if word == t:
                valid = True
                message = 'Correct!'
                current[index] = word
                break

        game.current = ''.join(current)
        """Update miss list"""
        if valid == False and inMissList == False:
            game.attempts_remaining -= 1
            miss.append(word)
            game.miss = ''.join(miss)
            game.put()
            message = 'Nice try! But it is not a valid word'
        """Compare between current and target"""

        if game.attempts_remaining < 1:
            game_history.addHistory(valid, word, 'lose')
            game.end_game(False)
            message = 'Game over!'
        else:
            if target == current:
                game.end_game(True)
                game_history.addHistory(valid, word, 'win')
                message = 'You Win!'
            else:
                game_history.addHistory(valid, word, 'pending')
            game.put()

        return game.to_form(message)
Пример #20
0
 def _cache_game_move(game, position, message, urlsafe_game_key):
     """Populates memcache with the actual moves of the Game"""
     if not game.game_over:
         history = memcache.get(MEMCACHE_GAME_HISTORY_PREFIX +
                                urlsafe_game_key) or []
         game_history = GameHistory(username=game.current_player,
                                    position=position,
                                    message=message)
         history.append(game_history)
         memcache.set(MEMCACHE_GAME_HISTORY_PREFIX + urlsafe_game_key,
                      history)
Пример #21
0
    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 finished
        if game.game_over:
            return game.to_form('Game already finished!')

        # Only alphabetic character is allowed
        if not request.guess.isalpha():
            return game.to_form('Only alphabetic character is allowed!')
        guess = request.guess.upper()

        # Only one character is allowed
        if len(guess) != 1:
            return game.to_form('Only one character allowed')

        # We will check if the character is already used
        game_key = ndb.Key(Game, request.urlsafe_game_key)
        ls = GameHistory.query(ancestor=game_key).filter(
            GameHistory.guess == guess).count()
        if ls != 0:
            return game.to_form('Character already used' + guess)

        found = False
        temp = list(game.guess_word)
        temp_wimp = list(game.word_in_progress)
        for i, val in enumerate(temp):
            if val == guess:
                temp_wimp[i] = guess
                found = True
                msg = 'Key found ' + guess
                GameHistory.create_game_history(request.urlsafe_game_key,
                                                guess, found, i, 'Found')

        game.word_in_progress = ''.join(temp_wimp)

        if found is False:
            GameHistory.create_game_history(request.urlsafe_game_key, guess,
                                            found, -1, 'Not found')
            game.attempts_remaining -= 1
            msg = 'Character not found in word: ' + request.guess

        if game.word_in_progress == game.guess_word:
            game.end_game(True)
            msg = 'You win'

        if game.attempts_remaining < 1:
            game.end_game(False)
            GameHistory.create_game_history(request.urlsafe_game_key, guess,
                                            found, -1,
                                            'Not attempts remaining you lose')
            return game.to_form(msg + ' Game over!')
        else:
            game.put()
            return game.to_form(msg)
Пример #22
0
    def get_game_history(self, request):
        """Return the game history."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        # If the game dose't exist throw exception.
        if not game:
            raise endpoints.NotFoundException('Game not found!')

        game_key = ndb.Key(Game, request.urlsafe_game_key)
        return GameHistoryForms(items=[
            game_history.to_form() for game_history in GameHistory.query(
                ancestor=game_key).order(GameHistory.date_created)
        ])
Пример #23
0
    def game_history(self, request):

        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found!')

        game_history = GameHistory.query(ancestor=game.key).get()

        items = []
        for index, item in enumerate(game_history.history):
            items.append(item.to_form(game_history.messages[index]))

        return GameForms(items=items)
Пример #24
0
    def make_move(self, request):
        """
        Make a move.  This function requires a url safe game key and allows the user
        to make a guess as to whether the 3rd generated number is inside or outside
        the 1st and 2nd generated number.  The input for this MUST be either 'inside'
        or 'outside' or an error will be thrown.
        """

        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if request.guess != 'inside' and request.guess != 'outside':
            raise endpoints.BadRequestException('Must guess inside or outside')
        if game.game_over:
            return game.to_form('Game already over!')
        sorting_list = [game.first_random_number, game.second_random_number]
        sorting_list = sorted(sorting_list, key=int)
        first_random_number = sorting_list[0]
        second_random_number = sorting_list[1]
        third_random_number = game.third_random_number
        max_guess = game.max_guess
        turn = game.streak


        if first_random_number == second_random_number or \
                third_random_number == second_random_number or \
                third_random_number == first_random_number: # tie is auto lose
            msg = 'tie'

        elif first_random_number < third_random_number < second_random_number:
            msg = 'inside'
        elif third_random_number < first_random_number or \
                third_random_number > second_random_number:
            msg = 'outside'
        if request.guess != msg or msg == 'tie':
            alert = "Sorry, you lost!"
            game.end_game()

        elif request.guess == msg:
            alert = "You're correct!"
            # max + 1 because of computer counting.
            game.first_random_number = random.choice(range(1, max_guess+1))
            game.second_random_number = random.choice(range(1, max_guess+1))
            game.third_random_number = random.choice(range(1, max_guess+1))
            game.streak += 1
            game.put()

        history = GameHistory.new_record(game.key, request.urlsafe_game_key, \
                                            request.guess, turn, alert)
        history.put()

        return game.to_form(alert)
Пример #25
0
 def cancel_game(self, request):
     """Delete a game from the database"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         if not game.game_over:
             game_history = GameHistory.query(ancestor=game.key).fetch()
             for h in game_history:
                 h.key.delete()
             game.key.delete()
             return StringMessage(message="The game has been deleted!")
         else:
             raise endpoints.ForbiddenException(
                 "Not allowed to delete a completed game")
     else:
         raise endpoints.NotFoundException("Game not found")
Пример #26
0
def get_game_status():
    info = {"target": None, "in_game": False, "game_exists": False, "msg": None, "player_exists": False, "game_completed": False, "time_left": None}
    try:
        game = Game.get_by_id(int(request.args["game_id"]))
        if game is None:
            info["msg"] = "Game does not exists. "
            return jsonify(info)
        info["game_exists"] = True
        killer = Player.all().filter('username ='******'game =', game).filter('player =', killer).get()
        if player_in is None:
            info["msg"] = "Player trying to kill is not in this game. "
            return jsonify(info)
        info["in_game"] = True
        if GameHistory.all().filter("game =", game).filter("is_complete =", False).count() == 0:
            info["game_completed"] = True
            game_player = GamePlayer.all().filter('game =', game).filter('is_winner =', True).get()
            info["winner_name"] = str(game_player.player.username)
            return jsonify(info)
        to_kill_game_history = GameHistory.all().filter('killer =', killer).filter('game =', game).filter('is_complete', False).get()
        be_killed_game_history = GameHistory.all().filter('target =', killer).filter('game =', game).filter('is_complete', False).get()
        if to_kill_game_history is None:
            return jsonify(info)
        else:
            info["time_left"] = to_kill_game_history.assign_date + timedelta(hours=1)
            info["target"] = to_kill_game_history.target.username
            info["msg"] = be_killed_game_history.confirm_msg
            return jsonify(info)
    except:
        # info["time_left"] = str(datetime.datetime.now())
        info["msg"] = "Something is fundamentally wrong. "
        return jsonify(info)
Пример #27
0
    def make_a_move(self, request):
        """ This function enables a player to move during the race.
        Input: game safe url key, player username, number render by the Dice"""

        if request.dice not in diceValue:
            raise endpoints.NotFoundException('Invalid Dice Number')
        game = utils.get_by_urlsafe(request.game_urlsafekey, Game)
        if game.status != "start":
            raise endpoints.NotFoundException(
                'This game is either over or save!! Resume if saved')

        player = Position.query(
            Position.game == game.key,
            Position.player == utils.get_by_username(
                request.player).key).get()
        if not player.isPlayingNow:
            raise endpoints.NotFoundException(
                'This player does not have token to play now')

        # Who is  Player and who is  Opponent ? Current user is always the
        # PLAYER
        if game.player == player.player:
            opponent = Position.query(Position.game == game.key,
                                      Position.player == game.opponent).get()
        elif game.opponent == player.player:
            opponent = Position.query(Position.game == game.key,
                                      Position.player == game.player).get()
        # IMPORTANT !!!!
        # player and opponent are key objects in POSITION model

        # change position
        player.position = utils.move(player.position, request.dice)

        self._updateScore(game, player)

        # remove token
        player.isPlayingNow = False
        player.put()
        game_status = "Token False. Time for your opponent to play!"
        # Opponent is given token to play
        opponent.isPlayingNow = True

        msg = "Player %s played %s; Distance Moved:%s; Points earned: %s " % (
            request.player, request.dice, player.position, player.position)
        GameHistory(game=game.key, message=msg).put()

        # Opponent loose its position as first
        if player.position == opponent.position:
            opponent.position -= 1
        # GAME Over
        if player.position == 100:
            opponent.isPlayingNow = False
            game.gameOver(player)
            GameHistory(game=game.key,
                        message="Player %s WON" % request.player).put()
            game_status = "GAME OVER, YOU WON THE RACE!!!!!"

        opponent.put()
        return MakeMoveForm(
            player=request.player,
            dice=request.dice,
            position=player.position,
            score=Score.query(Score.game == game.key,
                              Score.player == player.player).get().score,
            status=game_status)
Пример #28
0
 def get_game_history(self, request):
     """This function returns all moves in a game."""
     game = utils.get_by_urlsafe(request.game_urlsafekey, Game)
     games = GameHistory.query(GameHistory.game == game.key).order(
         GameHistory.date)
     return ListGameHistory(history=[game.toForm() for game in games])
Пример #29
0
    def make_move(self, request):
        """Make a move"""
        action = request.action
        origin = request.origin
        destination = request.destination
        card_position = request.card_position

        # If action is MOVE, the source and destination
        # field cannot be empty
        if action == Action.MOVE:
            if not origin or not destination:
                raise endpoints.BadRequestException(
                    'Souce and Destination must not be empty for MOVE action')

            if not card_position:
                card_position = -1

        # If action is SHOW, the source field cannot be empty
        if action == Action.SHOW:
            if not origin:
                raise endpoints.BadRequestException(
                    'Souce must not be empty for SHOW action')

        # Load the game from DB
        game_db = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game_db:
            raise endpoints.NotFoundException("The Game does not exist")

        # If game is over, copy to form and return
        if game_db.game_over:
            return game_db.to_form('Game already over')

        # Create Python game object
        game = to_python(piles=game_db.piles,
                         foundations=game_db.foundations,
                         deck=game_db.deck,
                         open_deck=game_db.open_deck,
                         game_over=game_db.game_over)

        # Make the move

        # To track whether any cards are moved or upturned

        changed = False
        if action == Action.DEAL:
            game.deal()
            changed = True
            game_db.moves += 1
            game.print_game()

        if action == Action.MOVE:
            changed = game.move(origin=str(origin),
                                destination=str(destination),
                                card_position=card_position)
            if changed:
                game_db.moves += 1
            else:
                game.print_game()
                raise endpoints.BadRequestException("Illigal move. Try again.")

            game.print_game()

        if action == Action.SHOW:
            changed = game.show_top(str(origin))

            if changed:
                game_db.moves += 1
            else:
                game.print_game()
                raise endpoints.BadRequestException('Could not show the card.')

            game.print_game()

        # Convert the game to JSON format
        game_json = to_json(game)

        # If changed, update the fields and save in DB
        if changed:
            game_db.piles = game_json['piles']
            game_db.foundations = game_json['foundations']
            game_db.deck = game_json['deck']
            game_db.open_deck = game_json['open_deck']
            game_db.game_over = game_json['game_over']

            game_db.put()

            GameHistory.new_history(game=game_db.key,
                                    sequence=game_db.moves,
                                    game_over=game_db.game_over,
                                    piles=game_db.piles,
                                    foundations=game_db.foundations,
                                    deck=game_db.deck,
                                    open_deck=game_db.open_deck)

        if game_db.game_over:
            game_db.save_game()

        return game_db.to_form('Made a move')
Пример #30
0
    def makeMove(self, request):
      """ Asigns specific move to a user for a specific game_id, as long as its available
      It also checks if the move is valid, returning the appropiate message for each situation. It 
      also keeps track of every valid move made by a user """
      x = request.x   
      y = request.y
      game_id = request.game_id
      user_id = request.user_id

      game = Game.query(Game.game_id == game_id).get()
      queried_move = Move.query(Move.x == x, Move.y == y, 
                        Move.game_id == game_id).fetch(1)
      all_moves = Move.query(Game.game_id==game_id)

      if game == None :
        print("\n\nInvalid Move, Wrong Game ID\n\n")
        return StringMessage(message = "Invalid Move, Wrong Game ID" )
 
      winner_id = GuessANumberApi._check_winning_condition(game_id) 

      if winner_id != False and winner_id != "no_winners_yet":
        print("\n\n Game Won By {0} \n\n".format(winner_id))
        game.finish_game(winner_id, "game_won")
                    
        return StringMessage(message = "\n\n Game Won By {0} \n\n".format(winner_id), game_state="game_won", winner_id=winner_id)             

      available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch()
      
      if len(available_moves) == 0:
        print("\n\n Game Ended, No more moves left {0} \n\n".format(game_id))   
        game.finish_game(winner_id, "no_more_moves")

        return StringMessage(message = "\n\n Game Ended, No more moves left {0} \n\n".format(game_id), game_state="no_more_moves", winner_id=winner_id or "")               

      if user_id == None or user_id not in [game.player1, game.player2]:
        print("\n\nInvalid move parameters\n\n")
        return StringMessage(message = "Invalid Move, Wrong User ID" )

      if len(queried_move) == 0:
        print("\n\nInvalid move parameters\n\n")
        return StringMessage(message = "Invalid move parameters, Wrong Game ID or Move out of range" )

      if user_id == game.last_play_user_id:
        print("\n\n This Player already moved\n\n")
        return StringMessage(message = "Invalid move, This Player already moved" )        

      move = queried_move[0]
      if move.available != True:
        print("\n\nMove already done by: {0} \n\n".format(move.user_id))
        return StringMessage(message = "Move {0} has already been made by User with ID: : {1}"
                             .format(move.description, move.user_id) )        

      move.user_id = user_id
      move.available = False
      move.put()

      game.last_play_user_id = user_id
      game.put()

      GuessANumberApi._show_game_picture(game_id)
      state = GuessANumberApi._check_game_state(game_id)

      if state == False:
        state = "no_winners_yet"

      string_move = "[{0},{1}]".format(move.x, move.y)
      saved_move = GameHistory(game_id = game.game_id, user_id = user_id, move = string_move, game_state = state)
      saved_move.put()

      print(saved_move)

      # Final Winning Check
      winner_id = GuessANumberApi._check_winning_condition(game_id) 

      if winner_id != False and winner_id != "no_winners_yet":
        print("\n\n Game Won By {0} \n\n".format(winner_id))
        game.finish_game(winner_id, "game_won")

        return StringMessage(message = "\n\n Game Won By {0} \n\n".format(winner_id), game_state="game_won", 
                             winner_id=winner_id)             

      return StringMessage(message = "New Move {0} assigned to {1} Game ID: {2}, x:{3} and y:{4}"
                           .format(move.description, user_id, game_id, x, y), game_state="game_active", 
                           winner_id=""  )
Пример #31
0
    def raise_bid(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        # Validity logic
        if game.game_over or game.cancelled:
            return game.to_form('Game already over!')

        bidding_player = Player.query(
            Player.game == game.key,
            Player.order == game.bid_player % game.players + 1).get()

        bidding_user = bidding_player.user.get()

        if bidding_user.password != request.password:
            return game.to_form('Invalid password.')

        if (game.bid_face == game.die_faces and
                game.bid_total == game.dice_total * game.players):
            return game.to_form('Already at max possible bid. Bid cannot be '
                                'rasied. Call liar to end game.')

        if request.bid_face < 1 or request.bid_face > game.die_faces:
            return game.to_form('Invalid face number. Must be between 1 '
                                'and ' + str(game.die_faces) + '.')

        if request.bid_face < game.bid_face:
            return game.to_form('Invalid dice face. Must be greater than or '
                                'equal to the current dice face bid:%d.' %
                                (game.bid_face))

        if (request.bid_face == game.bid_face and
                request.bid_total <= game.bid_total):
            return game.to_form('Invalid bid. If not raising dice face, '
                                'must raise dice total')

        # Game logic
        game.bid_face = request.bid_face
        game.bid_total = request.bid_total
        game.turn += 1
        # Update player info
        if game.bid_player == game.players:
            game.bid_player = 1
        else:
            game.bid_player += 1
        game.put()

        # Record History
        game_history = GameHistory(game=game.key,
                                   turn=game.turn,
                                   player=bidding_player.key,
                                   bid_face=game.bid_face,
                                   bid_total=game.bid_total)
        game_history.put()

        # Find the next player
        next_player = Player.query(
            Player.game == game.key,
            Player.order == game.bid_player % game.players + 1).get()

        next_user = next_player.user.get()

        if next_user.email is not None:
            task_params = ({
                'email': next_user.email,
                'user_name': next_user.user_name,
                'game_key': game.key.urlsafe(),
                'dice': Dice.query(Dice.player == next_player.key)
                            .order(Dice.face),
                'bid_face': game.bid_face,
                'bid_total': game.bid_total,
                'bid_player': bidding_user.user_name})

            taskqueue.add(
                params=task_params,
                url='/tasks/send_your_turn'
            )

        return game.to_form('Current bid is now face: %d, number %d. It is '
                            '%s\'s turn.' % (request.bid_face,
                                             request.bid_total,
                                             next_user.user_name))
Пример #32
0
 def get_game_history(self,request):
     """Return moves for specified game"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     return GameHistoryForms(items = [record.to_form() for record in \
        GameHistory.query(GameHistory.game == game.key).order(GameHistory.movecount)])