def join_game(self, gameobj): data = {"controllerid": -1, "streaming_port": -1} try: controllers = range(gameobj.max_limit) occupied = GameSession.objects.filter(game=gameobj).values_list("controller", flat=True) available = list(set(controllers) - set(occupied)) data["controllerid"] = available[0] except IndexError: return data if data["controllerid"] != -1: command = JOIN_CMD + str(data["controllerid"]).zfill(4) result = utils.connect_to_CPP(command) if result != ERROR_MSG: data["streaming_port"] = data["controllerid"] + PORT_NUM return data
def join_game(gameobj, user): user_controller = INVALID try: controllers = range(gameobj.max_limit) # Valid controller id # Controller id currently used by user occupied = GameSession.objects.filter(game = gameobj). \ values_list('controller', flat=True) # Find suitable controller id available = list(set(controllers) - set(occupied)) user_controller = available[0] except IndexError: return None if(user_controller != INVALID): session = GameSession.objects.create( game = gameobj, user = user, controller = user_controller, streaming_port = user_controller + PORT_NUM ) data = { 'game_session_id': session.id, 'controller': user_controller, 'streaming_port': session.streaming_port, 'streaming_ip': gameobj.address, 'game_id': gameobj.id, 'username': user.username, 'command': 'join' } result = utils.connect_to_CPP(data) if(result != ERROR_MSG): return session # Failed: rollback session.delete() return None