示例#1
0
 def get(self):
     """Handles requests concerning all the rooms"""
     rep = self.get_query_argument('cmd')
     cmd = RoomRequest[rep]
     msg_ = {}
     if cmd == RoomRequest.GET_ROOMATES:
         user_id = self.get_query_argument('userid')
         room_id = self.get_query_argument('roomid')
         list_of_roomates = self.controller.get_all_roomates(
             user_id, room_id)
         msg_ = DiscardMessage(cmd=ClientRcvMessage.GET_ROOMATES_REP.value,
                               data=list_of_roomates)
     elif cmd == RoomRequest.GET_ROOMS:
         list_of_rooms = self.controller.get_all_rooms()
         msg_ = DiscardMessage(cmd=ClientRcvMessage.GET_ROOMS_REP.value,
                               data=list_of_rooms)
     elif cmd == RoomRequest.GET_CURRENT_PLAYER:
         room_id = self.get_query_argument('roomid')
         player = self.controller.get_current_player(room_id)
         print("Player: ", player)
         msg_ = DiscardMessage(
             cmd=ClientRcvMessage.GET_CURRENT_PLAYER_REP.value,
             prompt='Currently playing: ',
             data=player.nickname)
     self.write(DiscardMessage.to_json(msg_))
示例#2
0
    def gen_ping(self):
        """ 
		This generates a ping message to send to 
		the server to ask if roomates can actually
		start playing the game
		"""
        msg_ = DiscardMessage(cmd=RoomGameStatus.ARE_ROOMATES_IN_GAME.value,
                              room_id=self.player.get_room_id(),
                              user_id=self.player.get_user_id())
        return DiscardMessage.to_json(msg_)
示例#3
0
    def handle_wsmessage(self, msg):
        """
		Handles websocket(game) messages

		:param
		"""
        print("[[ In handle_wsmessage ]]")
        cmd = RoomGameStatus[msg.cmd]
        msg_ = {}
        prompt_ = ""
        room_id = msg.get_payload_value(value='room_id')
        user_id = msg.get_payload_value(value='user_id')
        if cmd == RoomGameStatus.ARE_ROOMATES_IN_GAME:
            for room in self.rooms:
                print("[[ In rooms ]]")
                print("Room-id-1: ", room.get_room_id(), " room-id-2: ",
                      room_id)
                if room.get_room_id() == room_id:
                    print("[[ In rooms 45 ]]")
                    if all((room.has_game_started() == False,
                            room.get_num_of_players_remaining() > 0)):
                        print("[[ Waiting ]]")
                        prompt_ = 'Waiting for ' + \
                         str(room.get_num_of_players_remaining()) + \
                         ' players to join'
                        msg_ = DiscardMessage(cmd=ClientRcvMessage.
                                              ARE_ROOMATES_IN_GAME_REP.value,
                                              prompt=prompt_)
                        self.reply_on_game_conn(user_id, room_id, msg_)
                    elif all((room.has_game_started() == False,
                              room.get_num_of_players_remaining() == 0)):
                        print("[[ Success ]]")
                        msg_ = DiscardMessage(
                            cmd=ClientRcvMessage.GAME_MESSAGE_REP.value,
                            prompt=ClientRcvMessage.GAME_CAN_BE_STARTED_REP.
                            value)
                        self.broadcast_game_message(user_id, room_id, msg_)
                        #self.stop_all_roomates_cb(room_id)
                    else:
                        print(
                            "[[ Player is trying to see if game has started ]]"
                        )
                        msg_ = DiscardMessage(
                            cmd=ClientRcvMessage.GAME_MESSAGE_REP.value,
                            prompt=ClientRcvMessage.GAME_HAS_STARTED_REP.value)
                        self.reply_on_game_conn(user_id, room_id, msg_)
                print("[[ Out of rooms ]]")
        elif cmd == RoomGameStatus.GAME_MESSAGE:
            msg_ = DiscardMessage(cmd=ClientRcvMessage.GAME_MESSAGE_REP.value,
                                  prompt='Game is in session')
            self.reply_on_game_conn(user_id, room_id, msg_)
