如何实现用于判断游戏结束状态的end_of_game函数?
Implementing the
end_of_game Function for Your Card Game Let's walk through how to build this function step by step, based on your rules:
First, let's restate the rules in plain language to make sure we're aligned:
- Rule 1: If any player hasn't chosen to stay and hasn't busted yet, the game is still ongoing (we return
False). - Rule 2: Players who are either "busted but didn't stay" or "stayed but didn't bust" are done with their turn. The game only ends when all players fall into one of these two "done" categories.
Here's a straightforward implementation that follows these rules:
players = [{'name': 'Player 1', 'score': 23, 'stayed': False, 'at_14': True, 'bust': True}, {'name': 'Player 2', 'score': 17, 'stayed': True, 'at_14': True, 'bust': False}, {'name': 'Player 3', 'score': 19, 'stayed': True, 'at_14': True, 'bust': False}, {'name': 'Player 4', 'score': 19, 'stayed': True, 'at_14': True, 'bust': False}] def end_of_game(players): # Loop through each player to check their active status for player in players: # If this player is still active (no stay, no bust), game isn't over if not player['stayed'] and not player['bust']: return False # If we exit the loop, all players are done — game ends return True
How this works:
- We iterate over every player in the list. As soon as we find one that's still active (
stayed=Falseandbust=False), we immediately returnFalsebecause the game can't be over yet. - If we make it through all players without finding any active ones, that means every player is either busted (without staying) or stayed (without busting) — so we return
Trueto signal the game is over.
Test case with your sample data:
Your sample players all fall into the "done" categories: Player 1 is busted and didn't stay, while Players 2-4 stayed and didn't bust. Calling end_of_game(players) will return True, which is correct.
If you added a new player like {'name': 'Player 5', 'score': 12, 'stayed': False, 'at_14': False, 'bust': False}, the function would return False right away, since that player is still in the game.
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

