飞翔的小鸟精灵组

飞翔的小鸟精灵组 # # Pygame模板 -上 绘制背景精灵的使用静止的小鸟小鸟下落小鸟响应空格键上升小鸟的动画效果 # -中定义管道精灵类 并使用精灵组管道从右往左移动一次 # - (中) 管道移到左边后会重新出现在右侧随机位置 import pygame import random # 定义一个派生精灵子类-小鸟精灵类 class Bird(pygame.sprite.Sprite): # 构造函数对象初始化方法 def __init__(self): pygame.sprite.Sprite.__init__(self) # 先调用父类的初始化方法 self.images [] # 导入所有的小鸟图像用于动画效果 for i in range(8): img pygame.image.load(d:/test/bird%d.png%i) self.images.append(img) self.frame 0 # 当前显示的图像的编号 #self.image pygame.image.load(d:/test/bird0.png) # 导入小鸟图像 self.image self.images[self.frame] # 设置小鸟的图像属性值当前图像 self.rect self.image.get_rect() # 设置矩形属性当前位置 self.rect.x 50 self.rect.y 260 self.speed 2 # 初始化每次下落的距离速度 # 重写update方法控制精灵行为 def update(self): self.rect.y self.speed # 将增加的距离累加至小鸟的y坐标中 self.speed 2 # 重置每次下落的距离 # 实现飞翔动画效果 self.frame 1 # 当前图像编号加1即换成下一张 if self.frame 7: self.frame 0 self.image self.images[self.frame] # 根据编号更新当前图像 # 定义一个派生精灵子类-管道精灵类 class Pipe(pygame.sprite.Sprite): # 构造函数对象初始化方法 def __init__(self, image, x, y): # image-管道图像Surface对象x, y-左上角坐标 pygame.sprite.Sprite.__init__(self) self.image image self.rect self.image.get_rect() self.rect.x x self.rect.y y # 重写update方法控制精灵行为 def update(self): self.rect.x - 2 # 向左水平移动 # 窗口宽度和高度 WIDTH 350 HEIGHT 600 HALF_GATE_HEIGHT 120 # 管道开口高度的一半 TUNNEL_HEIGHT370 # 管道图片高度 # 初始化和窗口设置 pygame.init() #启动pygame并初始化 screen pygame.display.set_mode((WIDTH, HEIGHT)) # 创建一个游戏窗口 pygame.display.set_caption(飞翔的小鸟) # 设置标题 #创建一个时钟Clock对象以便我们能够确保我们的游戏以我们想要的 FPS 运行 clock pygame.time.Clock() bg pygame.image.load(d:/test/background.jpg) # 背景图片导入并缩放为窗口大小 bg pygame.transform.smoothscale(bg, (WIDTH, HEIGHT)) bird Bird() # 创建一个小鸟对象 #创建精灵组对象 pipes pygame.sprite.Group() #导入图像 pipe_down_image pygame.image.load(d:/test/bar_down.png) # 导入口冲下的管道 pipe_up_image pygame.image.load(d:/test/bar_up.png) # 导入口冲上的管道 #创建上下管道精灵并把他们加入精灵组 y random.randint(180, 420) pipe_down Pipe(pipe_down_image, WIDTH, yHALF_GATE_HEIGHT) pipe_up Pipe(pipe_up_image, WIDTH, y-TUNNEL_HEIGHT-HALF_GATE_HEIGHT) pipes.add(pipe_up, pipe_down) # 游戏主循环 running True while running: # 无限循环直到python退出时结束 # 设置每秒循环被执行的次数 clock.tick(50) # 处理输入(键盘、鼠标事件...) for event in pygame.event.get(): if event.type pygame.QUIT: # 处理关闭窗口事件 running False # 将 running 设置为 False游戏主循环结束 if event.type pygame.KEYDOWN and event.key pygame.K_SPACE: bird.speed -30 # 小鸟需要向上移动将下落距离设为负值 # 渲染到屏幕绘制 # 绘制背景 screen.blit(bg, (0, 0)) # 绘制小鸟 bird.update() screen.blit(bird.image, bird.rect) # 创建上下管道精灵并把他们加入精灵组 if len(pipes) 0: y random.randint(180, 420) pipe_down Pipe(pipe_down_image, WIDTH, yHALF_GATE_HEIGHT) pipe_up Pipe(pipe_up_image, WIDTH, y-TUNNEL_HEIGHT-HALF_GATE_HEIGHT) pipes.add(pipe_up, pipe_down) # 绘制管道 pipes.update() pipes.draw(screen) # 将精灵组显示在画布中 # 管道移出窗口范围时清空精灵组 if pipe_up.rect.right 0: pipes.empty() # 更新显示状态 pygame.display.update() #销毁窗口 pygame.quit()