我如何做到每次在刽子手游戏中玩_again时都会生成一个新词



基本上就是标题。我希望我的刽子手游戏每次再次玩时都能从导入的文件列表中生成一个新的随机单词。然而,当我这样做的时候,它只是使用了和以前相同的单词。这是代码。

import random
with open("English_Words", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
word = random.choice(words)}
def play_again():
print("Do you want to play again (Yes or No)")
response = input(">").upper()
if response.startswith("Y"):
return True
else:
return False
def singleplayer():
guessed = False
word_completion = "_" * len(word)
tries = 6
guessed_letters = []
while not guessed and tries > 0:
print(word_completion)
print(hangman_error(tries))
print(guessed_letters)
guess = input("Guess a letter:").lower()
if guess in guessed_letters:
print("You have already guessed that letter.")
elif guess not in word:
print("[INCORRECT] That letter is not in the word!")
guessed_letters.append(guess)
tries -= 1
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
elif guess in word:
print("[CORRECT] That letter is in the word!")
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 tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
if "_" not in word_completion:
guessed = True
if guessed:
print("You win, the man was saved! The word was:" + str(word))
while True:
singleplayer()
if play_again():
continue
else:
break

您需要在singleplayer((函数内部调用word = random.choice(words)。优选地在顶部,在guess = False线的正上方或正下方。

这样,每当调用单人游戏函数时,程序就会调用随机选择行。

def singleplayer():
word = random.choice(words)
guessed = False

最新更新