用py写一个简洁的植物大战僵尸小游戏
时间: 2023-12-07 07:06:08 浏览: 162
好的,下面是一个简单的植物大战僵尸小游戏的代码,仅供参考:
```python
import random
# 植物类
class Plant:
def __init__(self, name, attack):
self.name = name
self.attack = attack
def __str__(self):
return self.name
# 僵尸类
class Zombie:
def __init__(self, name, hp, attack):
self.name = name
self.hp = hp
self.attack = attack
def __str__(self):
return self.name
# 游戏类
class Game:
def __init__(self):
self.plants = [Plant("豌豆射手", 2), Plant("寒冰射手", 3), Plant("阳光菇", 1)]
self.zombies = [Zombie("普通僵尸", 5, 1), Zombie("路障僵尸", 10, 1), Zombie("铁桶僵尸", 15, 2)]
self.round = 1
self.score = 0
# 开始游戏
def start(self):
print("欢迎来到植物大战僵尸小游戏!")
while True:
print("第{}回合:".format(self.round))
for i in range(3):
print("选择第{}个植物:{}".format(i+1, self.plants[i]))
plant_choice = int(input()) - 1
zombie_choice = random.randint(0, 2)
self.fight(self.plants[plant_choice], self.zombies[zombie_choice])
self.round += 1
# 战斗
def fight(self, plant, zombie):
print("你选择了植物{},它的攻击力为{}。".format(plant, plant.attack))
print("僵尸{}的血量为{},攻击力为{}。".format(zombie, zombie.hp, zombie.attack))
while True:
zombie.hp -= plant.attack
if zombie.hp <= 0:
print("你赢了!得到了{}分。".format(zombie.attack))
self.score += zombie.attack
break
plant.hp -= zombie.attack
if plant.hp <= 0:
print("你输了!")
exit(0)
# 运行游戏
game = Game()
game.start()
```
这个代码实现了简单的植物大战僵尸小游戏,你可以根据自己的需求进行修改和扩展。
阅读全文