示例#4
0
 def __get_pick_option(self, prompt):
     choice = None
     if (self.__message_to_process.get_payload(value='return_type')
         == GameMoveType.DATATYPE_STR.value):
         choice = self._controller.get_str_input(prompt)
         while ( choice not in self.__message_to_process.get_paylaod_value(
             value='extra_data')):
             print('Wrong option')
             choice = self._controller.get_str_input(prompt)
     elif (self.__message_to_process.get_payload_value(
         value='return_type') == GameMoveType.DATATYPE_INT.value):
         choice = self._controller.get_int_input(prompt)
         while ( choice not in self.__message_to_process.get_payload_value(
             value='extra_data')):
             print('Wrong option')
             choice = self._controller.get_int_input(prompt)
     return DiscardMessage(
         cmd=RoomGameStatus.GAME_MESSAGE.value,
         data=choice,
         room_id=self.get_room_id(),
         user_id=self.get_user_id(),
         return_type=self.__message_to_process.get_payload_value(value='return_type'),
         flag=self.__message_to_process.get_payload_value(value='flag'),
         msg_id=self.__message_to_process.msg_id
     )
示例#5
0
 def handle_msg(self, message):
     """ Handles messages received from the game server """
     print("[[ In handle_msg ]]")
     msg = DiscardMessage.to_obj(message)
     if all((msg.cmd == ClientRcvMessage.GAME_MESSAGE_REP.value,
             msg.get_payload_value(value='prompt') ==
             ClientRcvMessage.GAME_CAN_BE_STARTED_REP.value)):
         print("[[ Starting game ]]")
         if self.has_initialised == False:
             self.has_initialised = True
             self.start_game()
             self.choose_initial_player()
     elif all(
         (msg.cmd == ClientRcvMessage.GAME_MESSAGE_REP.value,
          msg.get_payload_value(
              value='prompt') == ClientRcvMessage.GAME_HAS_STARTED_REP.value
          )):
         print("[[ Joining stared game ]]")
         if self.has_initialised == False:
             self.has_initialised = True
             self.choose_initial_player()
     elif msg.cmd == ClientRcvMessage.ASK_FOR_ROOMATES_REP:
         self.show_roomates()
     print("Received game message from server: ", msg)
     if self.has_initial_player_been_choosen == True:
         print("Setting message for eventual processing")
         self.player.set_message_to_process(msg)
示例#6
0
    def find_room(self):
        """ 
		This finds rooms 

		:returns: bool -- True if rooms has been found. False if otherwise
		"""
        print('==== Getting rooms to play the game ====')
        param = {'cmd': RoomRequest.GET_ROOMS.value}
        req = requests.get(self.room_url, params=param)
        rooms = DiscardMessage.to_obj(req.text)
        if rooms.get_payload_value(value='data'):
            ls = [{
                key: value
                for key, value in value.items() if key != 'roomid'
            } for value in rooms.get_payload_value(value='data')]
            ls[:] = [
                str(ind) + ') ' + repr(value) for ind, value in enumerate(ls)
            ]
            room_str = '\n'.join(ls)
            print('The rooms available:', '\n', room_str)
            choice = self.get_int_input('Choose room to join: ')
            while choice >= len(ls):
                choice = self.get_int_input('Choose room to join: ')
            room_ = rooms.get_payload_value(value='data')
            room = room_[choice]
            return room
        print(
            "Can't find rooms. You can try to find rooms again(Recommended) or create a room."
        )
        return None
