用python帮我写一个植物大战僵尸代码
时间: 2023-08-28 10:54:12 浏览: 214
当然可以帮您写一个简单版本的植物大战僵尸游戏。以下是一个基本的示例代码:
```python
import random
import time
# 游戏角色类
class Plant:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
def attack(self, zombie):
zombie.hp -= self.damage
# 植物类
class Sunflower(Plant):
def __init__(self):
super().__init__('Sunflower', 50, 0)
def generate_sun(self):
return Sun()
# 僵尸类
class Zombie:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
def attack(self, plant):
plant.hp -= self.damage
# 太阳类
class Sun:
def __init__(self):
self.value = 25
# 游戏类
class Game:
def __init__(self):
self.plants = [Sunflower()]
self.zombies = [Zombie('Regular Zombie', 100, 10)]
self.sun = 50
def generate_sun(self):
self.sun += random.randint(10, 25)
def buy_plant(self, plant_index):
if self.sun >= 50:
self.sun -= 50
self.plants.append(self.plants[plant_index])
else:
print("Insufficient sun!")
def spawn_zombie(self):
zombie = random.choice(self.zombies)
print(f"A {zombie.name} has appeared!")
return zombie
def start(self):
print("Welcome to Plants vs. Zombies!")
time.sleep(1)
while True:
self.generate_sun()
print(f"Sun: {self.sun}")
time.sleep(1)
action = input("What would you like to do? (1: Buy plant, 2: Spawn zombie, q: Quit)")
if action == '1':
plant_index = int(input("Enter the index of the plant you want to buy: "))
self.buy_plant(plant_index)
elif action == '2':
zombie = self.spawn_zombie()
plant = random.choice(self.plants)
plant.attack(zombie)
print(f"The {plant.name} attacked the {zombie.name}! Zombie HP: {zombie.hp}")
if zombie.hp <= 0:
print(f"The {zombie.name} has been defeated!")
break
elif action == 'q':
print("Game over!")
break
else:
print("Invalid input. Try again.")
# 游戏实例化并开始
game = Game()
game.start()
```
这只是一个简单的示例,您可以根据需要进行扩展和改进。希望能帮到您!