python猜单词小游戏

        改编自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')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值