python小游戏——跑酷小恐龙代码开源

简介: python小游戏——跑酷小恐龙代码开源

一.效果呈现

二.主代码

'''
Function:
Author:
    Charles
'''
import cfg
import sys
import random
import pygame
from modules import *
'''main'''
def main(highest_score):
    # 游戏初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('小恐龙闯关游戏')
    # 导入所有声音文件
    sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        sounds[key] = pygame.mixer.Sound(value)
    # 游戏开始界面
    GameStartInterface(screen, sounds, cfg)
    # 定义一些游戏中必要的元素和变量
    score = 0
    score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)
    highest_score = highest_score
    highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True)
    dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
    ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1]))
    cloud_sprites_group = pygame.sprite.Group()
    cactus_sprites_group = pygame.sprite.Group()
    ptera_sprites_group = pygame.sprite.Group()
    add_obstacle_timer = 0
    score_timer = 0
    # 游戏主循环
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                    dino.jump(sounds)
                elif event.key == pygame.K_DOWN:
                    dino.duck()
            elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
                dino.unduck()
        screen.fill(cfg.BACKGROUND_COLOR)
        # --随机添加云
        if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
            cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75))))
        # --随机添加仙人掌/飞龙
        add_obstacle_timer += 1
        if add_obstacle_timer > random.randrange(50, 150):
            add_obstacle_timer = 0
            random_value = random.randrange(0, 10)
            if random_value >= 5 and random_value <= 7:
                cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
            else:
                position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20]
                ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys))))
        # --更新游戏元素
        dino.update()
        ground.update()
        cloud_sprites_group.update()
        cactus_sprites_group.update()
        ptera_sprites_group.update()
        score_timer += 1
        if score_timer > (cfg.FPS//12):
            score_timer = 0
            score += 1
            score = min(score, 99999)
            if score > highest_score:
                highest_score = score
            if score % 100 == 0:
                sounds['point'].play()
            if score % 1000 == 0:
                ground.speed -= 1
                for item in cloud_sprites_group:
                    item.speed -= 1
                for item in cactus_sprites_group:
                    item.speed -= 1
                for item in ptera_sprites_group:
                    item.speed -= 1
        # --碰撞检测
        for item in cactus_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        for item in ptera_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        # --将游戏元素画到屏幕上
        dino.draw(screen)
        ground.draw(screen)
        cloud_sprites_group.draw(screen)
        cactus_sprites_group.draw(screen)
        ptera_sprites_group.draw(screen)
        score_board.set(score)
        highest_score_board.set(highest_score)
        score_board.draw(screen)
        highest_score_board.draw(screen)
        # --更新屏幕
        pygame.display.update()
        clock.tick(cfg.FPS)
        # --游戏是否结束
        if dino.is_dead:
            break
    # 游戏结束界面
    return GameEndInterface(screen, cfg), highest_score
'''run'''
if __name__ == '__main__':
    highest_score = 0
    while True:
        flag, highest_score = main(highest_score)
        if not flag: break

三.cfg


'''配置文件'''

import os



'''屏幕大小'''

SCREENSIZE = (600, 150)

'''FPS'''

FPS = 60

'''音频素材路径'''

AUDIO_PATHS = {

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

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

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

}

'''图片素材路径'''

IMAGE_PATHS = {

   'cacti': [

       os.path.join(os.getcwd(), 'resources/images/cacti-big.png'),

       os.path.join(os.getcwd(), 'resources/images/cacti-small.png')

   ],

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

   'dino': [

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

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

   ],

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

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

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

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

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

}

'''背景颜色'''

BACKGROUND_COLOR = (235, 235, 235)

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)



四.README

# Introduction

https://mp.weixin.qq.com/s/PnvcSBe0Va3GVIodGIjYRg


# Environment

```

OS: Windows10

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

```


# Usage

```

Step1:

pip install -r requirements.txt

Step2:

run "python Game7.py"

```


# Game Display

![giphy](demonstration/running.gif)




相关文章
|
2天前
|
C++ 开发者 Python
实现Python日志点击跳转到代码位置的方法
本文介绍了如何在Python日志中实现点击跳转到代码位置的功能,以提升调试效率。通过结合`logging`模块的`findCaller()`方法记录代码位置信息,并使用支持点击跳转的日志查看工具(如VS Code、PyCharm),开发者可以从日志直接点击链接定位到出错代码,加快问题排查。
12 2
|
2天前
|
Python
Python代码扫描目录下的文件并获取路径
【5月更文挑战第12天】Python代码扫描目录下的文件并获取路径
17 1
|
2天前
|
数据处理 Python
Python 代码中使用。
Python 代码中使用。 z
11 3
|
2天前
|
测试技术 Python
解密Python中的装饰器:提升代码可读性与灵活性
Python中的装饰器是一种强大的工具,能够在不改变原有函数结构的情况下,为函数添加额外功能。本文将深入探讨装饰器的原理及应用,介绍装饰器的基本语法和常见用法,并结合实例演示如何利用装饰器提升代码的可读性和灵活性,使代码更加简洁、模块化和易于维护。
|
2天前
|
监控 Python
Python中的装饰器:提升代码灵活性和可维护性
在Python编程中,装饰器是一种强大的工具,可以提高代码的灵活性和可维护性。本文将深入探讨装饰器的概念、用法和实际应用,帮助读者更好地理解并运用装饰器来优化自己的Python代码。
|
2天前
|
设计模式 前端开发 数据库
Django是一个用Python编写的开源Web应用框架
Django是一个用Python编写的开源Web应用框架
15 1
|
1天前
|
网络协议 Unix Python
Python编程-----网络通信
Python编程-----网络通信
8 1
|
2天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
【5月更文挑战第9天】`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
31 5