Beispiel #1
0
def fill_lobbies(lid_list):
    """Populates lobbies."""
    to_update = []
    for lid in lid_list:
        lobby = Lobby.query(Lobby.lobby_id == lid).get()
        lobby.users = ["route", "runner"]
        to_update.append(lobby)
    ndb.put_multi(to_update)
    def get(self):
        """ Returns a list of available lobbies.
        Response
            lobbies - list of lobbies
        """
        q = Lobby.query(Lobby.started == False)
        lobbies = [lobby.lobby_id for lobby in q.iter()]
        response = {'status': 'success', 'data': {'lobbies': lobbies}}

        self.response.out.write(json.dumps(response))
Beispiel #3
0
    def get(self):
        """ Returns a list of available lobbies.
        Response
            lobbies - list of lobbies
        """
        q = Lobby.query(Lobby.started == False)
        lobbies = [lobby.lobby_id for lobby in q.iter()]
        response = {'status': 'success', 'data': {'lobbies': lobbies}}

        self.response.out.write(json.dumps(response))
    def post(self):
        """ User joins an existing lobby.
        Request:
            uid - user_id
            lid - lobby to join
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        q = User.query(User.uuid == uid)
        if q is None:
            logging.error("Non-existent user (" + str(uid) +
                          ") attempted to join lobby.")
        # TODO: Make sure this user is actually who we think it is

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()
        # Stale lobby
        if lobby is None:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = "Lobby " + lobby_id + " does not exist!"
            return self.response.out.write(json.dumps(response))

        # Lobby already has REQ_USERS in it
        if len(lobby.users) == REQ_USERS or lobby.started is True:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = "Lobby " + lobby_id + " is at max capacity!"
            return self.response.out.write(json.dumps(response))

        lobby.users.append(uid)
        lobby.started = True
        lobby.put()

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
Beispiel #5
0
    def post(self):
        """ User joins an existing lobby.
        Request:
            uid - user_id
            lid - lobby to join
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        q = User.query(User.uuid == uid)
        if q is None:
            logging.error("Non-existent user (" + str(uid) +
                          ") attempted to join lobby.")
        # TODO: Make sure this user is actually who we think it is

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()
        # Stale lobby
        if lobby is None:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = "Lobby " + lobby_id + " does not exist!"
            return self.response.out.write(json.dumps(response))

        # Lobby already has REQ_USERS in it
        if len(lobby.users) == REQ_USERS or lobby.started is True:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = "Lobby " + lobby_id + " is at max capacity!"
            return self.response.out.write(json.dumps(response))

        lobby.users.append(uid)
        lobby.started = True
        lobby.put()

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
Beispiel #6
0
    def testJoinLobbyPostHandler(self):
        """Tests lobby joining handler."""
        endpoint = '/api/matchmaking/join'

        # No user id supplied
        response = self.testapp.post_json(endpoint, {}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing uid (User id)')

        # No lobby id supplied
        response = self.testapp.post_json(endpoint, {'uid': 'cs130'},
                                          expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing lid (Lobby id)')

        # Lobby does not exist anymore
        response = self.testapp.post_json(endpoint, {
            'uid': 'cs130',
            'lid': 'routerunner'
        },
                                          expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Lobby routerunner does not exist!')

        # Lobby is full
        request = {'uid': 'cs130', 'lid': self.full[0]}
        response = self.testapp.post_json(endpoint,
                                          request,
                                          expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'],
                         'Lobby ' + self.full[0] + ' is at max capacity!')

        # Successfully joined lobby
        request = {'uid': 'cs130', 'lid': 'rchen93'}
        response = self.testapp.post_json(endpoint, request)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 200)
        self.assertEqual(body['status'], 'success')
        lobby = Lobby.query(Lobby.lobby_id == 'rchen93').get()
        self.assertEqual(len(lobby.users), 2)
        self.assertEqual(collections.Counter(lobby.users),
                         collections.Counter(['rchen93', 'cs130']))
Beispiel #7
0
    def testNewLobbyHandler(self):
        """Tests lobby creation handler."""
        endpoint = '/api/matchmaking/new'

        # No user id supplied
        response = self.testapp.post_json(endpoint, {}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing uid (User id)')

        # No lobby id supplied
        response = self.testapp.post_json(endpoint, {'uid': 'cs130'},
                                          expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing lid (Lobby id)')

        # Test that a new User is created if we've never seen this user before
        uid = 'routerunner'
        lid = 'cs130'
        request = {'uid': uid, 'lid': lid}
        user = User.query(User.uuid == uid).get()
        lobby = Lobby.query(Lobby.lobby_id == lid).get()
        self.assertIsNone(user)
        self.assertIsNone(lobby)

        response = self.testapp.post_json(endpoint, request)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 200)
        self.assertEqual(body['status'], 'success')
        user = User.query(User.uuid == uid).get()
        lobby = Lobby.query(Lobby.lobby_id == lid).get()
        self.assertIsNotNone(user)
        self.assertIsNotNone(lobby)
    def testNewLobbyHandler(self):
        """Tests lobby creation handler."""
        endpoint = '/api/matchmaking/new'

        # No user id supplied
        response = self.testapp.post_json(endpoint, {}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing uid (User id)')

        # No lobby id supplied
        response = self.testapp.post_json(
            endpoint, {'uid': 'cs130'}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing lid (Lobby id)')

        # Test that a new User is created if we've never seen this user before
        uid = 'routerunner'
        lid = 'cs130'
        request = {'uid': uid, 'lid': lid}
        user = User.query(User.uuid == uid).get()
        lobby = Lobby.query(Lobby.lobby_id == lid).get()
        self.assertIsNone(user)
        self.assertIsNone(lobby)

        response = self.testapp.post_json(endpoint, request)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 200)
        self.assertEqual(body['status'], 'success')
        user = User.query(User.uuid == uid).get()
        lobby = Lobby.query(Lobby.lobby_id == lid).get()
        self.assertIsNotNone(user)
        self.assertIsNotNone(lobby)
    def testJoinLobbyPostHandler(self):
        """Tests lobby joining handler."""
        endpoint = '/api/matchmaking/join'

        # No user id supplied
        response = self.testapp.post_json(endpoint, {}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing uid (User id)')

        # No lobby id supplied
        response = self.testapp.post_json(
            endpoint, {'uid': 'cs130'}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Missing lid (Lobby id)')

        # Lobby does not exist anymore
        response = self.testapp.post_json(
            endpoint, {'uid': 'cs130', 'lid': 'routerunner'}, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Lobby routerunner does not exist!')

        # Lobby is full
        request = {'uid': 'cs130', 'lid': self.full[0]}
        response = self.testapp.post_json(
            endpoint, request, expect_errors=True)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 400)
        self.assertEqual(body['status'], 'error')
        self.assertEqual(body['msg'], 'Lobby ' +
                         self.full[0] + ' is at max capacity!')

        # Successfully joined lobby
        request = {'uid': 'cs130', 'lid': 'rchen93'}
        response = self.testapp.post_json(endpoint, request)
        body = json.loads(response.body)
        self.assertEqual(response.status_int, 200)
        self.assertEqual(body['status'], 'success')
        lobby = Lobby.query(Lobby.lobby_id == 'rchen93').get()
        self.assertEqual(len(lobby.users), 2)
        self.assertEqual(collections.Counter(lobby.users),
                         collections.Counter(['rchen93', 'cs130']))
    def post(self):
        """ User creates a lobby.
        Request
            uid - user_id
            lid - name of lobby
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))
        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        user = User.query(User.uuid == uid).get()
        # New User
        if user is None:
            logging.info("New user (" + str(uid) +
                         ") has joined RouteRunner.")
            user = User(uuid=uid, nickname=uid)
            user.put()
        # TODO: Make sure this user is actually who we think it is

        lobby = Lobby(lobby_id=lobby_id, users=[uid])
        # Check if this lobby already exists
        exists = Lobby.query(Lobby.lobby_id == lobby_id).get()
        if exists is None:
            lobby.put()

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
Beispiel #11
0
    def post(self):
        """ User creates a lobby.
        Request
            uid - user_id
            lid - name of lobby
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))
        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        user = User.query(User.uuid == uid).get()
        # New User
        if user is None:
            logging.info("New user (" + str(uid) + ") has joined RouteRunner.")
            user = User(uuid=uid, nickname=uid)
            user.put()
        # TODO: Make sure this user is actually who we think it is

        lobby = Lobby(lobby_id=lobby_id, users=[uid])
        # Check if this lobby already exists
        exists = Lobby.query(Lobby.lobby_id == lobby_id).get()
        if exists is None:
            lobby.put()

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
    def post(self):
        """ End game.
        Request
            uid - user id of user leaving
            lid - the game lobby to end
            sessid - the game session to end
            winner - user id of the winner
            loser - user id of the loser
        """
        data = json.loads(self.request.body)
        response = {}
        winner = None
        loser = None

        try:
            user_id = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        if 'winner' in data:
            winner = data['winner']
        else:
            loser = data['loser']

        # try:
        #     winner = data['winner']
        #     loser = data['loser']
        # except KeyError:
        #     self.error(400)
        #     response['status'] = 'error'
        #     response[
        #         'msg'] = 'Missing winner (id of winner) or loser (id of loser)'
        #     return self.response.out.write(json.dumps(response))

        # try:
        #     session_id = data['sessid']
        # except KeyError:
        #     self.error(400)
        #     failure_msg = {'error': 'Missing sessid (Game Session id)'}
        #     return self.response.out.write(json.dumps(failure_msg))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()

        # Lobby has not yet been deleted
        if lobby:
            # If there is only 1 user left, just delete lobby
            if len(lobby.users) == 1:
                if winner is not None:
                    win_user = User.query(User.uuid == winner).get()
                    win_user.win += 1
                    win_user.put()
                else:
                    lose_user = User.query(User.uuid == loser).get()
                    lose_user.loss += 1
                    lose_user.put()
                lobby.key.delete()
            # Otherwise, remove the user from lobby
            # Update the user's statistics
            else:
                lobby.users.remove(user_id)
                lobby.put()
                if winner is not None:
                    win_user = User.query(User.uuid == winner).get()
                    win_user.win += 1
                    win_user.put()
                else:
                    lose_user = User.query(User.uuid == loser).get()
                    lose_user.loss += 1
                    lose_user.put()

        # TODO: Session cleanup

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
    def post(self):
        """ Start game by both users.
        Request
            uid - user_id
            lid - the game lobby both users are playing in
        Response
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()

        if lobby is None:
            logging.error(
                "User (" + str(uid) + ") attempted to join non-existent Lobby (" + str(lobby_id) + ").")
        else:
            ready = lobby.ready
            # This is a new user who is ready
            if uid not in ready:
                lobby.ready.append(uid)
                lobby.put()

        response = {}
        # The game is ready to be started
        if len(lobby.ready) == REQ_USERS:
            # TODO: Add logic for creating a Session here
            session = Session(channel_id=lobby_id, target_gold_amount="100",
                              user_ids=[])
            for i in range(len(lobby.ready)):
                session.user_ids.append(lobby.ready[i])
            session.put()
            response['type'] = "info"
            response['data'] = {"ready": "true"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, response)
            pubnub.unsubscribe(lobby_id)

            self.response.out.write(json.dumps(response))
        else:
            response['type'] = "info"
            response['data'] = {"ready": "false"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, callback)
            pubnub.unsubscribe(lobby_id)
            self.response.out.write(json.dumps(response))
Beispiel #14
0
    def post(self):
        """ End game.
        Request
            uid - user id of user leaving
            lid - the game lobby to end
            sessid - the game session to end
            winner - user id of the winner
            loser - user id of the loser
        """
        data = json.loads(self.request.body)
        response = {}
        winner = None
        loser = None

        try:
            user_id = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        if 'winner' in data:
            winner = data['winner']
        else:
            loser = data['loser']

        # try:
        #     winner = data['winner']
        #     loser = data['loser']
        # except KeyError:
        #     self.error(400)
        #     response['status'] = 'error'
        #     response[
        #         'msg'] = 'Missing winner (id of winner) or loser (id of loser)'
        #     return self.response.out.write(json.dumps(response))

        # try:
        #     session_id = data['sessid']
        # except KeyError:
        #     self.error(400)
        #     failure_msg = {'error': 'Missing sessid (Game Session id)'}
        #     return self.response.out.write(json.dumps(failure_msg))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()

        # Lobby has not yet been deleted
        if lobby:
            # If there is only 1 user left, just delete lobby
            if len(lobby.users) == 1:
                if winner is not None:
                    win_user = User.query(User.uuid == winner).get()
                    win_user.win += 1
                    win_user.put()
                else:
                    lose_user = User.query(User.uuid == loser).get()
                    lose_user.loss += 1
                    lose_user.put()
                lobby.key.delete()
            # Otherwise, remove the user from lobby
            # Update the user's statistics
            else:
                lobby.users.remove(user_id)
                lobby.put()
                if winner is not None:
                    win_user = User.query(User.uuid == winner).get()
                    win_user.win += 1
                    win_user.put()
                else:
                    lose_user = User.query(User.uuid == loser).get()
                    lose_user.loss += 1
                    lose_user.put()

        # TODO: Session cleanup

        response['status'] = 'success'
        self.response.out.write(json.dumps(response))
Beispiel #15
0
    def post(self):
        """ Start game by both users.
        Request
            uid - user_id
            lid - the game lobby both users are playing in
        Response
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()

        if lobby is None:
            logging.error("User (" + str(uid) +
                          ") attempted to join non-existent Lobby (" +
                          str(lobby_id) + ").")
        else:
            ready = lobby.ready
            # This is a new user who is ready
            if uid not in ready:
                lobby.ready.append(uid)
                lobby.put()

        response = {}
        # The game is ready to be started
        if len(lobby.ready) == REQ_USERS:
            # TODO: Add logic for creating a Session here
            session = Session(channel_id=lobby_id,
                              target_gold_amount="100",
                              user_ids=[])
            for i in range(len(lobby.ready)):
                session.user_ids.append(lobby.ready[i])
            session.put()
            response['type'] = "info"
            response['data'] = {"ready": "true"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, response)
            pubnub.unsubscribe(lobby_id)

            self.response.out.write(json.dumps(response))
        else:
            response['type'] = "info"
            response['data'] = {"ready": "false"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, callback)
            pubnub.unsubscribe(lobby_id)
            self.response.out.write(json.dumps(response))