写一个不用第三方库的python游戏
时间: 2023-12-19 19:06:42 浏览: 121
使用Python第三方库pygame写个贪吃蛇小游戏
抛硬币游戏
游戏规则:
1. 玩家选择正面或反面;
2. 程序随机抛一次硬币;
3. 如果玩家猜对了,则获胜,否则失败。
代码实现:
```
import random
# 定义硬币类
class Coin:
def __init__(self):
self.side = None
# 抛硬币
def toss(self):
self.side = random.choice(['heads', 'tails'])
# 游戏开始
def play_game():
print('Welcome to the coin toss game!')
print('Please choose heads or tails.')
player_choice = input().lower()
while player_choice not in ['heads', 'tails']:
print('Please enter a valid choice.')
player_choice = input().lower()
coin = Coin()
coin.toss()
print(f'The coin landed on {coin.side}.')
if player_choice == coin.side:
print('Congratulations! You won!')
else:
print('Sorry, you lost.')
# 主程序
if __name__ == '__main__':
play_game()
```
运行结果:
```
Welcome to the coin toss game!
Please choose heads or tails.
heads
The coin landed on tails.
Sorry, you lost.
```
阅读全文