Python学习之hangman小游戏

warning: 这篇文章距离上次修改已过1407天,其中的内容可能已经有所变动。

要求



代码示例

import random
# 词库
words = ['program', 'process', 'pandemic', 'impairment', 'interface']
# 产生与词库数量对应的随机整数
index = random.randint(0, len(words) - 1)
# 从词库中随机挑取单词
word = words[index]
# 取消下面注释以获得作弊效果
# print(word)
# 将字母转化为星号并输出
wordblank = '*' * len(word)
print(wordblank)
# 定义尝试机会
guessTimes = 10
print('You have {} chances'.format(guessTimes))
# 令wordbak可修改
wordlst = list(wordblank)

while True:
    if guessTimes <= 0:
        break
    if '*' not in wordlst:
        break
    char = input('Please input a char:')
    if char in word:
        for i, c in enumerate(word):
            if c == char:
                wordlst[i] = char
    else:
        guessTimes -= 1
        if guessTimes == 1:
            print('You have only one chance left')
        else:
            print('You have {} chances left'.format(guessTimes))

    print(''.join(wordlst))

if guessTimes > 0:
    print('You win')
else:
    print('Sorry,the answer is {} '.format(word))
    print('You lose')

 


版权属于:NoColor

转载时须注明出处及本声明

none
最后修改于:2021年02月05日 02:34

添加新评论