add rejoin action (#12)
* answer to join call * add is_disconnected flag * add rejoin action * fix missing json dumps * fix old websocket object used after rejoin * add disconnect, reconnect and send message logic * use player object to send dataw * (wip) add tests for disconnect * fix abgelieferte gugus * turn off readyness and enable spectator in disconnect function
This commit is contained in:
1 parent
d95641d168
commit
465eb5554c
3 files changed
+84
-15
No files matched your search
@@ -1,17 +1,40 @@
|
||||
import json
|
||||
import time
|
||||
|
||||
from pprint import pprint
|
||||
from websockets.sync.client import connect
|
||||
|
||||
|
||||
actions = [
|
||||
({"action": "join", "name": "ruedi"}, True),
|
||||
({"action": "toggleReady"}, False),
|
||||
]
|
||||
|
||||
|
||||
def hello():
|
||||
with connect("ws://localhost:8888") as websocket:
|
||||
websocket.send(json.dumps({"action": "join", "name": "ruedi"}))
|
||||
for action, direct_response in actions:
|
||||
websocket.send(json.dumps(action))
|
||||
if direct_response:
|
||||
message = json.loads(websocket.recv())
|
||||
player_id = int(message["player"]["id"])
|
||||
pprint(message)
|
||||
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
websocket.send(json.dumps({"action": "toggleReady"}))
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
with connect("ws://localhost:8888") as websocket:
|
||||
websocket.send(json.dumps({"action": "rejoin", "id": player_id}))
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
message = json.loads(websocket.recv())
|
||||
pprint(message)
|
||||
|
||||
# websocket.send(json.dumps({"action": "toggleReady"}))
|
||||
# message = json.loads(websocket.recv())
|
||||
# pprint(message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+17
-1
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from itertools import count
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
@@ -12,9 +13,24 @@ class Player:
|
||||
) -> None:
|
||||
self.id = next(PLAYER_IDS)
|
||||
self.name = name
|
||||
self.websocket = websocket
|
||||
self.websocket: ServerConnection | None = websocket
|
||||
self.is_spectator = is_spectator
|
||||
self.is_ready = False
|
||||
self.is_disconnected = False
|
||||
|
||||
def disconnect(self) -> None:
|
||||
self.is_disconnected = True
|
||||
self.is_spectator = True
|
||||
self.is_ready = False
|
||||
self.websocket = None
|
||||
|
||||
def reconnect(self, websocket: ServerConnection) -> None:
|
||||
self.is_disconnected = False
|
||||
self.websocket = websocket
|
||||
|
||||
async def send_message(self, message) -> None:
|
||||
if not self.is_disconnected and self.websocket is not None:
|
||||
await self.websocket.send(json.dumps(message))
|
||||
|
||||
def as_dict(self) -> T_PlayerDict:
|
||||
return {"id": self.id, "name": self.name}
|
||||
+42
-12
@@ -2,13 +2,12 @@ import json
|
||||
import asyncio
|
||||
|
||||
from websockets.asyncio.server import ServerConnection, serve
|
||||
from websockets import exceptions
|
||||
from player import Player, T_PlayerDict
|
||||
|
||||
|
||||
T_PlayerStateDict = dict[str, T_PlayerDict | bool]
|
||||
T_SpectatorStateDict = dict[str, T_PlayerDict]
|
||||
|
||||
|
||||
MAX_PLAYERS = 2
|
||||
PLAYERS: set[Player] = set()
|
||||
|
||||
@@ -17,6 +16,13 @@ def num_players() -> int:
|
||||
return len(list(filter(lambda x: not x.is_spectator, PLAYERS)))
|
||||
|
||||
|
||||
def is_spectator() -> bool:
|
||||
if num_players() < MAX_PLAYERS:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
def get_players() -> list[T_PlayerStateDict]:
|
||||
query = filter(lambda x: not x.is_spectator, PLAYERS)
|
||||
|
||||
@@ -50,9 +56,9 @@ def get_gamestate() -> dict[
|
||||
}
|
||||
|
||||
|
||||
async def broadcast(data):
|
||||
async def broadcast(message):
|
||||
for player in PLAYERS:
|
||||
await player.websocket.send(json.dumps(data))
|
||||
await player.send_message(message)
|
||||
|
||||
|
||||
async def handler(websocket: ServerConnection):
|
||||
@@ -64,19 +70,32 @@ async def handler(websocket: ServerConnection):
|
||||
try:
|
||||
async for msg in websocket:
|
||||
raw_action = json.loads(msg)
|
||||
print(raw_action)
|
||||
|
||||
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)
|
||||
|
||||
player = Player(websocket, name, is_spectator())
|
||||
PLAYERS.add(player)
|
||||
|
||||
await player.send_message({"player": player.as_dict()})
|
||||
|
||||
elif raw_action["action"] == "rejoin":
|
||||
player_id = int(raw_action["id"])
|
||||
query = list(filter(lambda x: x.id == player_id, PLAYERS))
|
||||
|
||||
if len(query) == 0:
|
||||
print(f"player id not found: {player_id}")
|
||||
pass
|
||||
else:
|
||||
player = query[0]
|
||||
player.reconnect(websocket)
|
||||
player.is_spectator = True
|
||||
player.is_ready = False
|
||||
|
||||
print(f"{player.name} rejoined")
|
||||
|
||||
await player.send_message({"player": player.as_dict()})
|
||||
|
||||
else:
|
||||
if player is None:
|
||||
raise Exception("Player has not joined.")
|
||||
@@ -93,13 +112,24 @@ async def handler(websocket: ServerConnection):
|
||||
player.is_ready = not player.is_ready
|
||||
|
||||
data = get_gamestate()
|
||||
print("broadcasting")
|
||||
await broadcast(data)
|
||||
|
||||
for player in PLAYERS:
|
||||
print(player.as_dict())
|
||||
|
||||
except exceptions.ConnectionClosed:
|
||||
print("client has disconnected")
|
||||
|
||||
if player is not None:
|
||||
player.disconnect()
|
||||
|
||||
except Exception as exception:
|
||||
print(str(exception))
|
||||
await websocket.close(1011)
|
||||
|
||||
else:
|
||||
print("exited client polling loop")
|
||||
await websocket.close(1000)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user