当前位置: 代码迷 >> 综合 >> pygame 200行小游戏之 FlappyBird
  详细解决方案

pygame 200行小游戏之 FlappyBird

热度:90   发布时间:2023-09-22 20:04:23.0
  • 开发准备
    pip install pygame
    新建文件夹将代码和资源放在一起
  • 功能
  1. 鼠标移出窗口暂停游戏,移入恢复
  2. 播放我喜欢的背景音乐 Chain Hang Low
  3. 标题栏显示当前得分,撞柱子时游戏终止(画面静止,音乐暂停)
  4. 点击鼠标或者回车控制小鸟升起
  • 效果

pygame 200行小游戏之 FlappyBird的演示

  • 原理
  1. 地图的滚动:两张图首尾相连,变化绘图的位置即可
  2. 碰撞检查:简易做法就是保存小鸟图片的右上角的坐标,如果横坐标处有柱子,再判断是否碰到该柱子两端
  • 代码
# -*- coding: UTF-8 -*-#导入pygame库
import pygame
#向sys模块借一个exit函数用来退出程序
from sys import exit
# 导入 random(随机数) 模块
import randomFPS = 30 # 帧率
fpsClock = pygame.time.Clock()#鸟
class Bird(object):# 初始化鸟def __init__(self, scene):# 加载相同张图片资源,做交替实现地图滚动self.image = pygame.image.load("./bird.png")# 保存场景对象self.main_scene = scene# 尺寸self.size_x = 80self.size_y = 60# 辅助移动地图self.x = 40self.y = 120# 计算鸟绘制坐标def action(self, jump = 4):self.y = self.y + jumpif self.y > 520 :self.y = 520if self.y < 0 :self.y = 0# 绘制鸟的图片def draw(self):self.main_scene.scene.blit(self.image, (self.x, self.y))# 地图
class GameBackground(object):# 初始化地图def __init__(self, scene):# 加载相同张图片资源,做交替实现地图滚动self.image1 = pygame.image.load("./background.jpg")self.image2 = pygame.image.load("./background.jpg")# 保存场景对象self.main_scene = scene# 辅助移动地图self.x1 = 0self.x2 = self.main_scene.size[1]self.speed = 4# 柱子图self.pillar = pygame.image.load("./pillar.png")# 柱子 宽100 长1000 中间空隙200self.pillar_nums = 1self.pillar_positions_x = [800] self.pillar_positions_y = [-200] # 计算地图图片绘制坐标def action(self, addPillar = False):# 计算柱子新位置for i in range(0, self.pillar_nums):self.pillar_positions_x[i] -=  self.speedif self.pillar_nums > 0 and self.pillar_positions_x[0] + 100 < 0:del self.pillar_positions_x[0]del self.pillar_positions_y[0]self.pillar_nums -= 1if addPillar:self.pillar_nums += 1self.pillar_positions_x.append(800)self.pillar_positions_y.append(random.randint(-400, 0)) # 地图self.x1 = self.x1 - self.speedself.x2 = self.x2 - self.speedif self.x1 <= -self.main_scene.size[1]:self.x1 = 0if self.x2 <= 0:self.x2 = self.main_scene.size[1]# 绘制地图def draw(self):self.main_scene.scene.blit(self.image1, (self.x1, 0))self.main_scene.scene.blit(self.image2, (self.x2, 0))for i in range(0, self.pillar_nums):self.main_scene.scene.blit(self.pillar, (self.pillar_positions_x[i], self.pillar_positions_y[i]))# 主场景
class MainScene(object):# 初始化主场景def __init__(self):# 场景尺寸self.size = (800, 600)# 场景对象self.scene = pygame.display.set_mode([self.size[0], self.size[1]])# 得分self.point = 0# 设置标题及得分pygame.display.set_caption("Flappy Bird v1.0 得分:" + str(int(self.point)))# 暂停self.pause = False# 创建地图对象self.map = GameBackground(self)# 创建鸟对象self.bird = Bird(self)# 输了吗self.lose = False# 绘制def draw_elements(self):self.map.draw()self.bird.draw()pygame.display.set_caption("Flappy Bird v1.0 得分:" + str(float('%.2f' % self.point)))# 动作def action_elements(self, addPillar = False):self.map.action(addPillar)self.bird.action()# 处理事件def handle_event(self):for event in pygame.event.get():print(event)if event.type == pygame.QUIT:#接收到退出事件后退出程序exit()elif event.type == pygame.WINDOWLEAVE:#光标移出屏幕self.pause = Trueelif event.type == pygame.WINDOWENTER:#光标移入屏幕self.pause = Falseelif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN and event.dict["unicode"] == '\r':# 点击鼠标或者按回车键控制小鸟升起self.bird.action(-60)else:pass# 碰撞检测, 碰到返回-1, 过了返回1, 其他0def detect_conlision(self):# 只要检查第一个柱子if self.map.pillar_positions_x[0] <=  self.bird.size_x + self.bird.x and self.map.pillar_positions_x[0] >= -60:if self.map.pillar_positions_y[0] + 400 <  self.bird.y and self.bird.y < self.map.pillar_positions_y[0] + 600:if self.map.pillar_positions_x[0] == -60:return 1else:return -1return 0# 主循环,主要处理各种事件def run_scene(self):#放段音乐听pygame.mixer.init()pygame.mixer.music.load('./Jibbs - Chain Hang Low.mp3')pygame.mixer.music.play(-1)now = 0while True:# 处理事件self.handle_event()# 不暂停if self.pause == False and self.lose == False:# 计算元素坐标# 每3秒画个新柱子if now == 90:self.action_elements(True)now = 0else:self.action_elements(False)now += 1# 绘制元素图片self.draw_elements()# 碰撞检测state = self.detect_conlision()if state == 1:self.point += 1 elif state == -1:pygame.display.set_caption("Flappy Bird v1.0 游戏终止 得分:" + str(float('%.2f' % self.point))) pygame.mixer.music.stop()self.lose = True# 刷新显示pygame.display.update()fpsClock.tick(FPS)# 入口函数
if __name__ == "__main__":# 创建主场景mainScene = MainScene()# 开始游戏mainScene.run_scene()

代码及素材:(8M)

链接:https://pan.baidu.com/s/1cMDdPQRYl_wpvKIMKiXtbA
提取码:awsl

github:https://github.com/callmebg/pygame_examples/tree/master/flappyBird/src