如何实现粉丝对比游戏猜对后生成全新随机嵌套字典选项?
Fixing the Follower Comparison Game: Generate New Options After Correct Guesses
Hey Alex, let's fix that issue where your game keeps reusing the same options after a correct guess. The core problem here is that when you recursively call game() after a correct answer, you're passing the original names and names2 variables instead of generating new random entries. Let's adjust the code to generate fresh, unique options every time the user gets it right, and also add proper game-over logic for incorrect guesses.
Here's the revised code:
import game_data import random import art def get_two_unique_entries(): """Helper function to generate two distinct random entries from game_data""" entry_a = random.choice(game_data.data) entry_b = random.choice(game_data.data) # Ensure we never get the same entry for both A and B while entry_a == entry_b: entry_b = random.choice(game_data.data) return entry_a, entry_b def game(correct_score=0): # Generate fresh, unique entries every time the game runs names, names2 = get_two_unique_entries() print(art.logo) follower_count = names['follower_count'] print(f"Compare A: {names['name']}, a {names['description']}, from {names['country']}.") print(art.vs) follower_count2 = names2['follower_count'] print(f"Against B: {names2['name']}, a {names2['description']}, from {names2['country']}.") answer = input("Who has more followers 'A' or 'B': ").lower() # Check if the user's guess is correct is_correct = (answer == 'a' and follower_count > follower_count2) or (answer == 'b' and follower_count2 > follower_count) if is_correct: correct_score += 1 print(f"Correct! Current score: {correct_score}") # Recurse with the updated score—new entries will be generated automatically game(correct_score) else: print(f"Sorry, that's wrong. Final score: {correct_score}") # Start the game game()
Key Improvements Explained:
- Unique Entry Generator: The
get_two_unique_entries()helper function ensures we never show the same profile for both A and B, and generates fresh pairs every time it's called. - No More Global Variables: We removed the global
namesandnames2—now new options are created every timegame()runs, which happens on startup and after every correct guess. - Simplified Recursion: The
game()function only tracks the score now. When the user guesses right, we callgame()again with the updated score, and the next iteration handles generating new options. - Game-Over Handling: Your original code didn't account for incorrect guesses—now the game ends gracefully and shows the user's final score when they pick wrong.
- Cleaner Conditionals: Combined the correct guess checks into a single
is_correctvariable to make the code easier to read and maintain.
内容的提问来源于stack exchange,提问作者AlexLikesWater
相关产品推荐
相关产品推荐

