gpt4 book ai didi

python - 保存游戏中循环迭代的结果

转载 作者:行者123 更新时间:2023-11-28 19:02:32 26 4
gpt4 key购买 nike

我正在尝试制作刽子手游戏,但在显示方面遇到了问题。我有一个循环,应该将正确猜测的字母放在正确的位置,但它一次只显示一个字母的正确位置。我认为保存上一次迭代的结果然后显示它会很有帮助,但我不确定该怎么做。

import random,time
hanglist = []
answerlist = []
file_var = open("wordlist.100000")
for n in file_var:
hanglist.append(file_var.readline())
word = random.choice(hanglist)
print("word is",word)
guesses = 10
while guesses != 0:
print("guess a letter")
answer = input()
answerlist.append(answer)
if answer in word:
m = list(word)
for n in m:
if n == answer:
print(answer, end = '')
else:
print('_', end = '')
else:
print("close, but not exactly")
guesses -= 1

这里是输出

word is fabric

guess a letter
f
f______guess a letter
a
_a_____guess a letter

最佳答案

要解决您的问题,只需将 if n==answer 替换为 if n in answer。但是,从上面的代码中,我可以看到代码无法处理这些问题:

  1. 如果用户一次又一次地猜同一个词
  2. 在完成 4 次猜测并猜出总字数后,代码应该跳出循环,但它并没有发生。
  3. 读行的时候,需要去掉'\n'否则真的很难

我的代码解决了这些问题:

import random,time
hanglist = []
answerlist = []
file_var = open("wordlist.100000")
for n in file_var:
# strips the '/n' at the end
hanglist.append(file_var.readline().rstrip())
word = random.choice(hanglist)
print("word is",word)
guesses = 10
while guesses!=0:
print("guess a letter")
answer = input()
if answer in answerlist:
continue
answerlist.append(answer)
if answer in word:
# to print entire word guessed till now- with current and previous iterations
word_print = ''
for n in word:
# to print all the last state occurences
if n in answerlist:
word_print += n
else:
word_print += '_'
print(word_print,end='')
# word is correctly guessed
if '_' not in word_print:
break
else:
print("close, but not exactly")
guesses = guesses-1

关于python - 保存游戏中循环迭代的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com