Python-飞翔的小鸟【附源码】

飞翔的小鸟

飞翔的小鸟是一款经典的休闲游戏,玩家需要操控一只小鸟在空中飞行;游戏界面简约易懂,具有简单直观的操作方式,使得任何玩家都能很快上手,做一只飞翔的小鸟~~~

运行效果:玩家通过方向键上下两键即可操纵游戏!

在这里插入图片描述
在这里插入图片描述

import cfg
import sys
import random
import pygame
from modules import *

'''游戏初始化'''
def initGame():
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((cfg.SCREENWIDTH, cfg.SCREENHEIGHT))
    pygame.display.set_caption('飞翔的小鸟')
    return screen


'''显示当前分数'''
def showScore(screen, score, number_images):
    digits = list(str(int(score)))
    width = 0
    for d in digits:
        width += number_images.get(d).get_width()
    offset = (cfg.SCREENWIDTH - width) / 2
    for d in digits:
        screen.blit(number_images.get(d), (offset, cfg.SCREENHEIGHT*0.1))
        offset += number_images.get(d).get_width()


'''主函数'''
def main():
    screen = initGame()
    # 加载必要的游戏资源
    # --导入音频
    sounds = dict()
    for key, value in cfg.AUDIO_PATHS.items():
        sounds[key] = pygame.mixer.Sound(value)
    # --导入数字图片
    number_images = dict()
    for key, value in cfg.NUMBER_IMAGE_PATHS.items():
        number_images[key] = pygame.image.load(value).convert_alpha()
    # --管道
    pipe_images = dict()
    pipe_images['bottom'] = pygame.image.load(random.choice(list(cfg.PIPE_IMAGE_PATHS.values()))).convert_alpha()
    pipe_images['top'] = pygame.transform.rotate(pipe_images['bottom'], 180)
    # --小鸟图片
    bird_images = dict()
    for key, value in cfg.BIRD_IMAGE_PATHS[random.choice(list(cfg.BIRD_IMAGE_PATHS.keys()))].items():
        bird_images[key] = pygame.image.load(value).convert_alpha()
    # --背景图片
    backgroud_image = pygame.image.load(random.choice(list(cfg.BACKGROUND_IMAGE_PATHS.values()))).convert_alpha()
    # --其他图片
    other_images = dict()
    for key, value in cfg.OTHER_IMAGE_PATHS.items():
        other_images[key] = pygame.image.load(value).convert_alpha()
    # 游戏开始界面
    game_start_info = startGame(screen, sounds, bird_images, other_images, backgroud_image, cfg)
    # 进入主游戏
    score = 0
    bird_pos, base_pos, bird_idx = list(game_start_info.values())
    base_diff_bg = other_images['base'].get_width() - backgroud_image.get_width()
    clock = pygame.time.Clock()
    # --管道类
    pipe_sprites = pygame.sprite.Group()
    for i in range(2):
        pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
        pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('top')[-1])))
        pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('bottom')[-1])))
    # --bird类
    bird = Bird(images=bird_images, idx=bird_idx, position=bird_pos)
    # --是否增加pipe
    is_add_pipe = True
    # --游戏是否进行中
    is_game_running = True
    while is_game_running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                    bird.setFlapped()
                    sounds['wing'].play()
        # --碰撞检测
        for pipe in pipe_sprites:
            if pygame.sprite.collide_mask(bird, pipe):
                sounds['hit'].play()
                is_game_running = False
        # --更新小鸟
        boundary_values = [0, base_pos[-1]]
        is_dead = bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.)
        if is_dead:
            sounds['hit'].play()
            is_game_running = False
        # --移动base实现小鸟往前飞的效果
        base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg)
        # --移动pipe实现小鸟往前飞的效果
        flag = False
        for pipe in pipe_sprites:
            pipe.rect.left -= 4
            if pipe.rect.centerx < bird.rect.centerx and not pipe.used_for_score:
                pipe.used_for_score = True
                score += 0.5
                if '.5' in str(score):
                    sounds['point'].play()
            if pipe.rect.left < 5 and pipe.rect.left > 0 and is_add_pipe:
                pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
                pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=pipe_pos.get('top')))
                pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=pipe_pos.get('bottom')))
                is_add_pipe = False
            elif pipe.rect.right < 0:
                pipe_sprites.remove(pipe)
                flag = True
        if flag: is_add_pipe = True
        # --绑定必要的元素在屏幕上
        screen.blit(backgroud_image, (0, 0))
        pipe_sprites.draw(screen)
        screen.blit(other_images['base'], base_pos)
        showScore(screen, score, number_images)
        bird.draw(screen)
        pygame.display.update()
        clock.tick(cfg.FPS)
    endGame(screen, sounds, showScore, score, number_images, bird, pipe_sprites, backgroud_image, other_images, base_pos, cfg)


