Python - hangman用count替换字母和更新

时间:2016-12-06 14:33:08

标签: python python-3.x

def update(dictionary,letter):

    if letter in dictionary["word"]:

我正在制作刽子手游戏而且我仍然坚持如何制作我的最后一个功能,以便在猜出一封信时

2 个答案:

答案 0 :(得分:2)

if letter in dictionary['word'] and letter not in dictionary['guessWord']:
    dictionary['guessWord'] = ''.join([i if i in dictionary['guessWord'] or i == letter 
                                         else '*' for i in dictionary['word']])
else:
    dictionary['lives'] -= 1

此技术每次都会从密码字重建guessWordjoin获取字符串列表并使用分隔符将它们连接在一起,在本例中为''。对于秘密词中的每个字符,我们检查该字符是否等于letter或已经在猜测字中。如果是这样,它就被放入猜词中。如果没有,则将其替换为*

答案 1 :(得分:0)

您可以使用zip来迭代元组(character in word, character in guess)。如果letter update与正确答案中的字符匹配,则选择它,否则选择当前猜测和join一起挑选的字符。最后检查新猜测是否与当前相同,如果匹配会减少生命:

def update(dictionary, letter):
    old = dictionary['guessWord']
    dictionary['guessWord'] = ''.join(x if x == letter else y
                                      for x, y in zip(dictionary['word'], old))
    if old == dictionary['guessWord']:
        dictionary['lives'] -= 1