用python代码 写一个游戏
时间: 2024-03-20 16:18:35 浏览: 51
好的,我可以帮你写一个游戏。以下是一个简单的猜数字游戏的 Python 代码:
```
import random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("You have 10 attempts to guess the number.\n")
number = random.randint(1, 100)
attempts = 0
while attempts < 10:
guess = int(input("Guess the number: "))
attempts += 1
if guess < number:
print("Too low. Try again.")
elif guess > number:
print("Too high. Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts!")
break
if attempts == 10:
print(f"Sorry, you ran out of attempts. The number was {number}.")
```
这段代码实现了一个简单的猜数字游戏。游戏开始时,程序生成一个1到100之间的随机数,玩家需要在10次内猜出这个数字。每次猜测后,程序会给出提示,告诉玩家猜的数字是大了还是小了,直到玩家猜中或者用完了10次机会。如果成功猜中,程序会显示用了多少次机会猜中了;如果用完了10次机会还没有猜中,程序会显示正确的数字,并告诉玩家失败了。
希望这个代码能对你有所帮助!
阅读全文