游戏规则:电脑随机生成一个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()