コード例 #1
0
ファイル: views.py プロジェクト: noQ/TriviaOnline
    def post(self, request):
        token = TokenMiddleware.get_token(request)
        if token is None:
            raise NotAuthenticated("Token invalid or expired!")
        ''' check if token has user attribute '''
        if not token.has_key("user"):
            raise NotAuthenticated()
        user = token.get("user")
        uid  = user.uid
        
        """ get data from request """
        try:
            data = JSONParser().parse(request)
            data = data.get(PARAMETER_DATA)
        except JSONDecodeError:
            raise ParseError(detail="No data found on the request")
        
        session_name = WebRequestParameter.get_data(PARAMETER_SESSION, data)
        if session_name is None:
            raise ParseError(detail="Game session is not set on the request")
        
        ''' get session '''
        game_session = GameSession()
        ''' check if session exists '''
        if not game_session.find_session(session_name):
            return Error("Unable to join. Invalid session",
                         HttpStatus.SESSION_INVALID.value
                         ).show()
        ''' get plugin data '''
        session = game_session.get_session()
        if session is None:
            raise APIException("No session found with ID %s" % session_name)
        ''' load plugin data '''
        if session.game_name is None:
            raise APIException("Game is not set on session with ID %s" % session_name)
        
        ''' load plugin dictionary '''
        from TriviaOnline.settings import PLUGINS
        ''' get plugin by name '''
        plugin = PluginHandler.get_from_dict(PLUGINS, str(session.game_name))
        ''' check if session has game logic set '''
        game_logic = game_session.has_game_logic()
        if game_logic is None:
            ''' get game logic from plugin '''
            game_logic = plugin.game_logic()
            if game_logic:
                game_session.set_game_logic(game_logic)

        ''' get server info '''
        server_info = plugin.get_server_info()
        ''' check session on RT server '''
        try:
            action = Action.check_session(session_name)
            client = ServerActionHandler(
                                         (settings.GAME_SERVER_ADDRES, 
                                          settings.GAME_SERVER_PORT
                                          )
                                         )
            client.set_data(action)
            client.send()
            ''' retrieve data from server '''
            data = str(client.get_reveived_data())
            if data == ServerCommand.NO_DATA or data == ServerCommand.FAILED:
                raise APIException("Session not found on RT server!")
        except:
            traceback.print_exc()
            raise APIException("Unable to retrieve data from RT server!")
        
        response = {
                    'server' : server_info,
                    'game_logic' : game_logic
                    }
        ''' construct response '''
        return Response(response)
