python 小游戏案例
时间: 2024-12-05 15:07:07 浏览: 8
Python是一种非常适合初学者入门的游戏开发语言,因为它语法简洁、易于理解。下面举几个简单的Python小游戏案例:
1. **猜数字游戏**:程序随机生成一个数字让用户猜测,通过循环和条件判断用户输入的数字是否与目标数一致。
```python
import random
number = random.randint(1, 100)
guess = None
while guess != number:
guess = int(input("请输入你猜的数字(1-100):"))
if guess < number:
print("太小了!")
elif guess > number:
print("太大了!")
print("恭喜你,猜对了!")
```
2. **石头、剪刀、布游戏**:利用if-elif-else结构模拟玩家和电脑的选择并判断胜负。
```python
import random
choices = ["石头", "剪刀", "布"]
computer_choice = random.choice(choices)
player_choice = input("请选择(石头、剪刀、布):")
print(f"电脑选择了 {computer_choice}.")
if player_choice == computer_choice:
print("平局!")
elif (player_choice == "石头" and computer_choice == "剪刀") or \
(player_choice == "剪刀" and computer_choice == "布") or \
(player_choice == "布" and computer_choice == "石头"):
print("你赢了!")
else:
print("你输了!")
```
阅读全文