2014-10-29 102 views
1

这里是有问题的片我的功能的:Python实现吊颈功能

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从单词列表中选择。我可以正确地打印空白,但如果用户输入的是单词中的一个字母,它会打印出正确字母的一行而不是正确的字母混合在一起的空白。

任何帮助表示赞赏。

+0

您不能直接使用'replace'函数;你也需要切片。看到这里:http://stackoverflow.com/questions/12723751/replacing-letter-in-string-by-index – 101 2014-10-29 02:57:01

+0

不知道为什么这个问题downvoted。 OP试图解决他/她自己的问题,清楚地描述他被困在哪里以及他所尝试的是什么。作为第一篇文章,这非常好。我正在投票。 – 2014-10-29 20:21:30

回答

2

你现在遇到的主要问题是双重的 - 一个,那替换()方法替换字符串,而不是第一个中的任何给定输入的所有实例,和两个,你做不目前有任何方法可以告诉你已经发现了哪些字母。调用替换(“_”,让)永远取代“_”的每一个实例,因为你申请的是一个字符串,只有下划线组成,它会始终覆盖整个字符串。好像你还再生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") 

这使用切割功能的蟒蛇,在那里你可以使用括号和[第一:去年]语法访问任何收集的任意范围。如果缺少第一个或最后一个,则切片分别继续到集合的开始或结束。以上,current_guess [1:]将current_guess从第二个索引返回到最后一个索引。 current_guess [:i]返回current_guess从第一个索引到i之前的索引,因为last是唯一的结束边界。

+0

如果它有帮助,我可以添加其余的功能。 – Droxbot 2014-10-29 03:01:34

+0

哪里/什么?您的帖子看起来完全相同,您的评论中没有任何内容显示。 – furkle 2014-10-29 03:54:06

+0

我更新了原始问题中的功能。它有点工作,但仍不能以正确的格式打印出来。也许我在一路上的某个地方搞砸了。 – Droxbot 2014-10-29 03:54:31

2

hiddenLet.replace('_',let)替换任何let代表_所有出现。

newWordList = [x if x==let else '_' for x in randWord] 
newWord = ''.join(newWordList) 
+1

字符串是不可变的。 – 101 2014-10-29 03:11:07

+0

是的,忘了 – 2014-10-29 03:12:51