コード例 #2
0
ファイル: views.py プロジェクト: noQ/TriviaOnline
    def post(self, request):
        token = TokenMiddleware.get_token(request)
        if token is None:
            raise NotAuthenticated("Token invalid or expired!")
        ''' check if token has user attribute '''
        if not token.has_key("user"):
            raise NotAuthenticated()
        user = token.get("user")
        uid  = user.uid
        
        """ get data from request """
        try:
            data = JSONParser().parse(request)
            data = data.get(PARAMETER_DATA)
        except JSONDecodeError:
            raise ParseError(detail="No data found on the request")
        
        ''' get game name '''
        game_name = WebRequestParameter.get_data(PARAMETER_GAME_NAME, data)
        if game_name is None:
            game_name = self.GAME_NAME
        
        ''' get numbers of players to play this game '''
        game_slots = WebRequestParameter.get_data(PARAMETER_SLOTS, data)
        if game_slots is None:
            game_slots = self.DEFAULT_SLOTS
        else:
            if not isinstance(game_slots, int):
                try:
                    game_slots = int(game_slots)
                except TypeError:
                    raise ParseError(detail="SLOTS must be an instance of int")
            
        ''' pickup players in random order '''
        random_order = WebRequestParameter.get_data(PARAMETER_RANDOM, data)
        if random_order is None:
            random_order = False
        else:
            random_order = to_bool(random_order)

        ''' return a list with max players available (online) '''
        search_max_players = WebRequestParameter.get_data(PARAMETER_MAX_PLAYERS_TO_SEARCH, data)
        if search_max_players is None:
            search_max_players = self.MAX_PLAYERS_TO_SEARCH
        
        ''' auto join in game '''
        auto_pickup = WebRequestParameter.get_data(PARAMETER_AUTO_PICKUP, data)
        if auto_pickup is None:
            auto_pickup = self.AUTO_JOIN

        player = OnlineChecker()
        ''' create/get game session '''        
        sess = GameSession(user=user)
        ''' 1. check if current user not belongs to other session '''
        session = sess.get_awaiting_sessions()
        if session is None:
            ''' set game name '''
            sess.set_game_name(game_name)
            ''' create new session with one player (the session owner) '''
            sess.create()
            ''' pick up random players if available from a list with MAX_PLAYERS '''
            player = OnlineChecker()
            cnt, players = player.get_available_players(
                                                        max_list=search_max_players,
                                                        random_order=random_order
                                                        )
            if cnt == 0:
                ''' if no one is online then play this game using bot player '''
                return Error("No online players available!",
                              HttpStatus.NO_ONLINE_PLAYERS.value
                            ).show()
            ''' shuffle players '''
            '''
            if uid in players:
                try:
                    players.remove(str(uid))
                except ValueError:
                    pass
            ''' 
            random.shuffle(players)
            ''' just pick the players needed to start the game '''
            if cnt < sess.get_available_slots():
                return Error("Not enough players to start the game!",
                                 HttpStatus.NOT_ENOUGHT_PLAYERS.value
                                 ).show()                    
            
            if cnt > game_slots:
                players = players[:game_slots]
            ''' extract players by UID '''
            print "players: " + str(players)
            users =  User.objects(uid__in=players)
            if len(users) == 0:
                raise APIException("No users found in DB!")
            ''' add players in session '''
            has_players = False
            for user in users:
                ''' if has enough slots then join '''
                if not sess.has_free_slots():
                    break
                ''' add players in session '''
                player = Player(uid = user.uid,
                            status = PlayerStatus.not_ready.value
                        )
                ''' set player additional info '''
                player.get_player_info(user)
                ''' add player to current session '''
                sess.add_player(player)
                ''' set available game slots '''                
                sess.get_session().available_slots -= 1
                has_players = True
            if has_players:
                sess.get_session().save()
                
            ''' get session players '''
            players = sess.get_players()
            if players is None:
                return Error("No players found in current session!").show()
            
            try:
                ''' create RTS session '''
                action = Action.create_session(sess, self.DEFAULT_SLOTS, player)
                client = ServerActionHandler(
                                             (settings.GAME_SERVER_ADDRES, 
                                              settings.GAME_SERVER_PORT)
                                             )
                client.set_data(action)
                client.send()
            except:
                traceback.print_exc()
            return Response(players)
        
        else:
            ''' check if session is expired '''
            session_time = sess.get_session().expired_at
            if sess.is_expired(session_time):
                ''' get session owner and set flag: is_available to play other game '''
                session_owner = sess.get_session().owner_uid
                session_name = sess.get_session().name
                player.set_uid(session_owner)
                player.is_available()
                ''' destroy session is expired '''
                sess.destroy(session_name)
                
                return Error("Session is expired!", HttpStatus.SESSION_EXPIRED).show()
            ''' if session has free slots then join in session '''
            if sess.has_free_slots():
                if sess.can_join():
                    return Response(sess.get_players())
                else:
                    ''' return error message if session is full '''
                    return Error("Unable to join. Session is full!",
                                     HttpStatus.SESSION_FULL.value
                                     ).show()
            else:
                ''' set player status to ready to play '''
                players = sess.set_player_status(sess.user.uid,
                                                 PlayerStatus.ready_to_play.value
                                                 )
                if players is None:
                    return Error("No players found in current session!").show()
                ''' set session status ready to play '''
                sess.get_session().status = SessionStatus.ready_to_play.value
                sess.get_session().save()
                
                ''' join user to sesssion '''
                try:
                    action = Action.join_session(sess, sess.user)
                    client = ServerActionHandler(
                                                 (settings.GAME_SERVER_ADDRES, 
                                                  settings.GAME_SERVER_PORT
                                                  )
                                                 )
                    client.set_data(action)
                    client.send()
                except:
                    traceback.print_exc()
                
                return Response(sess.get_players())
        raise APIException("Unable to process data!")