示例#7
0
    def add_game_conn(self, user_id, username, room_id, conn):
        """
		This associates a websocket to a player and adds it
		to the list of game connections if the association 
		does not already exist

		:param user_id: Player identifier
		:param username: Player username
		:param room_id: Room identifier
		:param conn: Websocket connection
		"""
        print("[[ In add_game_conn ]]")
        add_new_conn = True
        if len(self.game_conns) > 0:
            for game_conn in self.game_conns:
                if all((game_conn.user_id == user_id,
                        game_conn.room_id == room_id)):
                    game_conn.wssocket = conn
                    add_new_conn = False
                    break
        if add_new_conn == True:
            callback = ioloop.PeriodicCallback(lambda: self.all_roomates_cb,
                                               120)
            game_conn = PlayerGameConn(user_id=user_id,
                                       room_id=room_id,
                                       wssocket=conn,
                                       roomates_callback=callback)
            print("A new game connection has been created")
            self.game_conns.append(game_conn)
            prompt_ = username + " just joined game"
            msg_ = DiscardMessage(
                cmd=ClientRcvMessage.PLAYER_JOINED_GAME.value, prompt=prompt_)
            self.broadcast_game_message(user_id, room_id, msg_)
            #game_conn.startCallBack()
        print("[[ Out of add_game_conn ]]")
示例#8
0
 def play(self):
     choice = None
     msg_ = {}
     if self.__message_to_process:
         prompt = self.__message_to_process.get_payload_value(
             value='prompt')
         print(self.__message_to_process.get_payload_value(
             value='data'))
         if all((self.__message_to_process.get_payload_value(
             value='return_type') in [ GameMoveType.DATATYPE_STR.value,
                 GameMoveType.DATATYPE_INT.value],
             self.__message_to_process.get_payload_value(
                 value='next_cmd') == GameMoveType.PICK_OPTION.value)):
             msg_ = self.__get_pick_option(prompt)
         elif all((self.__message_to_process.get_payload_value(
             value='return_type') == GameMoveType.DATATYPE_CARDS.value,
             self.__message_to_process.get_payload_value(
              value='next_cmd') == GameMoveType.PICK_CARDS.value )):
             print('My hand: ')
             print('\n'.join([ str(ind) + ') ' + value 
               for ind, value in enumerate(self.model.get_hand())]))
             choice = self._controller.get_int_input(prompt)
             cards = self.model.select_cards([choice])
             msg_ = DiscardMessage(
                 cmd=RoomGameStatus.GAME_MESSAGE.value,
                 data=cards,
                 room_id=self.get_room_id(),
                 user_id=self.get_user_id(),
                 flag=self.__message_to_process.get_payload_value(value='flag'),
                 msg_id=self.__message_to_process.msg_id
             )
         elif ( self.__message_to_process.get_payload_value(
                value='next_cmd') in [ GameMoveType.PICK_ONE.value, 
                  GameMoveType.PICK_TWO.value ]):
                # it is a punishment or an error   
             self.__punish(prompt)
             return msg
         else:
             msg_ = DiscardMessage(cmd=RoomGameStatus.GAME_MESSAGE.value,
                 data='[Test] I sent a game move',
                 room_id=self.get_room_id(),
                 user_id=self.get_user_id()
             )
         return msg_
     else:
         print("Do nothing")
示例#9
0
 def print_currently_playing(self):
     print("[[ In print_currently_playing ]]")
     param = {
         'cmd': RoomRequest.GET_CURRENT_PLAYER.value,
         'roomid': self.player.get_room_id()
     }
     rep = requests.get(self.room_url, params=param)
     response = DiscardMessage.to_obj(rep.text)
     return (response.get_payload_value(value='prompt'),
             response.get_payload_value(value='data'))
示例#10
0
    def gen_test_message(self):
        """ This generates a user-generated message 

		:param question: Question to be asked
		"""
        choice = None
        if self.has_initialised == True:
            choice = self.gen_ping()
        else:
            choice = self.get_str_input('Send a message: ')
        if choice == "End":
            msg_ = {}
            return json.dumps(msg_)
        else:
            msg_ = DiscardMessage(cmd=RoomGameStatus.GAME_MESSAGE.value,
                                  data=choice,
                                  room_id=self.player.get_room_id(),
                                  user_id=self.player.get_user_id())
            return DiscardMessage.to_json(msg_)
