Exemplo n.º 1
0
    def create_user(self, request):
        """Creates a User.
        Args:
            request: The USER_REQUEST objects, which includes a users
                chosen name and an email.
        Returns:
            StringMessage: A message that is sent to the client, saying that
                the user has been created.
        Raises:
            endpoints.BadRequestException: If no user name is provided.
            endpoints.ConflictException: If the user already exists.
            endpoints.BadRequestException: If no email is provided.
            endpoints.ConflictException: If a user with that email already exists.
        """
        if request.user_name is None:
            raise endpoints.BadRequestException(
                'You must enter a user name to create a new user!')
        elif User.query(User.name == request.user_name).get():
            raise endpoints.ConflictException(
                'A User with username {} already exists!'.format(
                    request.user_name))

        if request.email is None:
            raise endpoints.BadRequestException(
                'You must enter an email id to create a new user!')
        elif User.query(User.email == request.email).get():
            raise endpoints.ConflictException(
                'A User with email {} already exists!'.format(request.email))

        # Create a new user with the user_name and email.
        user = User(name=request.user_name, email=request.email)
        # Add the user to the datastore with kind 'User'
        user.put()
        return StringMessage(
            message='User {} created!'.format(request.user_name))
Exemplo n.º 2
0
def check_coords_validity(row_coord, col_coord):
    """Raise errors if the row or column coordinates are not valid"""
    if row_coord not in ROWS:
        raise endpoints.ConflictException(
            'Row coordinate must be between 1 - 10')

    if col_coord not in COLUMNS:
        raise endpoints.ConflictException(
            'Column coordinate must be between A - J')
Exemplo n.º 3
0
    def assign_ship_on_board(self, request):
        """One of the players, tries to assing one boat to his board game"""

        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 gameutils.valid_positions(request.start_x_position,
                                     request.start_y_position,
                                     SHIPS_IDS[request.ship_id],
                                     request.orientation):
            raise endpoints.BadRequestException(
                'Please verify the position that you choose for the boat')
        """Here we check if the boat sent
        in the request is already active in the board"""
        if gameutils.check_if_boat_is_active(request.ship_id, board):
            raise endpoints.BadRequestException(
                'Please the selected boat that you sent '
                'in the request is already active in the board')

        if gameutils.place_boat_in_board(board, request.start_x_position,
                                         request.start_y_position,
                                         request.ship_id, request.orientation):
            raise endpoints.BadRequestException(
                'The place for the boat is not available, '
                'Please verify the position that you choose for the boat')

        try:
            gameutils.log_board_on_console(board)
            board.put()
        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information ')

        return StringMessage(
            message='Boat Assigned!'.format(request.player_name))
Exemplo n.º 4
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 ')
Exemplo n.º 5
0
    def create_user(self, request):
        """Creates a User.

        :param username (req): A unique username without leading spaces.
        :type username: string
        :param email (opt): A unique and valid email.  Email is validated using
        MAILGUN email validation API.
        :type email: string
        :param email_notification (opt): True by default.  If True, user will
        receive email notifications of outstanding active games.
        :type email_notification: boolean

        :returns message: A message confirming user was created, or an error
        message.
        :rtype message: string

        :raises: ConflictException"""

        # Some format checking
        if not request.username:
            raise endpoints.ConflictException(
                    'User name cannot be null')
        if len(request.username) != len(request.username.lstrip(' ')):
            raise endpoints.ConflictException(
                    'User name can not have leading spaces')
        if request.username.isspace():
            raise endpoints.ConflictException(
                    'User name cannot be null')

        # Checking for duplicate entries
        if User.query(User.username == request.username).get():
            raise endpoints.ConflictException(
                'A user with the name {} already exists!'.
                format(request.username))

        # Only check if email is valid if there is an email to check
        if request.email:
            if User.query(User.email == request.email).get():
                raise endpoints.ConflictException(
                    'A user with the email {} already exists!'.
                    format(request.email))
            # Checking if the email is valid via MAILGUN APIs
            if not User.is_email_valid(request.email):
                return CreateUserResultForm(
                    message="Email address invalid! User is not created.")
            # All is good, saving User object
            user = User(
                username=request.username,
                email=request.email,
                email_notification=request.email_notification)
            user.put()
        else:
            user = User(username=request.username)
            user.put()
        return CreateUserResultForm(message='User {} created!'.
                             format(request.username))
Exemplo n.º 6
0
    def create_user(cls, auth_user, user_name):
        """ Register a username to a user's email address"""
        if User.query(User.email == auth_user.email()).get():
            raise endpoints.ConflictException('You have already registered!')

        if User.query(User.name == user_name).get():
            raise endpoints.ConflictException(
                'A User with that name already exists!')
        user = User(name=user_name, email=auth_user.email())
        user.put()
        return user
Exemplo n.º 7
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!')
     if User.query(User.email == request.email).get():
         raise endpoints.ConflictException(
             'A user with that email address already exists!')
     user = User(name=request.user_name, email=request.email)
     user.put()
     return StringMessage(
         message='User {} is created!'.format(request.user_name))
