add broadcast upon join (#10)
* add broadcast upon join * add max players * add toggleRole action * add simple error handling * add player check when toggling role * fix backend-breaking bug
This commit is contained in:
1 parent
429b0cb3cd
commit
72e3adc6f9
1 file changed
+71
-26
+71
-26
@@ -1,53 +1,98 @@
|
||||
import asyncio
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
from itertools import count
|
||||
from websockets.asyncio.server import serve, ServerConnection
|
||||
from websockets.asyncio.server import ServerConnection, serve
|
||||
|
||||
|
||||
class Client:
|
||||
class Player:
|
||||
def __init__(
|
||||
self,
|
||||
client_id: int,
|
||||
name: str,
|
||||
):
|
||||
self.client_id = client_id
|
||||
self, websocket: ServerConnection, name: str, is_spectator: bool
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.is_player: bool = True
|
||||
self.websocket = websocket
|
||||
self.is_spectator = is_spectator
|
||||
|
||||
|
||||
MAX_PLAYERS = 2
|
||||
CLIENT_IDS = count()
|
||||
clients = {}
|
||||
PLAYERS: set[Player] = set()
|
||||
|
||||
|
||||
async def handle_echo(websocket: ServerConnection):
|
||||
client_id = next(CLIENT_IDS)
|
||||
def num_players() -> int:
|
||||
return len(list(filter(lambda x: not x.is_spectator, PLAYERS)))
|
||||
|
||||
print("got a client")
|
||||
|
||||
msg = await websocket.recv()
|
||||
msg: dict = json.loads(msg)
|
||||
def get_players() -> list[str]:
|
||||
return [player.name for player in filter(lambda x: not x.is_spectator, PLAYERS)]
|
||||
|
||||
if not msg["action"] == "join":
|
||||
raise Exception("wtfffff")
|
||||
|
||||
name = msg["name"]
|
||||
def get_spectators() -> list[str]:
|
||||
return [player.name for player in filter(lambda x: x.is_spectator, PLAYERS)]
|
||||
|
||||
clients[client_id] = Client(client_id, name)
|
||||
|
||||
data = {
|
||||
def get_gamestate() -> dict[str, dict[str, list[str]]]:
|
||||
return {
|
||||
"gamestate": {
|
||||
"players": [client.name for client in clients.values()],
|
||||
"spectators": [],
|
||||
"players": get_players(),
|
||||
"spectators": get_spectators(),
|
||||
}
|
||||
}
|
||||
|
||||
await websocket.send(json.dumps(data))
|
||||
|
||||
async def broadcast(data):
|
||||
for player in PLAYERS:
|
||||
await player.websocket.send(json.dumps(data))
|
||||
|
||||
|
||||
async def start_le_server():
|
||||
async with serve(handle_echo, "localhost", 8888) as server:
|
||||
async def handler(websocket: ServerConnection):
|
||||
# client_id = next(CLIENT_IDS)
|
||||
# CLIENTS.add(Client(websocket))
|
||||
|
||||
player = None
|
||||
|
||||
try:
|
||||
async for msg in websocket:
|
||||
raw_action = json.loads(msg)
|
||||
|
||||
if raw_action["action"] == "join":
|
||||
name = raw_action["name"]
|
||||
|
||||
if num_players() < MAX_PLAYERS:
|
||||
is_spectator = False
|
||||
else:
|
||||
is_spectator = True
|
||||
|
||||
player = Player(websocket, name, is_spectator)
|
||||
|
||||
PLAYERS.add(player)
|
||||
|
||||
else:
|
||||
if player is None:
|
||||
raise Exception("Player has not joined.")
|
||||
|
||||
player: Player
|
||||
|
||||
if raw_action["action"] == "toggleRole":
|
||||
if player.is_spectator:
|
||||
if num_players() < MAX_PLAYERS:
|
||||
player.is_spectator = False
|
||||
else:
|
||||
player.is_spectator = True
|
||||
|
||||
data = get_gamestate()
|
||||
await broadcast(data)
|
||||
except Exception as exception:
|
||||
print(str(exception))
|
||||
await websocket.close(1011)
|
||||
else:
|
||||
await websocket.close(1000)
|
||||
|
||||
|
||||
async def main():
|
||||
async with serve(handler, "localhost", 8888) as server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
asyncio.run(start_le_server())
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in new issue
Block a user