Пример #1
0
 def create_user(self, request):
     """Create a User. Requires a unique username"""
     if User.query(User.name == request.user_name).get():
         raise endpoints.ConflictException(
             'A User with that name already exists!')
     user = User(name=request.user_name, email=request.email)
     user.put()
     return StringMessage(
         message='User {} created!'.format(request.user_name))
Пример #2
0
    def getAnnouncement(self, request):
        """Return Announcement from memcache."""
        # TODO 1
        # return an existing announcement from Memcache or an empty string.

        announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY)
        if not announcement:
            announcement = ""
        return StringMessage(data=announcement)
Пример #3
0
 def cancel_game(self, request):
     """Cancel a game in progress and penalize player"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game and not game.game_over:
         game.attempts += 3
         game.end_game(False)
         game.key.delete()
         return StringMessage(
             message=
             'Game with key{} has been cancelled and player penalized 3 points'
             .format(request.urlsafe_game_key))
     elif game and game.game_over:
         return StringMessage(message='Game with key{} is already over!'.
                              format(request.urlsafe_game_key))
     else:
         raise endpoints.NotFoundException(
             'A game with this key was not found. It may have been cancelled.'
         )
Пример #4
0
 def add_data(self, request):
     """Add game data. Administrative."""
     gData = GameData.new_game_data(sayer_category=request.sayer_category,
                                    sayer=request.sayer,
                                    saying=request.saying,
                                    hints=request.hints)
     gData.put()
     return StringMessage(
         message='Successfully added {}.'.format(request.saying))
Пример #5
0
    def make_move(self, request):
        """One of the players, tries to hit the opponent boat"""

        player = Player.query(Player.name == request.player_name).get()
        """we validate that the player is in the Data Base"""
        if not player:
            raise endpoints.NotFoundException('player not found')

        game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
        """we validate that the game where we want to create the board exists"""
        if not game:
            raise endpoints.NotFoundException(
                'Game not found in the DB, please start a new game')

        board = Board.query(Board.key == player.board).get()
        """we validate that the board where we want to create the board exists"""
        if not board:
            raise endpoints.NotFoundException('board not found')
        """we validate that the board of the player is active, the player can't create
            multiple boards for the same Game"""
        if not player.board and not player.board_active:
            raise endpoints.ConflictException(
                'This player has already an empty board have already a board')

        if player.board != board.key:
            raise endpoints.ConflictException(
                'the board for this player is not the proper')

        if not gameutils.valid_target_pointed(request.x_position,
                                              request.y_position):
            raise endpoints.ConflictException(
                'the targeted position is not ok')

        try:
            result = gameutils.search_in_board(board, request.x_position,
                                               request.y_position)

            if result == "error":
                raise endpoints.ConflictException(
                    'there is a problem with the BOARD')
            else:
                score = Score.query(Score.player_name == player.name,
                                    Score.board == board, Score.game == game)
                board.add_target(request.x_position, request.y_position)
                game.add_move_to_history(request.x_position,
                                         request.y_position, player.name)
                message = score.target_hitted(player, request.x_position,
                                              request.y_position, board, game)
                if score.check_if_win():
                    message = "You sunk the last Boat, you win!!!"
                    board.deactivate()
                return StringMessage(message=message)

        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information ')
Пример #6
0
 def cancel_game(self, request):
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game and not game.game_over:
         game.key.delete()
         return StringMessage(message='Game with key: {} deleted.'.
                              format(request.urlsafe_game_key))
     elif game and game.game_over:
         raise endpoints.BadRequestException('Game is already over!')
     else:
         raise endpoints.NotFoundException('Game not found!')
Пример #7
0
    def getFeaturedSpeaker(self, request):
        """Return featured speaker of a conference from memcache"""

        # get conference key
        MEMCACHE_FEATURED_KEY = request.websafeConferenceKey
        FeaturedSpeakers = memcache.get(MEMCACHE_FEATURED_KEY)
        if not FeaturedSpeakers:
            FeaturedSpeakers = ''  # return empty speaker form on failure for no results

        return StringMessage(data=FeaturedSpeakers)
Пример #8
0
 def cancel_game(self, request):
     """Delete a game where game_over is false"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game and game.game_over is False:
         game.key.delete()
         return StringMessage(message='Game with key: {} deleted.'.format(request.urlsafe_game_key))
     elif game and game.game_over is True:
         raise endpoints.BadRequestException('Game is already over, cannot delete!')
     else:
         raise endpoints.NotFoundException('Game not found!')
    def getFeaturedSpeaker(self, request):
        """
        getFeaturedSpeaker endpoint recieves the calls from client to get the
        featured speaker information from memcache

        Input: It doesn't require any input parameters
        Returns: String message about featured speaker and his/her sessions
        """
        featuredSpeaker = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY)
        return StringMessage(data=featuredSpeaker or "No Featured Speaker")
 def getFeaturedSpeaker(self, request):
     """Get the name of the currently featured speaker for a conference"""
     wsck = request.websafeConferenceKey
     # get Conference object from request; bail if not found
     c_key = ndb.Key(urlsafe=wsck)
     if not c_key.get():
         raise endpoints.NotFoundException(
             'No conference found with key: %s' % wsck)
     # Return memcache string for a particular conference
     return StringMessage(data=memcache.get('featuredSpeaker_' + wsck) or "")
