改编自hangman游戏:后台生成随机单词,用户输入字母,每猜中一个字母,就把相应的下划线替换为字母,若猜错5次则游戏结束
import random
listFruit = ['apple', 'banana', 'pear', 'peach', 'orange', 'grape'] #水果类别
listColor = ['red', 'blue', 'green', 'yellow', 'white', 'black', 'pink'] #颜色类别
listCountry = ['Australia', 'Brazil', 'China', 'Denmark', 'England', 'France'] #国家类别
listTotal = [listFruit, listColor, listCountry] #创建谜题字典
listBlank = [] #创建空白字典,用于显示下划线组成的字符串
strBlank = '' #初始显示为_ _ _ _下划线字符串,长度为单词的长度,猜谜过程显示为_ e _(以猜中red的e为例)
isOver = False #游戏结束标记
timeWrong = 0 #猜错的次数,达到5次时游戏结束
hintName = '' #用于提示单词类别
randomGroupIndex = random.randint(0, 2) #随机选择字典中的一个序号
match randomGroupIndex: #根据字典序号决定提示词
case 0:
hintName = 'fruit'
case 1:
hintName = 'color'
case 2:
hintName = 'country'
groupGenerated = listTotal[randomGroupIndex] #根据字典序号决定类别
randomStr = random.choice(groupGenerated) #根据序号生成谜题字符串
for i in range(len(randomStr)): #生成长度与谜题字符串相等的下划线字符串
listBlank.append('_')
#strBlank += listBlank[i] + ' ' 生成默认的下划线字符串,此句可省略
print(f"the string is a {hintName}")
while not isOver:
userInput = input(f"input a character, or press 'quit' to end\n") #提示用户猜测谜题字符串中的一个字母
if userInput == 'quit': #输入quit可退出程序
print('bye')
isOver = True
break
if userInput not in randomStr: #用户猜的字母不在谜题字符串中时,猜错次数+1,提示可猜的剩余次数
timeWrong += 1
print(f"u are wrong, left chance is {5 - timeWrong}")
else: #用户猜的字母在谜题字符串中时
strBlank = '' #再次输入字母之前初始化下划线字符串
for i in range(len(randomStr)): #用猜正确的字母替换下划线字符串中对应位置的下划线,举例:_ _ _变为_ e _
if randomStr[i] == userInput:
listBlank[i] = randomStr[i]
strBlank += listBlank[i]
print(f"good, the string is {strBlank}")
if '_' not in listBlank: #下划线字符串中的所有下划线都被替换为字母时,表示猜对了所有的字母,游戏结束
isOver = True
print('u win!!!')
if timeWrong == len(randomStr): #猜错次数达到谜题字符串长度时,游戏结束
isOver = True
print('time is up, game over')