python小游戏——像素鸟代码开源

简介: python小游戏——像素鸟代码开源

一.呈现效果

二.主代码

'''
Function:
    坠落的小鸟小游戏
'''
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('坠落的小鸟 ——源码基地:959755565 ')
    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()

三.cfg

'''配置文件'''

import os



# FPS

FPS = 60

# 屏幕

SCREENWIDTH = 288

SCREENHEIGHT = 512

# 管道之间的空隙

PIPE_GAP_SIZE = 100

# 图片

NUMBER_IMAGE_PATHS = {

   '0': os.path.join(os.getcwd(), 'resources/images/0.png'),

   '1': os.path.join(os.getcwd(), 'resources/images/1.png'),

   '2': os.path.join(os.getcwd(), 'resources/images/2.png'),

   '3': os.path.join(os.getcwd(), 'resources/images/3.png'),

   '4': os.path.join(os.getcwd(), 'resources/images/4.png'),

   '5': os.path.join(os.getcwd(), 'resources/images/5.png'),

   '6': os.path.join(os.getcwd(), 'resources/images/6.png'),

   '7': os.path.join(os.getcwd(), 'resources/images/7.png'),

   '8': os.path.join(os.getcwd(), 'resources/images/8.png'),

   '9': os.path.join(os.getcwd(), 'resources/images/9.png')

}

BIRD_IMAGE_PATHS = {

   'red': {

       'up': os.path.join(os.getcwd(), 'resources/images/redbird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/redbird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/redbird-downflap.png')

   },

   'blue': {

       'up': os.path.join(os.getcwd(), 'resources/images/bluebird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/bluebird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/bluebird-downflap.png')

   },

   'yellow': {

       'up': os.path.join(os.getcwd(), 'resources/images/yellowbird-upflap.png'),

       'mid': os.path.join(os.getcwd(), 'resources/images/yellowbird-midflap.png'),

       'down': os.path.join(os.getcwd(), 'resources/images/yellowbird-downflap.png')

   }

}

BACKGROUND_IMAGE_PATHS = {

   'day': os.path.join(os.getcwd(), 'resources/images/background-day.png'),

   'night': os.path.join(os.getcwd(), 'resources/images/background-night.png')

}

PIPE_IMAGE_PATHS = {

   'green': os.path.join(os.getcwd(), 'resources/images/pipe-green.png'),

   'red': os.path.join(os.getcwd(), 'resources/images/pipe-red.png')

}

OTHER_IMAGE_PATHS = {

   'gameover': os.path.join(os.getcwd(), 'resources/images/gameover.png'),

   'message': os.path.join(os.getcwd(), 'resources/images/message.png'),

   'base': os.path.join(os.getcwd(), 'resources/images/base.png')

}

# 音频路径

AUDIO_PATHS = {

   'die': os.path.join(os.getcwd(), 'resources/audios/die.wav'),

   'hit': os.path.join(os.getcwd(), 'resources/audios/hit.wav'),

   'point': os.path.join(os.getcwd(), 'resources/audios/point.wav'),

   'swoosh': os.path.join(os.getcwd(), 'resources/audios/swoosh.wav'),

   'wing': os.path.join(os.getcwd(), 'resources/audios/wing.wav')

}

四.README


# Introduction

https://mp.weixin.qq.com/s/44CZjwvjnH0kkkKIn5U9Uw


# Environment

```

OS: Windows10

Python: Python3.5+(have installed necessary dependencies)

```


# Usage

```

Step1:

pip install -r requirements.txt

Step2:

run "python Game6.py"

```


# Game Display

![giphy](demonstration/running.gif)


