python代码实现植物大战僵尸游戏
import pygame
import random
import sys
# 初始化 pygame
pygame.init()
# 游戏设置
WIDTH, HEIGHT = 800, 600
FPS = 30
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("植物大战僵尸")
# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 加载图片
plant_img = pygame.image.load('plant.png')
zombie_img = pygame.image.load('zombie.png')
bullet_img = pygame.image.load('bullet.png')
# 游戏对象
class Plant:
def __init__(self, x, y):
self.image = pygame.transform.scale(plant_img, (60, 60))
self.rect = self.image.get_rect(topleft=(x, y))
def draw(self):
WINDOW.blit(self.image, self.rect)
class Zombie:
def __init__(self, x, y):
self.image = pygame.transform.scale(zombie_img, (60, 60))
self.rect = self.image.get_rect(topleft=(x, y))
self.speed = 2
def move(self):
self.rect.x -= self.speed
if self.rect.x < 0:
self.rect.x = WIDTH
self.rect.y = random.randint(0, HEIGHT – 60)
def draw(self):
WINDOW.blit(self.image, self.rect)
class Bullet:
def __init__(self, x, y):
self.image = pygame.transform.scale(bullet_img, (10, 20))
self.rect = self.image.get_rect(center=(x, y))
self.speed = 10
def move(self):
self.rect.x += self.speed
def draw(self):
WINDOW.blit(self.image, self.rect)
# 游戏主函数
def main():
clock = pygame.time.Clock()
plants = [Plant(100, 100), Plant(100, 200)]
zombies = [Zombie(WIDTH, random.randint(0, HEIGHT – 60)) for _ in range(5)]
bullets = []
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
for plant in plants:
bullets.append(Bullet(plant.rect.right, plant.rect.centery))
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
pygame.quit()
sys.exit()
# 更新僵尸
for zombie in zombies:
zombie.move()
# 更新子弹
for bullet in bullets:
bullet.move()
if bullet.rect.x > WIDTH:
bullets.remove(bullet)
# 碰撞检测
for zombie in zombies:
for bullet in bullets:
if zombie.rect.colliderect(bullet.rect):
zombies.remove(zombie)
bullets.remove(bullet)
break
# 绘制
WINDOW.fill(WHITE)
for plant in plants:
plant.draw()
for zombie in zombies:
zombie.draw()
for bullet in bullets:
bullet.draw()
pygame.display.update()
clock.tick(FPS)
if __name__ == "__main__":
main()
作者:是叶子耶