鼠标点击爆炸特效演示
充分使用游戏素材,展示动画特效
主要思路比较直观:
- 加载一些列游戏素材图片
- 获取鼠标点击位置
- 顺序播放一系列图片帧,获得爆炸效果
效果如下:
加载素材
explosion_frames = []
for i in range(16): img = pygame.image.load(f"explosion/frame{i:04}.png") explosion_frames.append(img)
获取鼠标位置
# 处理鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = event.pos #if button_x <= mouse_x <= button_x + button_width and button_y <= mouse_y <= button_y + button_height: explosion_playing = True
绘制系列图片
if explosion_playing:
if frame_index < len(explosion_frames): frame = explosion_frames[frame_index] game_display.blit(frame, (mouse_x, mouse_y)) frame_index += 1 pygame.time.wait(100) else: explosion_playing = False frame_index = 0
完整代码如下:
import pygame
pygame.init()
# 窗口尺寸
width = 800
height = 600
game_display = pygame.display.set_mode((width, height))
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# 按钮尺寸和位置
button_width = 80
button_height = 40
button_x = width // 2 - button_width // 2
button_y = height // 2 - button_height // 2
# 加载爆炸动画帧
explosion_frames = []
for i in range(16):
img = pygame.image.load(f"explosion/frame{i:04}.png")
explosion_frames.append(img)
# 当前动画帧索引
frame_index = 0
# 爆炸动画是否正在播放
explosion_playing = False
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
#if button_x <= mouse_x <= button_x + button_width and button_y <= mouse_y <= button_y + button_height:
explosion_playing = True
# 绘制游戏内容
game_display.fill(BLACK) # 填充窗口为黑色
# 绘制按钮
if explosion_playing:
if frame_index < len(explosion_frames):
frame = explosion_frames[frame_index]
game_display.blit(frame, (mouse_x, mouse_y))
frame_index += 1
pygame.time.wait(100)
else:
explosion_playing = False
frame_index = 0
else:
pass
#pygame.draw.rect(game_display, BLUE, (button_x, button_y, button_width, button_height), 2)
# 更新显示
pygame.d
isplay.update()
pygame.quit()