You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python全局变量赋值求助:开发Mastermind游戏时函数返回值无法更新全局变量

Fixing Global Variable Issues in Your Mastermind Python Code

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?

  1. You declared global variables but didn't actually modify them: When you write global secret at 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 like hits and close as local variables inside both check_guess and start_game, which overrides the global ones entirely.
  2. You didn't capture the return values from check_guess: Your check_guess function correctly calculates hits and close and returns them, but in start_game you just call check_guess(guess,secret) without saving those values. That means your local hits and close in start_game never 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: In start_game, we assign hits, close = check_guess(guess, secret) so we actually get the calculated values instead of sticking with initial 0s.
  • Improved input validation: The get_guess function now checks that every character in the guess is in the allowed colors list, so users can't input invalid characters.
  • Added constants for magic numbers: CODE_LENGTH and MAX_ROUNDS make 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:59:07