下面是我的功能中有问题的部分:
def hangman1(word):
global guessesMade
global guessesLeft
currentGuess = '_ ' * len(word)
let = print(input('Please guess a letter: '))
for i in range(len(word)):
if word[i] == let:
print('{} is contained in the word.'.format(let))
if i == 0:
currentGuess = word[0] + currentGuess[1:]
else:
currentGuess = currentGuess[:i] + word[i] + currentGuess[i + 1:]
print(currentGuess)用户在提示符下输入一个字母,并检查该字母是否在函数外部从单词列表生成的randomWord中。我可以让它正确地打印空格,但是如果用户输入单词中的一个字母,它就打印出一行正确的字母,而不是中间混合正确字母的空格。
任何帮助都是非常感谢的。
发布于 2014-10-29 02:54:19
您现在遇到的主要问题是两重一,即replace()方法替换字符串中任何给定输入的所有实例,而不是第一个,第二个,您目前无法判断您已经发现了哪些字母。调用replace("_",let)将总是替换“_”的每个实例,并且考虑到将其应用于仅由下划线组成的字符串,它将始终覆盖整个字符串。在每次使用猜测字母调用hangman()时,您似乎也在重新生成hidden_let,这意味着现在您的设计中最好的情况只是显示用户刚刚猜到的每一个字母,而另一些字母则是下划线。
您想要做的是有两个值,correct_word和current_guess。correct_word将是玩家必须猜测的单词,而current_guess将是他们猜单词的进展,开始时只有与correct_word一样长的下划线。
下面是一个简短的例子。我冒昧地删除了您的全局引用--全局引用通常是不允许的--并将行为封装在一个小类中。您可能希望用任意单词替换hangmanner.play_hangman()中的值。
class Hangmanner:
correct_word = ''
current_guess = ''
def play_hangman(self, word):
self.correct_word = word
self.current_guess = '_' * len(self.correct_word)
while self.current_guess != self.correct_word:
self.guess_letter(input("Please guess a letter: "))
def guess_letter(self, guessed_letter):
for i in range(len(self.correct_word)):
if self.correct_word[i] == guessed_letter:
if i == 0:
self.current_guess = self.correct_word[i] + self.current_guess[1:]
else:
self.current_guess = self.current_guess[:i] + self.correct_word[i] + self.current_guess[i + 1:]
print(self.current_guess)
if __name__ == "__main__":
hangmanner = Hangmanner()
hangmanner.play_hangman("test")这使用python中的切片函数,可以使用括号和第一个语法来访问任意给定集合的任意范围。如果第一次或最后一次丢失,则切片将分别继续到集合的开始或结束。上面,current_guess1:从第二个索引返回current_guess到最后一个索引。current_guess:i从第一个索引到i之前的索引返回current_guess,因为最后是排它的结束界。
发布于 2014-10-29 03:08:52
hiddenLet.replace('_',let)用_所代表的任何内容替换_的所有出现。
newWordList = [x if x==let else '_' for x in randWord]
newWord = ''.join(newWordList)https://stackoverflow.com/questions/26621971
复制相似问题