feat: add exit game event and improve enter game

This commit is contained in:
2021-07-01 13:51:34 -04:00
parent 297c8279c7
commit a4c855cc2c

37
main.py
View File

@@ -7,43 +7,60 @@ import json
import websockets
GAMES = {}
# EVENT RESPONSES
def wait_for_player_response():
return json.dump({"type": "wait_for_player"})
def wait_for_opponent_response():
return json.dumps({"type": "wait_for_opponent"})
def start_game_response():
return json.dump({"type": "start_game"})
return json.dumps({"type": "start_game"})
def exit_game_response():
return json.dumps({"type": "exit_game"})
# EVENTS
async def enter_game(game_id, player_web_socket):
# TODO fix asssumption that there will only be two players per game
""" TODO fix asssumption that there will only be two players per game """
# if game does not exist, create it
if game_id not in GAMES:
GAMES[game_id] = {'players': [player_web_socket], 'game_id': game_id}
message = wait_for_player_response()
message = wait_for_opponent_response()
await player_web_socket.send(message)
else:
# if game exists, add player to game if they are not already in it
elif player_web_socket.remote_address[0] not in map(lambda p: p.remote_address[0], GAMES[game_id]['players']):
GAMES[game_id]['players'].append(player_web_socket)
message = start_game_response()
await asyncio.wait([player.send(message) for player in GAMES[game_id]['players']])
else:
print("Already in game...")
async def exit_game(game_id):
players = GAMES[game_id]['players']
del GAMES[game_id]
message = exit_game_response()
await asyncio.wait([player.send(message) for player in players])
# --------------------------
async def init(websocket, path):
data = ""
try:
async for message in websocket:
print(websocket.remote_address)
data = json.loads(message)
if data["action"] == "enter_game":
await enter_game(data["gameId"], websocket)
else:
print("Unsupported action...")
finally:
if data and "gameId" in data:
print("Exiting game...")
await exit_game(data["gameId"])
print("Connection closed...")
#start_server = websockets.serve(init, "", int(os.environ["PORT"]))
start_server = websockets.serve(init, "localhost", 5001)
start_server = websockets.serve(init, "", 5001)
#start_server = websockets.serve(init, "localhost", 5001)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()