Python学习之hangman小游戏
要求

代码示例
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')
Python学习之hangman小游戏
https://nocolor.cc/archives/108/