Exemplo n.º 8
0
def check_board_boundaries(piece_alignment, num_spaces, row_index, col_index):
    """Raise errors if the peice is being placed outside of the bounds of
    the board"""
    if (piece_alignment == 'vertical' and row_index + num_spaces > len(ROWS)):

        raise endpoints.ConflictException(
            'Your piece has gone past the boundaries of the board')

    if (piece_alignment == 'horizontal'
            and col_index + num_spaces > len(COLUMNS)):

        raise endpoints.ConflictException(
            'Your piece has gone past the boundaries of the board')
Exemplo n.º 9
0
def check_placement_validity(game, player_pieces, piece_type, piece_coords):
    """Raise errors if piece placement is invalid:
    if the piece has already been placed,
    or if the piece being placed intersects with another piece"""
    for placed_piece in player_pieces:
        # Raise error if the piece has already been placed on the
        # player's board
        if placed_piece.ship == piece_type:
            raise endpoints.ConflictException(
                'This piece has already been placed for this player')
        # Raise error if piece intersects with any other piece
        for placed_coordinate in placed_piece.coordinates:
            if placed_coordinate in piece_coords:
                raise endpoints.ConflictException(
                    'Your piece intersects with {}'.format(placed_coordinate))
Exemplo n.º 10
0
    def get_game_history(self, request):
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if game:
            return game.to_historyform()
        else:
            raise endpoints.ConflictException('Thie game is not exist')
Exemplo n.º 11
0
    def addBook(self, request):
        """create a book."""
        self._ensureAdmin()
        b_key = ndb.Key(Book, request.sbId.upper())
        if b_key.get():
            raise endpoints.ConflictException(
                'Another book with same id already exists: %s' % request.sbId)

        email = endpoints.get_current_user().email()

        book = Book(key=b_key,
                    title=request.title.lower(),
                    author=request.author,
                    sbId=request.sbId.upper(),
                    language=request.language,
                    volume=request.volume,
                    isbn=request.isbn,
                    price=request.price,
                    notes=request.notes,
                    suggestedGrade=request.suggestedGrade,
                    category=request.category,
                    publisher=request.publisher,
                    mediaType=request.mediaType,
                    editionYear=request.editionYear,
                    donor=request.donor,
                    comments=request.comments,
                    reference=request.reference,
                    createdBy=email,
                    createdDate=date.today())
        book.put()
        return request
Exemplo n.º 12
0
    def create(self, request):
        """
        Creates a new Session. Only available to the organizer of the conference
        :param request: SessionForm
        :return: SessionForm
        """
        if not request.websafeConfKey:
            raise endpoints.BadRequestException('Conference key required.')

        # try to prepare the Session instance
        session = self.__prep_new_session(request)

        # see if it exists already
        if session.key.get():
            raise endpoints.ConflictException(
                'Session with key %s already exists' % session.key.urlsafe())

        # deal with Speaker creation/updating
        speakers = [self.__prepare_speaker(form) for form in request.speakers]

        # try the transaction
        request.websafeKey = self._create(session, speakers).urlsafe()

        # Add a task to the queue for getting featured speaker changes
        taskqueue.add(params={'conf_key': request.websafeConfKey},
                      url='/tasks/update_featured_speaker')

        return request
Exemplo n.º 13
0
    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 new_game(self, request):
        """Creates new game"""
        player1 = User.query(User.name == request.player1).get()
        if not player1:
            raise endpoints.NotFoundException('Player1 does not exist!')
        player2 = User.query(User.name == request.player2).get()
        if not player2:
            raise endpoints.NotFoundException('Player2 does not exist!')
        if player1 == player2:
            raise endpoints.ConflictException('Cannot play against yourself')

        # randomize who gets the 1st turn
        next_turn = random.randint(1, 2)
        if next_turn == 1:
            next_turn_name = player1.name
        else:
            next_turn_name = player2.name

        # reset the tic tac toe board
        board = [' '] * 9

        # create a new game record in datastore
        game = Game.new_game(player1.key, player2.key, next_turn_name, board)

        return game.to_form(
            '{} will have the first move'.format(next_turn_name))
Exemplo n.º 15
0
 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!')
Exemplo n.º 16
0
def check_not_double_hit(pieces, target_coord):
    """Check for ensuring a coordinate that has
    already been hit is not being hit again"""
    pieces_hit_coords = [piece.hit_marks for piece in pieces]
    for hit_coords in pieces_hit_coords:
        if target_coord in hit_coords:
            raise endpoints.ConflictException(
                'This coordinate has already been hit')
Exemplo n.º 17
0
 def create_user(self, request):
     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))
Exemplo n.º 18
0
 def create(cls, user_name, email=''):
     """Create a user"""
     if cls.query(cls.user_name == user_name).get():
         msg = 'Error, that username already exists'
         raise endpoints.ConflictException(msg)
     user = cls(user_name=user_name, email=email)
     user.put()
     return user
