def roomjoin(): '''Attempt to assign the client a room. If the client already has a room (i.e. from spectating), let them join the same room. Spectators are given the first room returned by Redis and are automatically subscribed to any updates. Players must find the first room with an empty slot. The room they are spectating may be full, so we may need to send them elsewhere. ''' if bool(app.config['DEBUG_MODE']): print("EVENT: roomjoin:", session) isPlayer = session.get('player') is not None if session.get('room') is None: if Room.count() < 1: Room.create() rooms = list(Room.all()) if isPlayer: for room in rooms: if len(room.players) < DEFAULT_ARENA_SIZE: room.add_player(session.get('player')) break else: # Redis returns pseudo-random order of rooms, spectate the first room = rooms[0] session['room'] = room.id join_room(str(room.id)) if bool(app.config['DEBUG_MODE']): print( "EVENT: roomjoin: user '{}' joined room '{}'. session id: {}, session: {}" .format(session.get('username', "None"), room.id, session.sid, session)) else: room = Room.load(session.get('room')) if len(room.players) > DEFAULT_ARENA_SIZE: leave_room(session['room']) session['room'] = None roomjoin() else: room.add_player(session['player']) join_room(session['room']) if "username" in session and session['username'] is not None: # Notify the room that a new player has joined. emit('roomjoin', { "username": session['username'], "room": room.id }, room=str(room.id))
def roomleave(): '''Cleanly remove the client from the room and clear any session values.''' isPlayer = 'player' in session and session.get('player') is not None if session.get('room') is not None: room = Room.load(session['room']) leave_room(session.get('room')) if isPlayer: room.remove_player(session['player']) if len(room.players) == 0: room.delete() del session['room']
def constructUpdate(room: models.Room): '''Construct an update for the socketio server to send out. All mesages are published to the 'serverUpdate' channel with the following schema: { "timestamp": (float) Unix time when values were calculated, "roomid": (string) Client room where the update should be sent, "payload": see `models.Room.to_json()` } ''' data = '{"timestamp": ' + str(time()) data += ', "roomid": "' + str(room.id) data += '", "payload": ' + json.dumps(room.to_json()) + '}' r.publish('serverUpdate', data)
def serverUpdate(action='cycleUpdate'): roomid = session.get('room') j = Room.load(roomid).to_json() j['action'] = action emit('serverUpdate', j)