python猜数字小游戏

        游戏规则:电脑随机生成一个1-100之间的整数,用户通过输入数字来猜这个随机数,每次猜测都会提示猜测结果和剩余猜测次数

import random

isOver = False
def mainGame():     #定义游戏进程
    global isOver
    while not isOver:
        timeMax  = 0    #初始化最大猜测次数
        levelDifficulty = input("(e)asy or (h)ard\n")     #用户选择难度
        match levelDifficulty:      #hard模式可以猜5次,easy模式可以猜10次
            case "e":
                timeMax = 10
                print("u have 10 times\n")
            case "h":
                timeMax = 5
                print("u have 5 times\n")
        numberGenerated = random.randint(1, 100)    #随机生成1-100之间的数字让用户猜
        while timeMax != 0:     #到达猜测次数之前用户都可以猜
            numberInput = int(input("guess a number\n"))
            if numberInput == numberGenerated:      #若猜中则胜利
                print("u get it!!\n")
                break
            if numberInput > numberGenerated:       #若猜测数字大于生成的数字
                timeMax -= 1        #猜测次数-1
                if timeMax != 0:        #猜测数字等于0时游戏结束,否则输出本次猜测结果和剩余猜测次数
                    print(f"{numberInput} is too high, u have {timeMax} times left\n")
                    continue
                else:
                    print("time is up, u lose\n")
                    break
            if numberInput < numberGenerated:
                timeMax -= 1
                if timeMax != 0:
                    print(f"{numberInput} is too low, u have {timeMax} times left\n")
                    continue
                else:
                    print("time is up, u lose\n")
                    break
        inputAgain = input("press r to restart, or press e to end\n")
        match inputAgain:   #用户决定重开或者结束
            case "r":
                mainGame()
            case "e":
                isOver = True
mainGame()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值