用python写一个小游戏
时间: 2023-03-19 07:22:46 浏览: 71
好的,我可以为您提供一个简单的 Python 小游戏的示例代码,这个游戏叫做“猜数字游戏”(Guess the Number Game)。请参考下面的代码:
```python
import random
def guess_number_game():
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 10
print("I'm thinking of a number between 1 and 100. You have 10 attempts to guess the number.")
while attempts < max_attempts:
guess = int(input("Guess the number: "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
return
print(f"Game over. The secret number was {secret_number}.")
guess_number_game()
```
这个游戏会随机生成一个 1 到 100 之间的整数作为秘密数字,玩家需要在最多 10 次尝试内猜出这个数字。玩家每猜一次,程序会告诉玩家猜的数字是太低了还是太高了,直到玩家猜对为止。如果玩家猜错了 10 次,游戏结束并告诉玩家正确答案。
您可以将代码复制到 Python 编辑器中,保存为 `.py` 文件,然后在命令行中运行该文件来启动游戏。