Python编写hangman猜词游戏时猜对历史字母消失问题如何解决?
根因分析
- Python字符串为不可变类型,
validate_word函数内部对隐藏字符串的修改仅作用于传入参数的副本,没有将修改后的结果返回给外层主函数。 - 主函数中的
hidden_word变量从未被更新,每次调用validate_word时传入的都是初始状态的全下划线字符串,因此之前猜对的字母不会被保留。
修复方案
- 调整
validate_word函数逻辑,新增返回值,将修改后的隐藏字符串、本次猜测是否正确、是否已完成全部字母猜测三个状态返回给外层 - 主函数接收
validate_word的返回结果,更新全局hidden_word变量,同时补充猜错扣血、游戏胜利/失败的终止判断逻辑
修复后代码
调整后的validate_word函数
def validate_word(original,guess,hidden_word): listify_original = list(original) listify_hidden = list(hidden_word) guess_correct = False for char_place,char in enumerate(listify_original): if char == guess: listify_hidden[char_place] = char guess_correct = True if guess_correct: print('found it',"".join(listify_hidden)) new_hidden = "".join(listify_hidden) return new_hidden, guess_correct, new_hidden == original
调整后的主函数
def hang_man_guess_game(): generate_word = get_random_word_definition() definition = generate_word[0] word = generate_word[1] amount_of_tries = 6 print('Welcome to the hang man game!') print('The length of the word is: ',len(word)) print('The definition of word is: ',definition) print('Amount of health: ',amount_of_tries) print('Health gets lesser on each wrong guess!') print('You can write as many letters as you want!') print('Good luck player!') hidden_word = modify_word(word) while amount_of_tries != 0: print('Word: ', hidden_word) user_guess = input('Enter your guess: ').strip() # 可选:增加输入合法性校验 if len(user_guess) != 1 or not user_guess.isalpha(): print("请输入单个英文字母") continue hidden_word, guess_correct, is_win = validate_word(word,user_guess,hidden_word) if is_win: print(f"恭喜获胜!正确单词为:{word}") return if not guess_correct: amount_of_tries -= 1 print(f"猜错了,剩余生命值:{amount_of_tries}") print(f"游戏失败,正确单词为:{word}") hang_man_guess_game()
内容的提问来源于stack exchange,提问作者user14587589
相关产品推荐
相关产品推荐

