From 7ea63ce6236cb30d7ac2b7b471395d3e3248ec30 Mon Sep 17 00:00:00 2001 From: Stefan Rupp Date: Sat, 16 May 2020 19:32:57 +0200 Subject: [PATCH] prevent double-play through race condition --- views/player.py | 33 +++++++++++++++++++++------------ wiz_game.py | 2 +- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/views/player.py b/views/player.py index a8c9995..18912da 100644 --- a/views/player.py +++ b/views/player.py @@ -2,7 +2,7 @@ from app_instance import api from wiz_game import the_game from starlette.websockets import WebSocketDisconnect - +import asyncio @api.route("/player/{player}") def show(req, resp, player: str): @@ -31,19 +31,28 @@ def show(req, resp, player: str): @api.route("/player/{player}/play/{card}") async def play(req, resp, player: str, card: str): + lock = asyncio.Lock() p = int(player) c = int(card) - the_game.play_card(p, c) - if the_game.is_hand_finished(): - print("hand finished") - trick_winner, highest_card = the_game.get_trick_winner() - trick_winner.take_trick() - #the_game.next_hand() - elif the_game.is_trick_finished(): - print("trick finished") - trick_winner, highest_card = the_game.get_trick_winner() - trick_winner.take_trick() - the_game.next_trick() + + async with lock: + try: + isActive = the_game.players_ordered[the_game.active_player].id == p + except IndexError: + isActive = False + print("show p: {} | {}".format('None', p)) + if isActive: + the_game.play_card(p, c) + if the_game.is_hand_finished(): + print("hand finished") + trick_winner, highest_card = the_game.get_trick_winner() + trick_winner.take_trick() + #the_game.next_hand() + elif the_game.is_trick_finished(): + print("trick finished") + trick_winner, highest_card = the_game.get_trick_winner() + trick_winner.take_trick() + the_game.next_trick() url = '/player/'+player for ws in the_game.websockets: diff --git a/wiz_game.py b/wiz_game.py index 2ca616a..03998a9 100644 --- a/wiz_game.py +++ b/wiz_game.py @@ -209,6 +209,6 @@ class WizGame: return self.start_player-1 -p = ["Astrid", "Stephan", "Patrice", "struppi"] +p = ["A", "B", "C", "D", "E"] the_game = WizGame(p)