Python全局变量赋值求助:开发Mastermind游戏时函数返回值无法更新全局变量
Hey there! Great job diving into Python and building Mastermind—super fun project! Let's tackle that variable problem you're having. The issue isn't actually with global variables not updating, but rather that you're not using them correctly (and honestly, you don't even need global variables here—they're making things more complicated than they need to be).
What's Going Wrong?
- You declared global variables but didn't actually modify them: When you write
global secretat the top, that tells Python you want to use the global version if you modify it inside a function—but in your code, you're redefining variables likehitsandcloseas local variables inside bothcheck_guessandstart_game, which overrides the global ones entirely. - You didn't capture the return values from
check_guess: Yourcheck_guessfunction correctly calculateshitsandcloseand returns them, but instart_gameyou just callcheck_guess(guess,secret)without saving those values. That means your localhitsandcloseinstart_gamenever get updated from their initial 0 values.
The Fix: Ditch Global Variables & Use Return Values
Global variables are rarely the best approach for small projects like this. Instead, let's use local variables and pass data between functions using return values. Here's your revised code with key improvements:
import random colors = "YORPGB" CODE_LENGTH = 4 MAX_ROUNDS = 12 def gen_random_secret(): secret = "" for _ in range(CODE_LENGTH): n = random.randrange(len(colors)) secret += colors[n] return secret def get_guess(force_valid_input): while True: guess = input(f"Available letters: {colors}\nEnter a {CODE_LENGTH}-letter code using the available letters (duplicates allowed!): ").upper() # Add validation for allowed characters and length if len(guess) == CODE_LENGTH and all(char in colors for char in guess): return guess else: if not force_valid_input: return None print(f"Wrong input! Try again—needs to be {CODE_LENGTH} letters using only the allowed colors.") def check_guess(guess, secret): hits = 0 close = 0 # Calculate exact position matches first for i in range(CODE_LENGTH): if guess[i] == secret[i]: hits += 1 # Calculate total color matches, subtract hits to get close matches for color in colors: close += min(secret.count(color), guess.count(color)) close -= hits return hits, close def start_game(): print("Welcome to Mastermind!\nGenerating secret code...") current_round = 1 history = [] secret = gen_random_secret() while current_round <= MAX_ROUNDS: guess = get_guess(True) # Capture the calculated hits and close values hits, close = check_guess(guess, secret) print(f"Hits: {hits} | Close matches: {close}\n") if hits == CODE_LENGTH: history.append((guess, hits, close)) break history.append((guess, hits, close)) current_round += 1 print("\nGame History:") for row in history: for color in row[0]: print(f" {color}", end="") print(f" | Hits: {row[1]} | Close: {row[2]}") print() if hits == CODE_LENGTH: print(f"Congrats! You cracked the code: {secret}") else: print(f"Out of attempts—better luck next time!\nThe secret code was: {secret}") start_game()
Key Changes Made:
- Removed all global variable declarations: We're using local variables exclusively now, which keeps your code cleaner and avoids unexpected variable overrides.
- Captured return values from
check_guess: Instart_game, we assignhits, close = check_guess(guess, secret)so we actually get the calculated values instead of sticking with initial 0s. - Improved input validation: The
get_guessfunction now checks that every character in the guess is in the allowedcolorslist, so users can't input invalid characters. - Added constants for magic numbers:
CODE_LENGTHandMAX_ROUNDSmake it easy to adjust the game rules later without hunting for hardcoded numbers. - Fixed history tracking: The winning guess is now added to the history before breaking the loop, so your game log is complete.
Bonus Tip for Future Global Use:
If you ever do need to use global variables, remember to add the global keyword inside the function where you're modifying the variable (not just at the top of the file). For example:
hits = 0 def update_hits(): global hits # Tells Python to use the global hits variable hits += 1
Hope this fixes your issue and helps you keep building your Mastermind game—happy coding!
内容的提问来源于stack exchange,提问作者HiighQ

