写一段植物大战僵尸的代码用Python
时间: 2024-02-12 19:05:27 浏览: 91
以下是一个简单的植物大战僵尸游戏代码,使用了Python的Pygame库:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 窗口大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("植物大战僵尸")
# 颜色
white = (255, 255, 255)
black = (0, 0, 0)
# 植物和僵尸的图片
plant_image = pygame.image.load("plant.png")
zombie_image = pygame.image.load("zombie.png")
# 植物和僵尸的类
class Plant:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = plant_image
def draw(self):
screen.blit(self.image, (self.x, self.y))
class Zombie:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = zombie_image
self.speed = 2
def move(self):
self.x -= self.speed
def draw(self):
screen.blit(self.image, (self.x, self.y))
# 存储植物和僵尸的列表
plants = []
zombies = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 在鼠标单击的位置添加植物
x, y = pygame.mouse.get_pos()
plant = Plant(x, y)
plants.append(plant)
# 添加僵尸
if random.randint(0, 100) < 2:
zombie = Zombie(screen_width, random.randint(0, screen_height - zombie_image.get_height()))
zombies.append(zombie)
# 移动僵尸
for zombie in zombies:
zombie.move()
# 绘制背景和植物
screen.fill(white)
for plant in plants:
plant.draw()
# 绘制僵尸
for zombie in zombies:
zombie.draw()
# 更新屏幕
pygame.display.update()
# 退出Pygame
pygame.quit()
```
这只是一个简单的例子,可以根据需要添加更多的功能和逻辑。
阅读全文