UID1481106性别保密经验 EP铁粒 粒回帖0主题精华在线时间 小时注册时间2023-11-18最后登录1970-1-1
|
发表于 2023-11-24 19:01:06 来自手机|显示全部楼层 IP:浙江省
植物大战僵尸是一款非常受欢迎的游戏,下面是一个简单的植物大战僵尸游戏的代码示例:
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("植物大战僵尸")
# 定义颜色
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义游戏结束标志
game_over = False
# 定义僵尸和植物的类
class Zombie:
def __init__(self, x, y, speed):
self.x = x
self.y = y
self.speed = speed
self.health = 10
class Plant:
def __init__(self, x, y):
self.x = x
self.y = y
# 定义僵尸列表和植物列表
zombies = []
plants = []
# 定义僵尸移动速度
zombie_speed = 2
# 定义植物的攻击力
plant_damage = 10
# 定义游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 绘制背景
screen.fill(BLACK)
# 绘制植物
for plant in plants:
pygame.draw.rect(screen, GREEN, [plant.x, plant.y, 50, 50])
# 绘制僵尸
for zombie in zombies:
pygame.draw.rect(screen, RED, [zombie.x, zombie.y, 50, 50])
# 更新僵尸位置
for zombie in zombies:
zombie.x -= zombie_speed
# 检测僵尸和植物的碰撞
for zombie in zombies:
for plant in plants:
if pygame.Rect.colliderect(zombie, plant):
zombie.health -= plant_damage
# 检测僵尸是否到达屏幕边缘
for zombie in zombies:
if zombie.x < 0 or zombie.x > screen_width:
zombies.remove(zombie)
# 检测僵尸是否死亡
for zombie in zombies:
if zombie.health <= 0:
zombies.remove(zombie)
# 添加新的僵尸
if len(zombies) < 10:
x = random.randint(0, screen_width)
y = random.randint(0, screen_height)
speed = random.randint(1, 3)
new_zombie = Zombie(x, y, speed)
zombies.append(new_zombie)
# 绘制得分
score_text = "得分: " + str(len(zombies))
font = pygame.font.SysFont("Arial", 32)
score_label = font.render(score_text, True, GREEN)
screen.blit(score_label, [0, 0])
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
这只是一个简单的植物大战僵尸游戏的代码示例,你可以根据自己的需求进行修改和扩展。希望这个示例能对你有所帮助!如果你有其他问题,请随时提问。 |
|