目录
打赏
0
0
0
0
2
分享
相关文章
中国版“Manus”开源?AiPy:用Python重构AI生产力的通用智能体
AiPy是LLM大模型+Python程序编写+Python程序运行+程序可以控制的一切。
从零复现Google Veo 3:从数据预处理到视频生成的完整Python代码实现指南
本文详细介绍了一个简化版 Veo 3 文本到视频生成模型的构建过程。首先进行了数据预处理,涵盖了去重、不安全内容过滤、质量合规性检查以及数据标注等环节。
104 5
从零复现Google Veo 3:从数据预处理到视频生成的完整Python代码实现指南
从零开始200行python代码实现LLM
本文从零开始用Python实现了一个极简但完整的大语言模型,帮助读者理解LLM的工作原理。首先通过传统方法构建了一个诗词生成器,利用字符间的概率关系递归生成文本。接着引入PyTorch框架,逐步重构代码,实现了一个真正的Bigram模型。文中详细解释了词汇表(tokenizer)、张量(Tensor)、反向传播、梯度下降等关键概念,并展示了如何用Embedding层和线性层搭建模型。最终实现了babyGPT_v1.py,一个能生成类似诗词的简单语言模型。下一篇文章将在此基础上实现自注意力机制和完整的GPT模型。
119 14
从零开始200行python代码实现LLM
200行python代码实现从Bigram模型到LLM
本文从零基础出发,逐步实现了一个类似GPT的Transformer模型。首先通过Bigram模型生成诗词,接着加入Positional Encoding实现位置信息编码,再引入Single Head Self-Attention机制计算token间的关系,并扩展到Multi-Head Self-Attention以增强表现力。随后添加FeedForward、Block结构、残差连接(Residual Connection)、投影(Projection)、层归一化(Layer Normalization)及Dropout等组件,最终调整超参数完成一个6层、6头、384维度的“0.0155B”模型
116 11
200行python代码实现从Bigram模型到LLM
用 Python 制作简单小游戏教程:手把手教你开发猜数字游戏
本教程详细讲解了用Python实现经典猜数字游戏的完整流程,涵盖从基础规则到高级功能的全方位开发。内容包括游戏逻辑设计、输入验证与错误处理、猜测次数统计、难度选择、彩色输出等核心功能,并提供完整代码示例。同时,介绍了开发环境搭建及调试方法,帮助初学者快速上手。最后还提出了图形界面、网络对战、成就系统等扩展方向,鼓励读者自主创新,打造个性化游戏版本。适合Python入门者实践与进阶学习。
87 1
图神经网络在信息检索重排序中的应用:原理、架构与Python代码解析
本文探讨了基于图的重排序方法在信息检索领域的应用与前景。传统两阶段检索架构中,初始检索速度快但结果可能含噪声,重排序阶段通过强大语言模型提升精度,但仍面临复杂需求挑战
82 0
图神经网络在信息检索重排序中的应用:原理、架构与Python代码解析
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
本文探讨了多模态RAG系统的最优实现方案,通过模态特定处理与后期融合技术,在性能、准确性和复杂度间达成平衡。系统包含文档分割、内容提取、HTML转换、语义分块及向量化存储五大模块,有效保留结构和关系信息。相比传统方法,该方案显著提升了复杂查询的检索精度(+23%),并支持灵活升级。文章还介绍了查询处理机制与优势对比,为构建高效多模态RAG系统提供了实践指导。
405 0
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
Python与MongoDB的亲密接触:从入门到实战的代码指南
本文详细介绍了Python与MongoDB结合使用的实战技巧,涵盖环境搭建、连接管理、CRUD操作、高级查询、索引优化、事务处理及性能调优等内容。通过15个代码片段,从基础到进阶逐步解析,帮助开发者掌握这对黄金组合的核心技能。内容包括文档结构设计、批量操作优化、聚合管道应用等实用场景,适合希望高效处理非结构化数据的开发者学习参考。
49 0
python小游戏——贪吃蛇游戏4.0版本の背景音乐和音效功能实现
python小游戏——贪吃蛇游戏4.0版本の背景音乐和音效功能实现
333 0
python小游戏——贪吃蛇游戏3.0版本の历史最高得分记录功能实现
python小游戏——贪吃蛇游戏3.0版本の历史最高得分记录功能实现
375 0

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问