Exemplo n.º 19
0
 def create_user(self, request):
     """Creates new user to play the game"""
     if User.query(User.name == request.name).get():
         raise endpoints.ConflictException(
             'A User with that name already exists!')
     user = User(name=request.name, wins=0, email=request.email)
     user.put()
     return JSONMessage(message="User {} added!".format(request.name))
Exemplo n.º 20
0
    def cancel_game(self, request):
        """Cancel an active 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))
        if not game.is_active:
            raise endpoints.ConflictException('This game is already finished')

        game.round = 9
        game.is_active = False
        game.put()

        return StringMessage(
            message='Game {} cancelled'.format(request.game_key))
Exemplo n.º 21
0
def check_not_double_miss(game, target_player, target_coord):
    """Ensure that the coordinate being struck has not previsouly
    been attempted and missed against target player for given game"""
    misses = Miss.query(Miss.game == game.key).filter(
        Miss.target_player == target_player.key).fetch()
    miss_coords = [missCoord.coordinate for missCoord in misses]
    if target_coord in miss_coords:
        raise endpoints.ConflictException(
            'This coordinate has already been struck and missed')
Exemplo n.º 22
0
 def create_user(self, request):
     """Create a new user for Hangman"""
     if User.query(User.user_name == request.user_name).get():
         raise endpoints.ConflictException(
             "Try again with a new handle, that one is taken.")
     user = User(user_name=request.user_name,
                 email_address=request.email_address)
     user.put()
     return StringMessage(
         message="Welcome to Hangman, {}".format(request.user_name))
Exemplo n.º 23
0
 def resume_game(self, request):
     """ This function resumes a game that has been saved.
     Input: Game safe url key"""
     game = utils.get_by_urlsafe(request.urlsafekey, Game)
     if game.status == "save":
         game.status = "start"
         game.put()
         return MessageForm(message=" The game has been resume")
     else:
         raise endpoints.ConflictException('Cannot resume a Game over')
Exemplo n.º 24
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,
                 games_played=0, wins=0, average_score=0.0)
     user.put()
     return StringMessage(message='User {} created!'.format(
             request.user_name))
Exemplo n.º 25
0
    def signIn(self, request):
        """ This function register a new user as player.
        Input: A unique username and email address"""
        username = request.username
        email = request.email
        if not utils.valid_username(username) or not utils.valid_email(email):
            raise endpoints.ConflictException('Invalid Input')
        if Player.query(Player.username == request.username).get():
            raise endpoints.ConflictException(
                'A User with that name already exists!')

        Player(username=username, email=email).put()

        # create default player if not exist
        if not Player.query(Player.username == "computer").get():
            self._defaultPlayer()

        return MessageForm(message="Welcome Player %s. Enjoy racing!!!" %
                           username)
Exemplo n.º 26
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!')
Exemplo n.º 27
0
    def create_empty_board(self, request):
        """One of the players, creates the game and gets the game-id and gives that ID
        to the other player in order to play between each other"""
        player = Player.query(Player.name == request.player_name).get()
        game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
        """ HERE WE START THE PROPER VALIDATIONS FOR THIS ENDPOINT"""
        """we validate that the player is in the Data Base"""
        if not player:
            raise endpoints.NotFoundException(
                'A Player with that name does not exist!, '
                'we need a second player in order to join the 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')
        """we validate that the game where we want to create the board is not Over"""
        if not game.game_over == False:
            raise endpoints.ConflictException('Game is over')
        """we validate that the board of the player is active, the player can't create
                    multiple boards for the same Game"""
        if player.board and player.board_active:
            raise endpoints.ConflictException(
                'This player has already an empty board have already a board')

        try:
            board = Board.new_board(player, Board.create_empty_board(), game)
            player.board_active = True
            player.board = board.key
            player.put()
            board.put()
        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information '
                'of the board')

        # 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.

        return board.to_form("Board created", player.name,
                             board.aircraft_carrier, board.battleship,
                             board.submarine, board.destroyer,
                             board.patrol_boat)
Exemplo n.º 28
0
 def create_user(self, request):
     """Create a User. Requires a unique username."""
     if User.query(User.username == request.username).get():
         raise endpoints.ConflictException(
             'A User with that name already exists!')
     user = User(username=request.username,
                 display_name=request.display_name,
                 email=request.email)
     user.put()
     return user.to_form()
Exemplo n.º 29
0
 def save_game(self, request):
     """ This function saves a game; The game can be played later.
     Input: Game safe url key"""
     game = utils.get_by_urlsafe(request.urlsafekey, Game)
     if game.status != "over":
         game.status = "save"
         game.put()
         return MessageForm(message=" The game has been save")
     else:
         raise endpoints.ConflictException('Cannot save a Game over')
Exemplo n.º 30
0
 def get_game_history(self, request):
     """Returns a history of all guesses made in game."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.ConflictException(
             'Cannot find game with key {}'.format(
                 request.urlsafe_game_key))
     else:
         history = History.query(ancestor=game.key).order(History.order)
         return HistoryForms(items=[guess.to_form() for guess in history])