示例#11
0
 def start_game(self):
     """ This sends a START_GAME request to game server """
     msg_ = {
         'userid': self.player.get_user_id(),
         'roomid': self.player.get_room_id()
     }
     param = {'cmd': RoomRequest.START_GAME.value}
     req = requests.post(self.room_url, json=msg_, params=param)
     response = DiscardMessage.to_obj(req.text)
     print(response)
示例#12
0
 def main_loop(self):
     """This is the main loop in the game"""
     choice = None
     msg_ = {}
     prompt, player = self.print_currently_playing()
     print(prompt, player)
     choice = self.get_enum_choice(self.get_str_input(self.menu()))
     while choice == None:
         print('Wrong option')
         choice = self.get_enum_choice(self.get_str_input(self.menu()))
     if choice == MainLoopChoices.PRETTY_HELP:
         #req = requests.get(self.doc_url)
         msg_ = DiscardMessage(cmd='DOCUMENTATION')
     elif choice == MainLoopChoices.CMD_RULES:
         msg_ = DiscardMessage(cmd='DOCUMENTATION')
     elif choice == MainLoopChoices.PLAY_ROUND:
         msg_ = self.player.play()
     elif choice == MainLoopChoices.LEAVE_GAME:
         msg_ = DiscardMessage(cmd='DOCUMENTATION')
     print("[[ Out of main_loop ]] ", msg_)
     return DiscardMessage.to_json(msg_)
示例#13
0
    def broadcast_game_message(self, user_id, room_id, msg):
        """
		Server broadcasts messages to all roomates
		
		:param user_id: Player identifier
		:param room_id: Room identifier
		:param msg: Message to be broadcasted
		"""
        if len(self.game_conns) > 0:
            for player_conns in self.game_conns:
                conn = player_conns.wssocket
                conn.write_message(DiscardMessage.to_json(msg))
示例#14
0
 def choose_initial_player(self):
     print("[[ In choose_initial_player ]]")
     param = {'cmd': RoomRequest.SET_FIRST_PLAYER.value}
     msg_ = {
         'userid': self.player.get_user_id(),
         'roomid': self.player.get_room_id(),
         'username': self.player.get_nickname()
     }
     rep = requests.post(self.room_url, params=param, json=msg_)
     response = DiscardMessage.to_obj(rep.text)
     print(response.get_payload_value(value='prompt'),
           response.get_payload_value(value='data'))
     if self.has_initial_player_been_choosen == False:
         self.has_initial_player_been_choosen = True
示例#15
0
    def reply_on_game_conn(self, user_id, room_id, msg):
        """
		Server sends a message to a particular Player
		
		:param user_id: User identifier		
		:param room_id: Room identifier
		:param msg: Message to be sent to Player
		"""
        print("[[ In reply_on_game_conn ]]")
        for game_conn in self.game_conns:
            if all(
                (game_conn.user_id == user_id, game_conn.room_id == room_id)):
                game_conn.wssocket.write_message(DiscardMessage.to_json(msg))
                break
示例#16
0
 def show_roomates(self):
     """ This shows roomates """
     param = {
         'cmd': RoomRequest.GET_ROOMATES.value,
         'userid': self.player.get_user_id(),
         'roomid': self.player.get_room_id()
     }
     req = requests.get(self.room_url, params=param)
     response = DiscardMessage.to_obj(req.text)
     ls = [
         str(ind) + ') ' + value for ind, value in enumerate(
             response.get_payload_value(value='data'))
     ]
     if ls:
         room_str = '\n'.join(ls)
         print('My roomates:', '\n', room_str)
     else:
         print('You have no roomates yet!!')
示例#17
0
    def join_room(self, room=None):
        """
		This adds current player to room

		:param room: Room to join
		"""
        print('=== Joining room ===')
        self.create_new_user()
        self.player.set_room_id(room['roomid'])
        print('You selected: ', self.player.get_room_id())
        param = {'cmd': RoomRequest.JOIN_ROOM.value}
        msg = {
            'username': self.player.get_nickname(),
            'userid': self.player.get_user_id(),
            'roomid': room['roomid']
        }
        req = requests.post(self.room_url, json=msg, params=param)
        response = DiscardMessage.to_obj(req.text)
        print(response)
