6人网球游戏双玩家选择功能开发问题求助
Let's walk through fixing your player selection system to resolve both of your issues: limiting the selection to exactly two players, and hiding already chosen players during the second pick.
First, let's break down the problems in your current code:
- The
whileloop runs indefinitely because you're modifyingSelectioninstead of tracking how many players have been chosen. There's no check to stop after two selections. - There's no mechanism to track which players are already selected, so all six players still appear in the menu for the second pick.
Here's a cleaned-up, functional solution:
# Track selected players with a list selected_players = [] while len(selected_players) < 2: print("\n=== Player Selection Menu ===") # Print only available players (not yet selected) for player_num in range(1, 7): if player_num not in selected_players: print(f"{player_num}. Player {player_num}") print("7. Quit") # Get and validate user input try: selection = int(input(f"Please choose player {len(selected_players) + 1}: ")) except ValueError: print("Invalid input! Please enter a number between 1 and 7.") continue # Handle quit option if selection == 7: print("Exiting selection.") break # Handle valid player selection if 1 <= selection <= 6: if selection in selected_players: print(f"Player {selection} is already chosen! Pick another.") else: selected_players.append(selection) print(f"You chose Player {selection}.") else: print("Invalid option! Please choose a number between 1 and 7.") # If two players were selected, display the match if len(selected_players) == 2: print(f"\nTennis match set: Player {selected_players[0]} vs Player {selected_players[1]}!")
Key improvements explained:
- Selection tracking: We use a
selected_playerslist to keep track of chosen players. The loop runs only until this list has 2 entries, so we stop exactly after two valid selections. - Dynamic menu: When printing the menu, we skip any player numbers already in
selected_players, so they won't appear for the second pick. - Input validation: Added a
try/exceptblock to handle non-numeric inputs, plus checks to prevent selecting the same player twice or invalid options. - Reduced redundancy: No more separate functions for each player—we handle selections with a single logic flow, making the code easier to maintain.
- Clear feedback: The user gets clear messages about their choices, errors, and the final match setup.
内容的提问来源于stack exchange,提问作者Darwin Uthman
相关产品推荐
相关产品推荐

