The before code allows any player to act at any time, causing chaos. The after code uses a TurnManager to track whose turn it is, allowing only the current player to act and then moving to the next player in order.
### Before: No turn management, players can act anytime
class Game:
def __init__(self, players):
self.players = players
def player_action(self, player, action):
print(f"{player} performs {action}")
### After: Enforced player turn management
class TurnManager:
def __init__(self, players):
self.players = players
self.current_index = 0
def current_player(self):
return self.players[self.current_index]
def next_turn(self):
self.current_index = (self.current_index + 1) % len(self.players)
class GameWithTurns:
def __init__(self, players):
self.turn_manager = TurnManager(players)
def player_action(self, player, action):
if player != self.turn_manager.current_player():
print(f"It's not {player}'s turn!")
return
print(f"{player} performs {action}")
self.turn_manager.next_turn()