Pygame 教程:制作简单生日蛋糕动画
代码解析
1. 初始化 Pygame 库
import pygame pygame.init()
2. 设置屏幕大小
size = (700, 500) screen = pygame.display.set_mode(size)
3. 加载蛋糕图片,获取蛋糕图片的矩形对象
cake_img = pygame.image.load('cake.png') cake_rect = cake_img.get_rect()
4. 设置蛋糕初始位置和速度
cake_x = 0 cake_y = 200 cake_speed = 5
5. 设置蜡烛初始位置和速度
candle_x = 50 candle_y = 150 candle_speed = 2
6. 设置字体
font = pygame.font.SysFont('comicsansms', 72)
7. 进入游戏循环
done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True
# 8. 移动蛋糕
cake_x += cake_speed
if cake_x > size[0]:
cake_x = -cake_rect.width
# 9. 移动蜡烛
candle_y += candle_speed
if candle_y < 150 or candle_y > 250:
candle_speed = -candle_speed
# 10. 绘制蛋糕和蜡烛
screen.blit(cake_img, (cake_x, cake_y))
pygame.draw.rect(screen, (255, 255, 0), (candle_x, candle_y, 20, 50))
pygame.draw.circle(screen, (255, 0, 0), (candle_x + 10, candle_y - 20), 10)
# 11. 绘制文字
text = font.render('Happy Birthday!', True, (0, 0, 255))
text_rect = text.get_rect(center=(size[0] // 2, 50))
screen.blit(text, text_rect)
# 12. 刷新屏幕
pygame.display.flip()
13. 退出 Pygame 库
pygame.quit()
原文地址: https://www.cveoy.top/t/topic/nJ1P 著作权归作者所有。请勿转载和采集!