示例#18
0
    def create_room(self):
        """ This creates a room	"""
        print("=== Creating a room ===")
        self.create_new_user()
        question = "What is the room's name? "
        room_name = self.get_str_input(question)
        question = 'How many players do you want to play with: '
        num_of_players = self.get_int_input(question)
        while num_of_players == 0:
            num_of_players = self.get_int_input(question)

        msg = {'username': self.player.get_nickname(), \
          'userid': self.player.get_user_id(), \
         'num_of_players': num_of_players,
         'room_name': room_name}
        param = {'cmd': RoomRequest.CREATE_A_ROOM.value}
        req = requests.post(self.room_url, json=msg, params=param)
        response = DiscardMessage.to_obj(req.text)
        print("Your new room id=", response.get_payload_value(value='data'))
        self.player.set_room_id(response.get_payload_value(value='data'))
示例#19
0
 def on_message(self, msg):
     # called anytime a new message is received
     print("Received from client ,msg=", msg)
     self.controller.handle_wsmessage(DiscardMessage.to_obj(msg))
示例#20
0
 def post(self):
     """Handles requests concerning a room"""
     recv_data = escape.json_decode(self.request.body)
     user_id = recv_data.get('userid')
     username = recv_data.get('username')
     query = self.get_query_argument('cmd')
     cmd = RoomRequest[query]
     msg_ = {}
     if cmd == RoomRequest.CREATE_A_ROOM:
         num_of_players = recv_data.get('num_of_players')
         room_name = recv_data.get('room_name')
         print('Num of players: ', num_of_players)
         if any((num_of_players < 2, num_of_players > 8)):
             raise web.HTTPError(
                 status_code=400,
                 log_message=
                 "Argument num_of_players must be between 2 and 8")
         else:
             room_id = self.controller.create_room(num_of_players,
                                                   room_name)
             self.controller.add_player_to_room(room_id, user_id, username)
             print('Room id: ', room_id)
             msg_ = DiscardMessage(
                 cmd=ClientRcvMessage.CREATE_A_ROOM_REP.value, data=room_id)
             self.write(DiscardMessage.to_json(msg_))
     elif cmd == RoomRequest.JOIN_ROOM:
         room_id = recv_data.get('roomid')
         if self.controller.can_join(room_id, user_id):
             self.controller.add_player_to_room(room_id, user_id, username)
             prompt_ = "You have been added to room " + str(room_id)
             msg_ = DiscardMessage(cmd=ClientRcvMessage.JOIN_ROOM_REP.value,
                                   prompt=prompt_)
             self.write(DiscardMessage.to_json(msg_))
         else:
             raise web.HTTPError(status_code=500,
                                 log_message="Room is full")
     elif cmd == RoomRequest.START_GAME:
         room_id = recv_data.get('roomid')
         if self.controller.can_start_game(room_id, user_id):
             self.controller.start_game(room_id)
             msg_ = DiscardMessage(
                 cmd=ClientRcvMessage.START_GAME_REP.value,
                 prompt=ClientRcvMessage.GAME_HAS_STARTED_REP.value)
         else:
             msg_ = DiscardMessage(
                 cmd=ClientRcvMessage.START_GAME_REP.value,
                 prompt=ClientRcvMessage.GAME_HAS_ALREADY_STARTED_REP.value)
         self.write(DiscardMessage.to_json(msg_))
     elif cmd == RoomRequest.SET_FIRST_PLAYER:
         room_id = recv_data.get('roomid')
         self.controller.set_initial_player(user_id, room_id)
         player = self.controller.get_initial_player(room_id)
         msg_ = DiscardMessage(
             cmd=ClientRcvMessage.SET_FIRST_PLAYER_REP.value,
             prompt='Player to start:',
             data=player.nickname)
         self.write(DiscardMessage.to_json(msg_))
     elif cmd == RoomRequest.LEAVE_ROOM:
         pass
     else:
         pass