这是一个简单的猜数字小游戏,玩家需要在有限的次数内猜出一个随机生成的数字。

import random

def guess_number():
    answer = random.randint(1, 100)
    tries = 0
    while tries < 5:
        guess = int(input("Guess a number between 1 and 100: "))
        tries += 1
        if guess == answer:
            print("Congratulations, you guessed the number in", tries, "tries!")
            return
        elif guess < answer:
            print("The number is higher than your guess.")
        else:
            print("The number is lower than your guess.")
    print("Sorry, you ran out of tries. The number was", answer)

guess_number()

在这个游戏中,我们使用了Python内置的random模块生成随机数。通过input函数获取玩家的猜测,然后比较猜测和答案的大小关系,给出提示。如果玩家猜对了,游戏结束,否则玩家有5次机会猜测。如果5次机会用完了,游戏结束并显示答案。

写一串关于小游戏的代码

原文地址: https://www.cveoy.top/t/topic/bwsP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录