add toggle ready and player ids (#11)
This commit is contained in:
1 parent
72e3adc6f9
commit
d95641d168
3 files changed
+64
-35
No files matched your search
+13
-18
@@ -1,23 +1,18 @@
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
from pprint import pprint
|
||||
from websockets.sync.client import connect
|
||||
|
||||
|
||||
async def tcp_echo_client(message):
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", 8888)
|
||||
|
||||
data = {
|
||||
"action": "join",
|
||||
"name": "Johnny",
|
||||
}
|
||||
|
||||
writer.write(json.dumps(data).encode())
|
||||
writer.write_eof()
|
||||
await writer.drain()
|
||||
|
||||
msg = await reader.read()
|
||||
print(json.loads(msg.decode()))
|
||||
def hello():
|
||||
with connect("ws://localhost:8888") as websocket:
|
||||
websocket.send(json.dumps({"action": "join", "name": "ruedi"}))
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
websocket.send(json.dumps({"action": "toggleReady"}))
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
|
||||
|
||||
data = {"key": "value"}
|
||||
|
||||
asyncio.run(tcp_echo_client(json.dumps(data)))
|
||||
if __name__ == "__main__":
|
||||
hello()
|
||||
@@ -0,0 +1,20 @@
|
||||
from itertools import count
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
|
||||
PLAYER_IDS = count()
|
||||
T_PlayerDict = dict[str, str | int]
|
||||
|
||||
|
||||
class Player:
|
||||
def __init__(
|
||||
self, websocket: ServerConnection, name: str, is_spectator: bool
|
||||
) -> None:
|
||||
self.id = next(PLAYER_IDS)
|
||||
self.name = name
|
||||
self.websocket = websocket
|
||||
self.is_spectator = is_spectator
|
||||
self.is_ready = False
|
||||
|
||||
def as_dict(self) -> T_PlayerDict:
|
||||
return {"id": self.id, "name": self.name}
|
||||
+31
-17
@@ -1,21 +1,15 @@
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
from itertools import count
|
||||
from websockets.asyncio.server import ServerConnection, serve
|
||||
from player import Player, T_PlayerDict
|
||||
|
||||
|
||||
class Player:
|
||||
def __init__(
|
||||
self, websocket: ServerConnection, name: str, is_spectator: bool
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.websocket = websocket
|
||||
self.is_spectator = is_spectator
|
||||
T_PlayerStateDict = dict[str, T_PlayerDict | bool]
|
||||
T_SpectatorStateDict = dict[str, T_PlayerDict]
|
||||
|
||||
|
||||
MAX_PLAYERS = 2
|
||||
CLIENT_IDS = count()
|
||||
PLAYERS: set[Player] = set()
|
||||
|
||||
|
||||
@@ -23,15 +17,31 @@ def num_players() -> int:
|
||||
return len(list(filter(lambda x: not x.is_spectator, PLAYERS)))
|
||||
|
||||
|
||||
def get_players() -> list[str]:
|
||||
return [player.name for player in filter(lambda x: not x.is_spectator, PLAYERS)]
|
||||
def get_players() -> list[T_PlayerStateDict]:
|
||||
query = filter(lambda x: not x.is_spectator, PLAYERS)
|
||||
|
||||
players: list[T_PlayerStateDict] = []
|
||||
|
||||
for player in query:
|
||||
players.append({"player": player.as_dict(), "ready": player.is_ready})
|
||||
|
||||
return players
|
||||
|
||||
|
||||
def get_spectators() -> list[str]:
|
||||
return [player.name for player in filter(lambda x: x.is_spectator, PLAYERS)]
|
||||
def get_spectators() -> list[T_SpectatorStateDict]:
|
||||
query = filter(lambda x: x.is_spectator, PLAYERS)
|
||||
|
||||
players: list[T_SpectatorStateDict] = []
|
||||
|
||||
for player in query:
|
||||
players.append({"player": player.as_dict()})
|
||||
|
||||
return players
|
||||
|
||||
|
||||
def get_gamestate() -> dict[str, dict[str, list[str]]]:
|
||||
def get_gamestate() -> dict[
|
||||
str, dict[str, list[T_PlayerStateDict] | list[T_SpectatorStateDict]]
|
||||
]:
|
||||
return {
|
||||
"gamestate": {
|
||||
"players": get_players(),
|
||||
@@ -49,7 +59,7 @@ async def handler(websocket: ServerConnection):
|
||||
# client_id = next(CLIENT_IDS)
|
||||
# CLIENTS.add(Client(websocket))
|
||||
|
||||
player = None
|
||||
player: Player | None = None
|
||||
|
||||
try:
|
||||
async for msg in websocket:
|
||||
@@ -71,20 +81,24 @@ async def handler(websocket: ServerConnection):
|
||||
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
|
||||
player.is_ready = False
|
||||
else:
|
||||
player.is_spectator = True
|
||||
|
||||
elif raw_action["action"] == "toggleReady":
|
||||
player.is_ready = not player.is_ready
|
||||
|
||||
data = get_gamestate()
|
||||
await broadcast(data)
|
||||
|
||||
except Exception as exception:
|
||||
print(str(exception))
|
||||
await websocket.close(1011)
|
||||
|
||||
else:
|
||||
await websocket.close(1000)
|
||||
|
||||
|
||||
Reference in new issue
Block a user