Пример #11
0
 def cancel_game(self, request):
     """Cancel current active game"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game and not game.game_over:
         game.key.delete()
         return StringMessage(message='Game canceled!')
     elif game and game.game_over:
         raise endpoints.ConflictException('Game already over!')
     else:
         raise endpoints.NotFoundException('No active game found!')
Пример #12
0
    def _show_game_picture(game_id):
        """ Print visual representation of game state """

        moves = Move.query(Move.game_id == game_id).order(Move.x,
                                                          Move.y).fetch()

        if len(moves) == 0:
            print("\n\nCant print game state, Invalid game_id {0}\n\n".format(
                game_id))
            return StringMessage(
                message="Invalid move parameters. no game found")

        player1, player2 = GuessANumberApi._get_players_in_game(game_id)

        print("Current Players for Game ID {0}: {1}, {2}".format(
            game_id, player1, player2))

        m_00 = Move.query(Move.x == 0, Move.y == 0,
                          Move.game_id == game_id).fetch(1)[0]
        m_01 = Move.query(Move.x == 0, Move.y == 1,
                          Move.game_id == game_id).fetch(1)[0]
        m_02 = Move.query(Move.x == 0, Move.y == 2,
                          Move.game_id == game_id).fetch(1)[0]
        m_10 = Move.query(Move.x == 1, Move.y == 0,
                          Move.game_id == game_id).fetch(1)[0]
        m_11 = Move.query(Move.x == 1, Move.y == 1,
                          Move.game_id == game_id).fetch(1)[0]
        m_12 = Move.query(Move.x == 1, Move.y == 2,
                          Move.game_id == game_id).fetch(1)[0]
        m_20 = Move.query(Move.x == 2, Move.y == 0,
                          Move.game_id == game_id).fetch(1)[0]
        m_21 = Move.query(Move.x == 2, Move.y == 1,
                          Move.game_id == game_id).fetch(1)[0]
        m_22 = Move.query(Move.x == 2, Move.y == 2,
                          Move.game_id == game_id).fetch(1)[0]

        m_00 = m_00.user_id or m_00.description
        m_01 = m_01.user_id or m_01.description
        m_02 = m_02.user_id or m_02.description
        m_10 = m_10.user_id or m_10.description
        m_11 = m_11.user_id or m_11.description
        m_12 = m_12.user_id or m_12.description
        m_20 = m_20.user_id or m_20.description
        m_21 = m_21.user_id or m_21.description
        m_22 = m_22.user_id or m_22.description

        print("\n\n\n")
        print("TIC TAC TOE GAME")
        print("\n")
        print(" {0} | {1} | {2} ".format(m_00, m_01, m_02))
        print("-----------------------------")
        print(" {0} | {1} | {2} ".format(m_10, m_11, m_12))
        print("-----------------------------")
        print(" {0} | {1} | {2} ".format(m_20, m_21, m_22))
        print("\n\n\n")
Пример #13
0
 def create_user(self, request):
     """Create a User. Requires a unique username and an email"""
     if User.query(User.name == request.user_name).get():
         raise endpoints.ConflictException(
                 'User already exists!')
     if request.user_name is None or request.email is None:
         raise endpoints.BadRequestException('Enter a username and email')
     user = User(name=request.user_name, email=request.email)
     user.put()
     return StringMessage(message='User {} created!'.format(
             request.user_name))
Пример #14
0
    def getFeaturedSpeaker(self, request):
        """Returns featured speakers with respective sessions from memcache."""

        wsck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsck).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        MEMCACHE_CONFERENCE_KEY = "FEATURED:%s" % wsck
        return StringMessage(data=memcache.get(MEMCACHE_CONFERENCE_KEY)
                             or "There are no featured speakers!")
Пример #15
0
 def cancel_game(self, request):
     """Cancels a current game."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         if game.game_over:
             raise endpoints.ConflictException('Game is already completed!')
         key = ndb.Key(urlsafe=request.urlsafe_game_key)
         key.delete()
         return StringMessage(message='Game cancelled!')
     else:
         raise endpoints.NotFoundException('Game not found!')
Пример #16
0
 def create_user(self, request):
     """Create user api"""
     if User.query(User.name == request.user_name).get():
         raise endpoints.ConflictException(
             'A User with that name already exists')
     # If the user is not given in parameter throw exception
     if not request.user_name:
         raise endpoints.BadRequestException('Name of the user not given')
     # Ok create the user and return message
     user = User.create_user(request.user_name, request.email)
     return StringMessage(message='User {} created!'.format(user.name))
