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 json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
from itertools import count
|
from itertools import count
|
||||||
from websockets.asyncio.server import serve, ServerConnection
|
from websockets.asyncio.server import ServerConnection, serve
|
||||||
|
|
||||||
|
|
||||||
class Client:
|
class Player:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self, websocket: ServerConnection, name: str, is_spectator: bool
|
||||||
client_id: int,
|
) -> None:
|
||||||
name: str,
|
|
||||||
):
|
|
||||||
self.client_id = client_id
|
|
||||||
self.name = name
|
self.name = name
|
||||||
self.is_player: bool = True
|
self.websocket = websocket
|
||||||
|
self.is_spectator = is_spectator
|
||||||
|
|
||||||
|
|
||||||
|
MAX_PLAYERS = 2
|
||||||
CLIENT_IDS = count()
|
CLIENT_IDS = count()
|
||||||
clients = {}
|
PLAYERS: set[Player] = set()
|
||||||
|
|
||||||
|
|
||||||
async def handle_echo(websocket: ServerConnection):
|
def num_players() -> int:
|
||||||
client_id = next(CLIENT_IDS)
|
return len(list(filter(lambda x: not x.is_spectator, PLAYERS)))
|
||||||
|
|
||||||
print("got a client")
|
|
||||||
|
|
||||||
msg = await websocket.recv()
|
def get_players() -> list[str]:
|
||||||
msg: dict = json.loads(msg)
|
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": {
|
"gamestate": {
|
||||||
"players": [client.name for client in clients.values()],
|
"players": get_players(),
|
||||||
"spectators": [],
|
"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 def handler(websocket: ServerConnection):
|
||||||
async with serve(handle_echo, "localhost", 8888) as server:
|
# 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()
|
await server.serve_forever()
|
||||||
|
|
||||||
|
|
||||||
asyncio.run(start_le_server())
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
Reference in new issue
Block a user