python
import pygame
import sys
import math
import random
# --- 1. 游戏设置与常量 (Constants & Settings) ---
SCREEN_WIDTH = 640 # 游戏窗口宽度
SCREEN_HEIGHT = 480 # 游戏窗口高度
GAME_AREA_WIDTH = 384 # 弹幕主要活动区域
FPS = 60 # 帧率
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 资源路径 (如果找不到图片, 程序会自动创建色块代替)
try:
PLAYER_IMG = pygame.image.load('player.png')
BOSS_IMG = pygame.image.load('boss.png')
PLAYER_BULLET_IMG = pygame.image.load('bullet_player.png')
ENEMY_BULLET_IMG = pygame.image.load('bullet_enemy.png')
except pygame.error:
PLAYER_IMG = None
BOSS_IMG = None
PLAYER_BULLET_IMG = None
ENEMY_BULLET_IMG = None
FONT_NAME = 'font.ttf' # 需要一个 ttf 字体文件
# --- 2. 自机类 (Player Class) ---
class Player(pygame.sprite.Sprite):
def __init__(self, all_sprites, player_bullets):
super().__init__()
# 图像与位置
if PLAYER_IMG:
self.image = pygame.transform.scale(PLAYER_IMG, (32, 48))
else:
self.image = pygame.Surface((32, 48))
self.image.fill(BLUE)
self.rect = self.image.get_rect(center=(GAME_AREA_WIDTH // 2, SCREEN_HEIGHT - 50))
# 判定点 (一个更小的矩形, 用于碰撞检测)
self.hitbox = pygame.Rect(0, 0, 6, 6)
self.hitbox.center = self.rect.center
# 移动属性
self.speed = 5
self.low_speed_multiplier = 0.5
self.is_low_speed = False
# 射击属性
self.shoot_delay = 100 # 射击间隔 (毫秒)
self.last_shot = pygame.time.get_ticks()
self.all_sprites = all_sprites
self.player_bullets = player_bullets
# 游戏属性
self.lives = 3
self.bombs = 3
self.score = 0
self.invincible = False # 无敌状态
self.invincible_timer = 2000 # 无敌时间 (毫秒)
self.last_hit_time = 0
def update(self):
# 处理无敌状态
if self.invincible:
now = pygame.time.get_ticks()
if now - self.last_hit_time > self.invincible_timer:
self.invincible = False
# 闪烁效果
self.image.set_alpha(128 if (now // 100) % 2 == 0 else 255)
else:
self.image.set_alpha(255)
# 获取按键
keys = pygame.key.get_pressed()
self.is_low_speed = keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT]
current_speed = self.speed * self.low_speed_multiplier if self.is_low_speed else self.speed
if keys[pygame.K_LEFT]:
self.rect.x -= current_speed
if keys[pygame.K_RIGHT]:
self.rect.x += current_speed
if keys[pygame.K_UP]:
self.rect.y -= current_speed
if keys[pygame.K_DOWN]:
self.rect.y += current_speed
# 限制在游戏区域内
self.rect.left = max(0, self.rect.left)
self.rect.right = min(GAME_AREA_WIDTH, self.rect.right)
self.rect.top = max(0, self.rect.top)
self.rect.bottom = min(SCREEN_HEIGHT, self.rect.bottom)
# 更新判定点位置
self.hitbox.center = self.rect.center
# 射击 (按住 Z 键)
if keys[pygame.K_z]:
self.shoot()
def shoot(self):
now = pygame.time.get_ticks()
if now - self.last_shot > self.shoot_delay:
self.last_shot = now
# 创建两发子弹
b1 = PlayerBullet(self.rect.centerx - 8, self.rect.top)
b2 = PlayerBullet(self.rect.centerx + 8, self.rect.top)
self.all_sprites.add(b1, b2)
self.player_bullets.add(b1, b2)
def use_bomb(self):
if self.bombs > 0:
self.bombs -= 1
# 这里可以添加 Bomb 的效果, 比如清屏, 对 Boss 造成大量伤害等
return True
return False
def die(self):
if not self.invincible:
self.lives -= 1
if self.lives > 0:
self.bombs = 3 # 残机-1, bomb补满
self.invincible = True
self.last_hit_time = pygame.time.get_ticks()
self.rect.center = (GAME_AREA_WIDTH // 2, SCREEN_HEIGHT - 50) # 重置位置
else:
self.kill() # 游戏结束
# --- 3. 子弹类 (Bullet Classes) ---
class PlayerBullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
if PLAYER_BULLET_IMG:
self.image = pygame.transform.scale(PLAYER_BULLET_IMG, (10, 20))
else:
self.image = pygame.Surface((10, 20))
self.image.fill(GREEN)
self.rect = self.image.get_rect(center=(x, y))
self.speedy = -10
def update(self):
self.rect.y += self.speedy
if self.rect.bottom < 0:
self.kill()
class EnemyBullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle):
super().__init__()
if ENEMY_BULLET_IMG:
self.image_orig = pygame.transform.scale(ENEMY_BULLET_IMG, (16, 16))
else:
self.image_orig = pygame.Surface((12, 12))
pygame.draw.circle(self.image_orig, RED, (6, 6), 6)
self.image_orig.set_colorkey(BLACK)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect(center=(x, y))
self.speed = 3
# 将角度转换为弧度, 计算速度分量
rad = math.radians(angle)
self.vx = math.cos(rad) * self.speed
self.vy = math.sin(rad) * self.speed
# 用于旋转图像
self.angle = angle
self.rot_angle = -self.angle # Pygame的旋转方向与数学相反
self.image = pygame.transform.rotate(self.image_orig, self.rot_angle)
self.rect = self.image.get_rect(center=self.rect.center)
def update(self):
self.rect.x += self.vx
self.rect.y += self.vy
# 边界外销毁
if not pygame.Rect(0, 0, GAME_AREA_WIDTH, SCREEN_HEIGHT).colliderect(self.rect):
self.kill()
# --- 4. Boss 类 (Boss Class) ---
class Boss(pygame.sprite.Sprite):
def __init__(self, all_sprites, enemy_bullets, spell_cards):
super().__init__()
if BOSS_IMG:
self.image = pygame.transform.scale(BOSS_IMG, (128, 128))
else:
self.image = pygame.Surface((100, 100))
self.image.fill(YELLOW)
self.rect = self.image.get_rect(center=(GAME_AREA_WIDTH // 2, 100))
self.all_sprites = all_sprites
self.enemy_bullets = enemy_bullets
# 符卡管理
self.spell_cards = spell_cards
self.current_spell_index = -1 # -1 表示尚未开始
self.current_spell = None
self.max_hp = 0
self.hp = 0
self.is_defeated = False
self.next_spell() # 启动第一张符卡
def update(self):
if self.current_spell and not self.is_defeated:
self.current_spell.update(self)
def take_damage(self, amount):
if self.current_spell:
self.hp -= amount
if self.hp <= 0:
self.hp = 0
self.next_spell()
def next_spell(self):
# 清理场上所有敌机子弹
for bullet in self.enemy_bullets:
bullet.kill()
self.current_spell_index += 1
if self.current_spell_index < len(self.spell_cards):
self.current_spell = self.spell_cards[self.current_spell_index]
self.max_hp = self.current_spell.hp
self.hp = self.max_hp
self.current_spell.start()
else:
self.is_defeated = True
print("Boss Defeated!")
self.kill()
# --- 5. 符卡系统 (Spell Card System) ---
# 这是引擎的核心, 您将在这里定义Boss的弹幕行为
class SpellCard:
"""符卡基类, 所有符卡都应继承它"""
def __init__(self, name, hp, duration):
self.name = name # 符卡名
self.hp = hp # 这张卡的血量
self.duration = duration * FPS # 持续时间 (秒 * 帧率)
self.timer = 0 # 内部计时器, 用于控制弹幕发射时机
def start(self):
"""在符卡开始时调用"""
self.timer = 0
def update(self, boss):
"""每帧调用, 在这里编写弹幕逻辑"""
self.timer += 1
if self.timer >= self.duration:
# 时间到了, 自动进入下一张卡
boss.next_spell()
def create_bullet(self, boss, angle, speed_mult=1.0):
"""一个创建子弹的辅助函数"""
bullet = EnemyBullet(boss.rect.centerx, boss.rect.centery, angle)
bullet.speed *= speed_mult
# 重新计算速度分量
rad = math.radians(bullet.angle)
bullet.vx = math.cos(rad) * bullet.speed
bullet.vy = math.sin(rad) * bullet.speed
boss.all_sprites.add(bullet)
boss.enemy_bullets.add(bullet)
# --- 在这里定义您的符卡 ---
class SpellCard1(SpellCard):
"""符卡示例1: [星符「流星雨」]"""
def __init__(self):
super().__init__(name="星符「流星雨」", hp=1500, duration=30)
self.angle_offset = 0
def update(self, boss):
super().update(boss) # 调用父类的计时器
# 每 5 帧发射一波
if self.timer % 5 == 0:
num_bullets = 3
for i in range(num_bullets):
# 随机角度, 造成流星雨的感觉
angle = random.uniform(45, 135)
# 随机生成位置, 而非总在Boss中心
spawn_x = random.randint(0, GAME_AREA_WIDTH)
bullet = EnemyBullet(spawn_x, 0, angle)
boss.all_sprites.add(bullet)
boss.enemy_bullets.add(bullet)
class SpellCard2(SpellCard):
"""符卡示例2: [幻符「旋转的阴阳玉」]"""
def __init__(self):
super().__init__(name="幻符「旋转的阴阳玉」", hp=2000, duration=40)
self.base_angle = 0
def update(self, boss):
super().update(boss)
# 每 10 帧发射一波
if self.timer % 10 == 0:
num_bullets = 12
angle_step = 360 / num_bullets
for i in range(num_bullets):
angle = self.base_angle + i * angle_step
self.create_bullet(boss, angle, speed_mult=1.2)
# 让基础角度旋转, 产生螺旋效果
self.base_angle += 3.3
# --- 6. 游戏主循环 (Main Game Loop) ---
def draw_text(surface, text, size, x, y, color=WHITE):
"""绘制文字的辅助函数"""
try:
font = pygame.font.Font(FONT_NAME, size)
except FileNotFoundError:
font = pygame.font.SysFont('sans', size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.topleft = (x, y)
surface.blit(text_surface, text_rect)
def draw_hud(surface, player, boss):
"""绘制游戏界面 (HUD)"""
# 绘制游戏区和信息区的分割线
pygame.draw.line(surface, WHITE, (GAME_AREA_WIDTH, 0), (GAME_AREA_WIDTH, SCREEN_HEIGHT), 2)
# 信息区背景
surface.fill(BLACK, (GAME_AREA_WIDTH, 0, SCREEN_WIDTH - GAME_AREA_WIDTH, SCREEN_HEIGHT))
# 显示分数
draw_text(surface, 'Score', 22, GAME_AREA_WIDTH + 20, 20)
draw_text(surface, str(player.score), 20, GAME_AREA_WIDTH + 20, 50)
# 显示残机和Bomb
draw_text(surface, 'Player', 22, GAME_AREA_WIDTH + 20, 100)
draw_text(surface, f"Lives: {player.lives}", 20, GAME_AREA_WIDTH + 20, 130)
draw_text(surface, f"Bombs: {player.bombs}", 20, GAME_AREA_WIDTH + 20, 160)
# 显示Boss信息
if boss and boss.alive():
draw_text(surface, 'Boss', 22, GAME_AREA_WIDTH + 20, 220)
# 符卡名
if boss.current_spell:
draw_text(surface, boss.current_spell.name, 16, GAME_AREA_WIDTH + 20, 250, YELLOW)
# 血条
if boss.max_hp > 0:
hp_ratio = boss.hp / boss.max_hp
bar_width = SCREEN_WIDTH - GAME_AREA_WIDTH - 40
bar_height = 15
fill_width = bar_width * hp_ratio
border_rect = pygame.Rect(GAME_AREA_WIDTH + 20, 280, bar_width, bar_height)
fill_rect = pygame.Rect(GAME_AREA_WIDTH + 20, 280, fill_width, bar_height)
pygame.draw.rect(surface, WHITE, border_rect, 2)
pygame.draw.rect(surface, RED, fill_rect)
# 显示低速模式提示
if player.is_low_speed:
pygame.draw.circle(surface, WHITE, player.hitbox.center, player.hitbox.width, 1)
def main():
# 初始化
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("东方-Style 弹幕引擎")
clock = pygame.time.Clock()
# 创建精灵组
all_sprites = pygame.sprite.Group()
player_bullets = pygame.sprite.Group()
enemy_bullets = pygame.sprite.Group()
# 创建游戏对象
player = Player(all_sprites, player_bullets)
all_sprites.add(player)
# 定义Boss的符卡序列
boss_spell_cards = [
SpellCard1(),
SpellCard2()
]
boss = Boss(all_sprites, enemy_bullets, boss_spell_cards)
all_sprites.add(boss)
# 游戏主循环
running = True
while running:
# 控制帧率
clock.tick(FPS)
# --- 事件处理 ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_x: # 按 X 使用 Bomb
if player.use_bomb():
# Bomb 成功使用, 清屏并对Boss造成伤害
for bullet in enemy_bullets:
bullet.kill()
if boss.alive():
boss.take_damage(500) # Bomb 伤害
player.score += 10000
# --- 更新游戏状态 ---
all_sprites.update()
# --- 碰撞检测 ---
# 自机子弹 vs Boss
if boss.alive():
hits = pygame.sprite.spritecollide(boss, player_bullets, True)
for hit in hits:
boss.take_damage(10)
player.score += 100
# 敌人子弹 vs 自机
# 使用 player.hitbox 进行精确碰撞检测
hits = pygame.sprite.spritecollide(player, enemy_bullets, True, pygame.sprite.collide_rect_ratio(0.5))
if hits:
player.die()
# --- 绘制 ---
screen.fill(BLACK, (0, 0, GAME_AREA_WIDTH, SCREEN_HEIGHT)) # 游戏区背景
all_sprites.draw(screen)
draw_hud(screen, player, boss)
# 刷新屏幕
pygame.display.flip()
# 游戏结束判断
if not player.alive():
# 这里可以跳转到游戏结束画面
print("Game Over")
running = False
if boss.is_defeated:
# 这里可以跳转到胜利画面
print("You Win!")
running = False
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()