Пример #17
0
    def cancel_game(self, request):
        """Cancel game API."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game and game.game_over == False and game.canceled == False:
            game.canceled = True
            game.end_game(False)
            game.put()
        else:
            raise endpoints.NotFoundException('Game not found!')

        return StringMessage(message="Game canceled")
Пример #18
0
 def create_user(self, request):
     """
     Creates a new User. Username is required
     """
     if User.query(User.name == request.user_name).get():
         raise endpoints.ConflictException(
             "Username: %s is already taken!" % request.user_name)
     user = User(name=request.user_name, email=request.email)
     user.put()
     return StringMessage(
         message="User {} created".format(request.user_name))
Пример #19
0
 def cancel_game(self, request):
     """cancel the current game state."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         if not game.game_over:
             game.key.delete()
             return StringMessage(message='Game canceled!')
         else:
             raise endpoints.BadRequestException('Game already over!')
     else:
         raise endpoints.NotFoundException('Game not found!')
Пример #20
0
    def getFeaturedSpeaker(self, request):
        """Return Featured Speaker from memcache."""

        # Getting and Verifying current user
        user = getUser()
        
        # return an existing Featured Speaker from Memcache or an empty string.
        featured = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY)
        if not featured:
            featured = ""
        return StringMessage(data=featured)
    def deleteSessionInWishlist(self, request):
        """remove a session from users' wishlist."""
        #load currrent user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization is requied')
        userProfile = self._getProfileFromUser()

        currentWishlist = userProfile.sessionsWishlist

        sessionToRemove = request.websafeSessionKey

        message = StringMessage(data="session does not exist")
        #if session is in wish list, remove it
        if sessionToRemove in userProfile.sessionsWishlist:
            userProfile.sessionsWishlist.remove(sessionToRemove)
            userProfile.put()
            message = StringMessage(data="Session removed")

        return message
Пример #22
0
 def cancel_game(self, request):
     """Deletes the game, if it is unfished."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.NotFoundException('Game not found!')
     if game.game_over:
         raise endpoints.ConflictException(
             'Game is already over, therefore cannot be deleted!')
     game.key.delete()
     return StringMessage(message='Game {} has been deleted!'.format(
         request.urlsafe_game_key))
Пример #23
0
    def cancel_game(self, request):
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game:
            if game.game_over == True:
                msg = ("You can't cancel this game!")
            else:
                game.key.delete()
                msg = ("You just canceled this game!")

            return StringMessage(message=msg)
        else:
            raise endpoints.ConflictException('Thie game is not exist')
Пример #24
0
    def get_average_moves(self, request):
        """
        Get the cached average moves remaining.

        Args:
            None
        Returns:
            StringMessage: A message with the average moves remaining
            of all active games.
        """
        return StringMessage(
            message=memcache.get(MEMCACHE_MOVES_REMAINING) or '')
Пример #25
0
    def getConferenceSessionTypes(self, request):
        """Given a conference, returns a string listing all unique session
        types offered within the conference"""
        conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        sessions = Session.query(ancestor=conf_key).fetch(
            projection=[Session.typeOfSession])
        types_set = set()
        for s in sessions:
            types_set.add(s.typeOfSession)
        types = ', '.join(types_set)

        return StringMessage(data=types)
Пример #26
0
 def getFeaturedSpeaker(self, request):
     """Get the featured speaker for given conference."""
     # check the validity of websafeConferenceKey.
     conference = _entityByKindAndUrlsafeKeyOrNone(Conference, request.websafeConferenceKey)
     if not conference:
         raise endpoints.NotFoundException(
             'No conference found with key: %s' % request.websafeConferenceKey)
     response = memcache.get(
         MEMCACHE_FEATURED_SPEAKER_KEY_PREFIX+request.websafeConferenceKey)
     if response is None:
         response = ""
     return StringMessage(data = response)
Пример #27
0
    def get_announcement(self, request):
        """
        Get Announcement from Memcache
        :param request: VoidMessage
        :return:
        """
        if not isinstance(request, message_types.VoidMessage):
            raise endpoints.BadRequestException()

        client = memcache.Client()

        return StringMessage(data=client.get(MEMCACHE_ANNOUNCEMENTS_KEY) or '')
Пример #28
0
    def deleteAllSessionsInWishlist(self, request):
        """Delete all sessions from the current user's wishlist"""
        # Get current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        profile = ndb.Key(Profile, user_id).get()
        profile.sessionWishlist = []
        profile.put()
        return StringMessage(data='All sessions deleted from wishlist')
Пример #29
0
 def cancel_game(self, request):
     """Delete the requested game."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         if not game.game_over:
             game.key.delete()
             return StringMessage(message="Game with key: %s deleted."
                                  % request.urlsafe_game_key)
         else:
             raise endpoints.ForbiddenException('Game is already over.')
     else:
         raise endpoints.NotFoundException('Game not found!')
Пример #30
0
    def cancel_game(self, request):
        """Cancel and delete the current game state."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if game:  # game exits
            # check if user is a player in this game
            if request.user_name not in (game.player1.get().name,
                                         game.player2.get().name):
                raise endpoints.UnauthorizedException(
                    'You are not a player of this game')

            if game.game_over:
                user = game.whose_turn.get()
                message = """This game has ended. It was won by {user_name} and
                    cannot be cancelled""".format(user_name=user.name)
                return StringMessage(message=message)
            else:
                game.key.delete()
                return StringMessage(message='Game cancelled and deleted.')
        else:
            raise endpoints.NotFoundException('No game exists with that key!')