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