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

Python开发的Hangman游戏每次触发play_again时如何生成新随机单词?

问题原因

你的代码仅在程序启动时执行了一次随机单词抽取逻辑,random.choice(words) 定义在全局作用域,后续重开游戏不会重新触发该逻辑,因此每次游玩都会沿用第一次生成的单词。

修改方案

你不需要重复读取单词文件,仅需把单词抽取逻辑挪到单局游戏的函数内部即可,同时修正原代码末尾多余的右大括号语法错误:

  • 保留全局的单词列表读取逻辑,避免重复IO操作
  • 在singleplayer()函数开头新增随机选单词的逻辑
  • 移除原全局定义的word变量,避免变量作用域冲突

修改后完整代码

import random

# 单词列表仅读取一次即可,内容固定不需要重复加载
with open("English_Words", "r") as file:
    allText = file.read()
words = list(map(str, allText.split()))

def play_again():
    print("你想要再玩一次吗(是/否)")
    response = input(">").upper()
    return response.startswith("Y") or response.startswith("是")

def singleplayer():
    # 每次启动单局游戏,重新随机抽取单词
    word = random.choice(words)
    guessed = False
    word_completion = "_" * len(word)
    tries = 6
    guessed_letters = []
    while not guessed and tries > 0:
        print(word_completion)
        # 注意:你原代码未定义hangman_error函数,运行前需要自行补充实现
        # print(hangman_error(tries))
        print("已经猜过的字母:", guessed_letters)
        guess = input("猜一个字母:").lower()
        if guess in guessed_letters:
            print("你已经猜过这个字母了。")
        elif guess not in word:
            print("[错误] 这个字母不在单词里!")
            guessed_letters.append(guess)
            tries -= 1
            if tries == 0:
                print("你的机会用完了,游戏失败!正确的单词是:" + str(word))
        elif guess in word:
            print("[正确] 这个字母在单词里!")
            guessed_letters.append(guess)
            word_as_list = list(word_completion)
            indices = [i for i, letter in enumerate(word) if letter == guess]
            for index in indices:
                word_as_list[index] = guess
            word_completion = "".join(word_as_list)
            if "_" not in word_completion:
                guessed = True
        if guessed:
            print("你赢了,猜对了单词:" + str(word))

while True:
    singleplayer()
    if play_again():
        continue
    else:
        break

内容的提问来源于stack exchange,提问作者Mopps

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:45:04