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

时间:2018-06-21 18:23:34

标签: python

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

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

2 个答案:

答案 0 :(得分:1)

要解决您的问题,只需将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

答案 1 :(得分:-1)

您的问题出在

if n == answer:
    print(answer,end = '')
else:
    print('_', end = '')  

仅将每个字母与当前猜测answer进行比较。相反,如果您使用

if n in answerlist:
    print(n, end = '')
else:
    print('_', end = '')  

如果该字母在其先前的猜测列表中,则会显示该字母。

此外:上一个m= list(word)无效,因为for n in word:有效。