Hangman:用玩家输入猜测替换 *

Hangman: replacing an * with player input guess

我研究这段代码已经有一段时间了。我已经尝试了很多不同的方法来找到玩家在随机生成的单词中正确猜测的输入的索引——我认为我目前写的应该有效,但我担心我忽略了一个非常简单的错误。每当我 运行 时,玩家所做的每一次猜测都被认为是正确的,此外,当我尝试引用值 player_guess 时,它不会出现在我的打印语句 print(f"Correct! {player_guess} is in the word!") 中。

我只是 python 的初学者(事实上,完全是编码),我花了大约 8 个小时在 Whosebug 上以前类似问题的帮助下尝试自己解决这些问题,但最终我遇到了一堵墙,所以任何帮助将不胜感激。

#random module to choose random word from word_list.txt
import random

#port in word_list.txt and create list
word_list = ['rarely', 'universe', 'notice', 'sugar', 'interference', 'constitution', 'we', 'minus', 'breath', 'clarify', 'take', 'recording', 'amendment', 'hut', 'tip', 'logical', 'cast', 'title', 'brief', 'none', 'relative', 'recently', 'detail', 'port', 'such', 'complex', 'bath', 'soul', 'holder', 'pleasant', 'buy', 'federal', 'lay', 'currently', 'saint', 'for', 'simple', 'deliberately', 'means', 'peace', 'prove', 'sexual', 'chief', 'department', 'bear', 'injection', 'off', 'son', 'reflect', 'fast', 'ago', 'education', 'prison', 'birthday', 'variation', 'exactly', 'expect', 'engine', 'difficulty', 'apply', 'hero', 'contemporary', 'that', 'surprised', 'fear', 'convert', 'daily', 'yours', 'pace', 'shot', 'income', 'democracy', 'albeit', 'genuinely', 'commit', 'caution', 'try', 'membership', 'elderly', 'enjoy', 'pet', 'detective', 'powerful', 'argue', 'escape', 'timetable', 'proceeding', 'sector', 'cattle', 'dissolve', 'suddenly', 'teach', 'spring', 'negotiation', 'solid', 'seek', 'enough', 'surface', 'small', 'search']

#Global variables
guesses = []
playing = True
lives = 7
#word generation
word = random.choice(word_list)
#create a display version on the generated word comprised of *
display = '*'* len(word)
#tracker of most recent player_guess
player_guess = ''

#create hangman graphics
def hangman():
    if lives == 7:
        print('____________')
        print('|/          ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 6:
        print('____________')
        print('|/        | ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 5:
        print('____________')
        print('|/        | ')
        print('|         O ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 4:
        print('____________')
        print('|/        | ')
        print('|         O ')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')       
    if lives == 3:
        print('____________')
        print('|/        | ')
        print('|        _O ')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 2:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 1:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print('|        /  ')
        print('|           ')
        print('|___________')
    if lives == 0:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print("|        / \ ")
        print('|           ')
        print('|___________')
        print("You lose")

def guess_input():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    try:
        player_guess = str(input("\nSelect a letter between A-Z: ")).lower()
    except:
        print("\nThat was not a letter between A-Z, try again...")
    else:
        if len(player_guess) > 1:
            print("\nPlease only guess 1 letter - no cheating!")
        elif player_guess in guesses:
            print("\nYou have already guessed this letter, try again...")
        elif player_guess not in alphabet:
            print("\nThat was not a letter between A-Z, try again...")
        else:
            guesses.append(player_guess)
            return player_guess

def guess_checker():
    global lives, display, word, player_guess
    if player_guess in word:
        print(f"Correct! {player_guess} is in the word!")
        for i, letter in enumerate(word):
            if letter == player_guess:
                display[i] = player_guess
    else:
        lives -= 1

def win_check(word):
    if '*' not in display:
        print("Congratulations, you win!")
    else:
        False

############################# MAIN PROGRAM ####################################

#Introduction
print('Welcome to HANGMAN, I have randomly generated a word for your game. You have 7 lives - good luck!')

while playing == True:
    if lives > 0:
        #Guess input
        hangman()
        print('\n')
        print(display)
        guess_input()
        guess_checker()
        win_check(display)
        if win_check == True:
            playing = False
        if win_check == False:
            continue
    elif lives == 0:
        hangman()
        playing = False

函数guess_input中的变量player_guess不是同名的全局变量。如果你添加

会更好
global player_guess

...在该函数中。

但是,最好避免(或至少限制)使用 global。相反,在主程序中捕获 guess_input returns 的值,然后 作为参数传递给 guess_checker,例如:

guess_checker(guess_input())

您将不再需要该全局变量 -- 删除相应的 public 指令,并为 guess_checker:

定义参数
def guess_checker(player_guess):

备注

虽然不是您的问题,但您的代码中还有其他几个问题。一个主要问题是 display 是一个字符串,因此您不能执行 display[i] = player_guess - 它会给出一个例外。

请检查 this 我改进和更正了几处的地方。查看评论。