我正在使用python中基于文本的简单刽子手游戏。我有一个粗略的程序运行,但我遇到了两个小问题:
为什么欢迎信息会打印两次?
当用户连续两次输入不在单词中的字母时,第二次,"nope, try again"
- 消息不显示,并且不显示当前单词。第一次输入错误的字母时,它可以正常工作。为什么不能第二次运作?
from random import randrange
class HangmanApp:
def __init__(self, interface):
self.infile = open("hangman.txt", "r")
self.interface = textInterface()
for line in self.infile:
self.wordlist = line.split()
self.secretword = self.wordlist[randrange(len(self.wordlist))]
self.letter_list = list(self.secretword)
#tests the user's guess
def guess(self):
self.new_list = ["_"]*len(self.secretword)
#keep loop going as long as there are letters in the list
while self.letter_list != ["_"]*len(self.letter_list):
self.guess = self.interface.guess()
if self.guess in self.letter_list:
while self.guess in self.letter_list:
i = self.letter_list.index(self.guess)
#replace that letter from the list with "_"
self.letter_list[self.letter_list.index(self.guess)] = "_"
#add the chosen letter to a new list for display
self.new_list[i] = self.guess
#print list with letter added
self.interface.correct(self.new_list)
else:
self.interface.incorrect(self.new_list)
self.guess = self.interface.guess()
class textInterface:
def __init__(self):
print("Welcome to Hangman!")
def guess(self):
guess = input("Guess a letter! ")
return guess
def display (self, word):
string = ' '.join(word)
print(string)
def incorrect(self, word):
print("Nope, try again")
self.display(word)
def correct(self, word):
print("Correct")
self.display(word)
def main():
inter = textInterface()
app = HangmanApp(inter)
app.guess()
答案 0 :(得分:0)
欢迎讯息会打印两次,因为您要创建两个textInterface
个实例:一个在main()
中,另一个在HangmanApp.__init__()
内。我想你的意思是:
self.interface = interface
而不是
self.interface = textInterface()
在HangmanApp.guess()
内,收到错误的猜测(到达else:
子句)后,您还有一个额外的guess
提示,不需要提示 - 一个不通过您的提示检查代码。我认为这可能导致问题,第二次没有工作。