用python写植物大战僵尸的代码
时间: 2023-12-17 18:26:04 浏览: 81
使用pygame库编写的植物大战僵尸游戏,全程使用python语言,运行简单,下载即可运行
5星 · 资源好评率100%
以下是一个简单的Python植物大战僵尸的代码示例,可以作为参考:
```python
import time
class Plant:
def __init__(self, name, cost, damage, hp):
self.name = name
self.cost = cost
self.damage = damage
self.hp = hp
class Zombie:
def __init__(self, name, speed, damage, hp):
self.name = name
self.speed = speed
self.damage = damage
self.hp = hp
class Game:
def __init__(self):
self.plants = []
self.zombies = []
self.sun = 50
self.score = 0
def add_plant(self, plant):
self.plants.append(plant)
def add_zombie(self, zombie):
self.zombies.append(zombie)
def get_plant_by_name(self, name):
for plant in self.plants:
if plant.name == name:
return plant
return None
def get_zombie_by_name(self, name):
for zombie in self.zombies:
if zombie.name == name:
return zombie
return None
def check_win(self):
if not self.zombies:
print("Congratulations! You win!")
return True
return False
def check_lose(self):
for zombie in self.zombies:
if zombie.position <= 0:
print("Game over! Zombies win!")
return True
return False
def start(self):
while True:
print("Sun: %d" % self.sun)
for plant in self.plants:
print("%s: cost %d, damage %d, hp %d" % (plant.name, plant.cost, plant.damage, plant.hp))
command = input("Please select a plant to add, or enter 'q' to exit: ")
if command == 'q':
break
plant = self.get_plant_by_name(command)
if not plant:
print("Invalid input!")
continue
if self.sun < plant.cost:
print("Not enough sun!")
continue
self.sun -= plant.cost
print("Planting %s..." % plant.name)
time.sleep(1)
print("Plant %s is ready!" % plant.name)
while True:
for zombie in self.zombies:
if zombie.position == 0:
print("Zombie %s has reached the house!" % zombie.name)
return
for zombie in self.zombies:
zombie.position -= zombie.speed
if zombie.position <= 0:
continue
print("Zombie %s is %d steps away from the house." % (zombie.name, zombie.position))
if self.check_win() or self.check_lose():
return
time.sleep(1)
```
这个示例代码实现了一个简单的游戏逻辑,玩家可以在游戏中选择并种植不同的植物,防御不断前进的僵尸。需要注意的是,这只是一个简单的示例,游戏中还有许多细节需要完善。
阅读全文