Пример #1
0
 def get(self, request, max_players, random_list=True):
     token = TokenMiddleware.get_token(request)
     if token is None:
         raise NotAuthenticated("Token invalid or expired!")
     if not isinstance(max_players, int):
         try:
             max_players = int(max_players)
         except TypeError:
             raise ParseError(detail="MAX_PLAYERS must be an instance of int")
     
     players = []
     try:
         """ get all available players """
         player = OnlineChecker()
         cnt, players = player.get_available_players(max_list=max_players, random_order=random_list)
     except Exception as exc:
         raise APIException(detail=exc)
     
     ''' get players details '''
     response_data = []
     if len(players) > 0:
         ''' extract players based on uid '''
         players = User.objects(uid__in=players)
         if len(players) > 0: 
             ''' serialize players '''
             serializer = UserSerializer(players, many=True)
             response_data = serializer.data
     return Response(response_data)
Пример #2
0
    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!")