'''run'''
if __name__ == '__main__':
    while True:
        main()

因为素材及源码过多,无法在文章中全部展示,关注+私信我发送源码

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个简单的飞翔小鸟Python游戏的实现,包括小鸟和管道的类方法: ```python import pygame import random # 初始化pygame pygame.init() # 设置游戏窗口大小 screen_width = 288 screen_height = 512 screen = pygame.display.set_mode((screen_width, screen_height)) # 加载背景图片 background = pygame.image.load("background.png").convert() # 加载地面图片 ground = pygame.image.load("ground.png").convert() # 加载小鸟图片 bird_images = [ pygame.image.load("bird1.png").convert_alpha(), pygame.image.load("bird2.png").convert_alpha(), pygame.image.load("bird3.png").convert_alpha() ] # 加载管道图片 pipe_image = pygame.image.load("pipe.png").convert_alpha() # 设置字体 font = pygame.font.SysFont(None, 48) # 定义小鸟类 class Bird(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.images = bird_images self.index = 0 self.image = self.images[self.index] self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.speed = 0 self.gravity = 0.5 def update(self, flap=False): if flap: self.speed = -10 else: self.speed += self.gravity self.rect.y += self.speed self.index += 1 if self.index >= len(self.images): self.index = 0 self.image = self.images[self.index] def go_die(self): self.speed = 0 self.gravity = 0 self.images = [pygame.image.load("bird_die.png").convert_alpha()] # 定义管道类 class Pipe(pygame.sprite.Sprite): def __init__(self, x, y, upwards=True): pygame.sprite.Sprite.__init__(self) self.image = pipe_image self.rect = self.image.get_rect() self.rect.x = x if upwards: self.image = pygame.transform.flip(self.image, False, True) self.rect.y = y - self.rect.height - 100 else: self.rect.y = y + 100 def update(self): self.rect.x -= 5 # 创建小鸟和管道的精灵组 bird_group = pygame.sprite.Group() pipe_group = pygame.sprite.Group() # 创建小鸟对象并添加到精灵组 bird = Bird(50, 200) bird_group.add(bird) # 游戏主循环 clock = pygame.time.Clock() score = 0 while True: # 处理游戏事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.update(flap=True) # 更新小鸟和管道 bird.update() pipe_group.update() # 检测小鸟是否碰到地面或者管道 if pygame.sprite.spritecollide(bird, pipe_group, False) or bird.rect.bottom >= screen_height - ground.get_height(): bird.go_die() # 检测小鸟是否通过管道 for pipe in pipe_group: if pipe.rect.right < bird.rect.left and not pipe.passed: pipe.passed = True score += 1 # 添加新的管道 if len(pipe_group) < 3: pipe = Pipe(screen_width, random.randint(100, 400)) pipe_group.add(pipe) # 绘制游戏界面 screen.blit(background, (0, 0)) pipe_group.draw(screen) bird_group.draw(screen) screen.blit(ground, (0, screen_height - ground.get_height())) # 显示分数 score_text = font.render(str(score), True, (255, 255, 255)) screen.blit(score_text, (screen_width // 2 - score_text.get_width() // 2, 50)) # 更新屏幕 pygame.display.update() # 控制游戏帧率 clock.tick(30) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温轻舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值