Skip to content

Commit

Permalink
Merge pull request #31 from corail-research/remove_timer
Browse files Browse the repository at this point in the history
remove time manager
  • Loading branch information
YoannSab authored Jun 5, 2024
2 parents 3ea0ae2 + 9e818c4 commit 09b0272
Show file tree
Hide file tree
Showing 4 changed files with 325 additions and 303 deletions.
76 changes: 49 additions & 27 deletions src/seahorse/game/master.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ def __init__(
players_iterator: Iterable[Player],
log_level: str = "INFO",
port: int =8080,
hostname: str ="localhost"
hostname: str ="localhost",
time_limit: int = 15*60,
) -> None:
"""
Initializes a new instance of the GameMaster class.
Expand All @@ -56,10 +57,12 @@ def __init__(
log_level (str): The name of the log file.
"""
self.timetol = 1e-1
self.recorded_plays = []
# self.recorded_plays = []
self.name = name
self.current_game_state = initial_game_state
self.players = initial_game_state.players
self.remaining_time = {player.get_id(): time_limit for player in self.players}

player_names = [x.name for x in self.players]
if len(set(player_names))<len(self.players):
logger.error("Multiple players have the same name this is not allowed.")
Expand Down Expand Up @@ -93,20 +96,23 @@ async def step(self) -> GameState:
possible_actions = self.current_game_state.get_possible_heavy_actions()

start = time.time()
next_player.start_timer()
logger.info(f"time : {next_player.get_remaining_time()}")
# next_player.start_timer()
logger.info(f"time : {self.remaining_time[next_player.get_id()]}")

if isinstance(next_player,EventSlave):
action = await next_player.play(self.current_game_state)
action = await next_player.play(self.current_game_state, remaining_time=self.remaining_time[next_player.get_id()])
else:
action = next_player.play(self.current_game_state)

action = next_player.play(self.current_game_state, remaining_time=self.remaining_time[next_player.get_id()])
tstp = time.time()
if abs((tstp-start)-(tstp-next_player.get_last_timestamp()))>self.timetol:
next_player.stop_timer()
raise StopAndStartError()
self.remaining_time[next_player.get_id()] -= (tstp-start)
if self.remaining_time[next_player.get_id()] < 0:
raise SeahorseTimeoutError()

# if abs((tstp-start)-(tstp-next_player.get_last_timestamp()))>self.timetol:
# next_player.stop_timer()
# raise StopAndStartError()

next_player.stop_timer()
# next_player.stop_timer()

action = action.get_heavy_action(self.current_game_state)
if action not in possible_actions:
Expand All @@ -129,44 +135,55 @@ async def play_game(self) -> list[Player]:
"play",
json.dumps(self.current_game_state.to_json(),default=lambda x:x.to_json()),
)
self.recorded_plays.append(self.current_game_state.__class__.from_json(json.dumps(self.current_game_state.to_json(),default=lambda x:x.to_json())))
# self.recorded_plays.append(self.current_game_state.__class__.from_json(json.dumps(self.current_game_state.to_json(),default=lambda x:x.to_json())))
id2player={}
verdict_scores=[-1e9,-1e9]
# verdict_scores=[-1e9,-1e9]
for player in self.get_game_state().get_players() :
id2player[player.get_id()]=player.get_name()
logger.info(f"Player : {player.get_name()} - {player.get_id()}")
while not self.current_game_state.is_done():
try:
logger.info(f"Player now playing : {self.get_game_state().get_next_player().get_name()} - {self.get_game_state().get_next_player().get_id()}")
self.current_game_state = await self.step()
<<<<<<< remove_timer
# self.recorded_plays.append(self.current_game_state.__class__.from_json(json.dumps(self.current_game_state.to_json(),default=lambda x:x.to_json())))
=======
self.recorded_plays.append(self.current_game_state.__class__.from_json(json.dumps(self.current_game_state.to_json(),default=lambda x:x.to_json())))

>>>>>>> main
except (ActionNotPermittedError,SeahorseTimeoutError,StopAndStartError) as e:
if isinstance(e,SeahorseTimeoutError):
logger.error(f"Time credit expired for player {self.current_game_state.get_next_player()}")
elif isinstance(e,ActionNotPermittedError) :
logger.error(f"Action not permitted for player {self.current_game_state.get_next_player()}")
else:
logger.error(f"Player {self.current_game_state.get_next_player()} might have tried tampering with the timer.\n The timedelta difference exceeded the allowed tolerancy in GameMaster.timetol ")
# else:
# logger.error(f"Player {self.current_game_state.get_next_player()} might have tried tampering with the timer.\n The timedelta difference exceeded the allowed tolerancy in GameMaster.timetol ")

temp_score = copy.copy(self.current_game_state.get_scores())
id_player_error = self.current_game_state.get_next_player().get_id()
temp_score.pop(id_player_error)
self.winner = self.compute_winner(temp_score)
self.current_game_state.get_scores()[id_player_error] = -3
other_player = next(iter([player.get_id() for player in self.current_game_state.get_players() if player.get_id()!=id_player_error]))
self.current_game_state.get_scores()[other_player] = 0
scores = self.get_scores()
for key in scores.keys():
verdict_scores[int(id2player[key].split("_")[-1])-1]=-scores[key]
logger.info(f"{id2player[key]}:{scores[key]}")
temp_score[id_player_error] = -1e9
temp_score[other_player] = 1e9

# temp_score.pop(id_player_error)
self.winner = self.compute_winner(temp_score)

# self.current_game_state.get_scores()[id_player_error] = -3
# other_player = next(iter([player.get_id() for player in self.current_game_state.get_players() if player.get_id()!=id_player_error]))
# self.current_game_state.get_scores()[other_player] = 0

# scores = self.get_scores()
for key in temp_score.keys():
# verdict_scores[int(id2player[key].split("_")[-1])-1]=-scores[key]
logger.info(f"{id2player[key]}:{temp_score[key]}")

for player in self.get_winner() :
logger.info(f"Winner - {player.get_name()}")

await self.emitter.sio.emit("done",json.dumps(self.get_scores()))
logger.verdict(f"{verdict_scores[::-1]}")
with open(self.players[0].name+"_"+self.players[-1].name+"_"+str(time.time())+".json","w+") as f:
f.write(json.dumps(self.recorded_plays),default=lambda x:x.to_json())

logger.verdict(f"{self.current_game_state.get_next_player().get_name()} has been disqualified")

return self.winner

logger.info(f"Current game state: \n{self.current_game_state.get_rep()}")
Expand All @@ -179,15 +196,20 @@ async def play_game(self) -> list[Player]:
self.winner = self.compute_winner(self.current_game_state.get_scores())
scores = self.get_scores()
for key in scores.keys() :
verdict_scores[int(id2player[key].split("_")[-1])-1]=-scores[key]
# verdict_scores[int(id2player[key].split("_")[-1])-1]=-scores[key]
logger.info(f"{id2player[key]}:{(scores[key])}")

for player in self.get_winner() :
logger.info(f"Winner - {player.get_name()}")

await self.emitter.sio.emit("done",json.dumps(self.get_scores()))
<<<<<<< remove_timer
logger.verdict(f"{','.join(w.get_name() for w in self.get_winner())} has won the game")
=======
logger.verdict(f"{verdict_scores[::-1]}")

print(f"Time taken for the whole game : {time.time()-time_start}")
>>>>>>> main

return self.winner

Expand Down
Loading

0 comments on commit 09b0272

Please sign in to comment.