【Python游戏】基于化学方程式的基础上,用Python实现一个消灭泡泡小游戏 | 附源码

前言

halo,包子们下午好
今天实现的这个小游戏呀,说实话化学不太好的小伙伴可能看起来会有点懵逼
不过不用担心,咱们今天不是来学化学的,我们是来学习Python的
所以呀,不要太担心啦,大家先好好看看这个实现过程,然后在开始学习就好啦
有啥问题都可以找到小编帮大家解决哈

相关文件

源码领取公众号:Python日志
源码点击蓝色字体领取

开发工具

Python版本:3.7.8
相关模块:
pygame模块;
random模块;
bubble模块;
fish模块;
traceback模块;
以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

效果展示

开始界面

【Python游戏】基于化学方程式的基础上,用Python实现一个消灭泡泡小游戏 | 附源码_第1张图片

游戏界面

【Python游戏】基于化学方程式的基础上,用Python实现一个消灭泡泡小游戏 | 附源码_第2张图片

结束界面

【Python游戏】基于化学方程式的基础上,用Python实现一个消灭泡泡小游戏 | 附源码_第3张图片

代码展示

导入模块

import pygame
from pygame.locals import *
import sys
import os
import traceback
import fish
import bubble
import bullet
from bubble import *

基础设置

# 初始化
pygame.init()
pygame.mixer.init()

# 设置尺寸参数
bg_size = width,height = 480,800
# 设置窗口
screen = pygame.display.set_mode(bg_size)
# 设置标题
pygame.display.set_caption("消灭泡泡 源码领取加QQ群:494958217")
# 加载背景图片
background = pygame.image.load("tuxiang/bg.png").convert()
# 加载游戏开始图片
game_start = pygame.image.load("tuxiang/game_start.png").convert_alpha()
# 加载游戏重新开始图片
game_restart = pygame.image.load("tuxiang/game_restart.png").convert_alpha()
game_restart_rect = game_restart.get_rect()
game_restart_rect.left, game_restart_rect.top = width - game_restart_rect.width - 160, 520
# 加载游戏准备图片
game_loading1 = pygame.image.load("tuxiang/game_loading1.png").convert_alpha()
game_loading2 = pygame.image.load("tuxiang/game_loading2.png").convert_alpha()
game_loading3 = pygame.image.load("tuxiang/game_loading3.png").convert_alpha()
game_loading_rect = game_loading1.get_rect()

# 加载暂停图片
game_stop = pygame.image.load("tuxiang/game_stop.png").convert_alpha()
game_stop_rect = game_stop.get_rect()
# 加载游戏结束图片
game_over = pygame.image.load("tuxiang/game_over.png").convert()
# 加载暂停键图片
game_pause_nor = pygame.image.load("tuxiang/game_pause_nor.png").convert_alpha()
game_pause_pressed = pygame.image.load("tuxiang/game_pause_pressed.png").convert_alpha()
# 加载继续键图片
game_resume_nor = pygame.image.load("tuxiang/game_resume_nor.png").convert_alpha()
game_resume_pressed = pygame.image.load("tuxiang/game_resume_pressed.png").convert_alpha()
# 暂停键按钮范围值
paused_rect = game_pause_nor.get_rect()
paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
paused_image = game_pause_nor
resume_image = game_resume_nor
# 加载'生命'数量图片
life_image = pygame.image.load("tuxiang/life.png").convert_alpha()
life_rect = life_image.get_rect()
life_num = 3

# 设置音乐变量
bg_music = pygame.mixer.music
game_achievement_sound = pygame.mixer
game_over_sound = pygame.mixer
bullet_sound = pygame.mixer
bubble1_down_sound = pygame.mixer
bubble2_out_sound = pygame.mixer
bubble2_down_sound = pygame.mixer
pygame.mixer.set_num_channels(15)      # 设置音轨通道
volume = 0.6                           # 音量

# 加载游戏音乐,设置音量
bg_music.load("music/game_music.mp3")
game_achievement_sound = game_achievement_sound.Sound("music/game_achievement.wav")
game_over_sound = game_over_sound.Sound("music/game_over.wav")
bubble1_down_sound = bubble1_down_sound.Sound("music/bubble1_down.wav")
bubble2_out_sound = bubble2_out_sound.Sound("music/bubble2_out.wav")
bubble2_down_sound = bubble2_down_sound.Sound("music/bubble2_down.wav")
bg_music.set_volume(volume)
game_achievement_sound.set_volume(volume)
game_over_sound.set_volume(volume)
bubble1_down_sound.set_volume(volume)
bubble2_out_sound.set_volume(volume)
bubble2_down_sound.set_volume(volume)

# 基础参数
WHITE = (255,255,255)  # 白色
GREEN = (0, 255, 0)    # 绿色
RED = (255, 0, 0)      # 红色
destroy_speed = 5     # 销毁速度
bullet_speed = 10      # 子弹初始射速
msec = 45 * 1000       # 毫秒数

主函数

def main():
    run = True                      # 循环控制参数
    start = False                   # 游戏开始参数
    paussed = True                  # 暂停标志参数
    clock = pygame.time.Clock()     # 帧率控制
    delay = 100                     # 延迟设置
    score = 0                       # 设置得分
    grade1 = 50                     # 小型泡泡分数
    grade2 = 50
    grade3 = 50
    level = 1                       # 等级水平
    life_num = 3                    # 生命数
    # 字体设置
    score_font = pygame.font.Font("font/font.ttf",35)
    game_over_font = pygame.font.Font("font/font.ttf",30)
    # 设置"游戏准备"图片精灵
    game_loadings = list()
    game_loadings_index = 0
    game_loadings_num = 3
    game_loadings.append(game_loading1)
    game_loadings.append(game_loading2)
    game_loadings.append(game_loading3)
    # 背景音乐播放
    bg_music.play(-1)
    # 实例化鱼
    hero = fish.Fish(bg_size)
    # 实例化泡泡组
    enemies = pygame.sprite.Group()
    # 实例化小型泡泡一
    mini_enemise = pygame.sprite.Group()
    add_enemies('mini',bg_size,mini_enemise,enemies,8)
    # 实例化小型泡泡二
    other_enemise = pygame.sprite.Group()
    add_enemies('other',bg_size,other_enemise,enemies,8)
    # 实例化小型泡泡三
    other2_enemise = pygame.sprite.Group()
    add_enemies('other2',bg_size,other2_enemise,enemies,8)
    # 实例化小型泡泡四
    other3_enemise = pygame.sprite.Group()
    add_enemies('other3',bg_size,other3_enemise,enemies,8)
    # 实例化中型泡泡
    medium_enemise = pygame.sprite.Group()
    add_enemies('medium', bg_size, medium_enemise, enemies, 4)
    
    
    # 实例化子弹
    bullets = []
    # 子弹索引下标
    bullets_index = 0
    # 初始子弹数目
    bullet_num = 4
    
    for i in range(bullet_num):
        bullets.append(bullet.Bullet(hero.rect.midtop))
        #定时
        supply_time =  USEREVENT
        pygame.time.set_timer(supply_time, msec)

    # 游戏循环
    while run:
        # 事件检测
        for event in pygame.event.get():
            # 右上角关闭按钮检测
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # 鼠标点击检测
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    # 游戏开始
                    start = True
                if event.button == 1 and paused_rect.collidepoint(event.pos):
                    paussed = not paussed
                    if not paussed:
                        pygame.time.set_timer(supply_time, 0)
                        # 暂停音效
                        pygame.mixer.music.pause()
                        pygame.mixer.pause()
                    else:
                        pygame.time.set_timer(supply_time, msec)
                        # 恢复音效
                        pygame.mixer.music.unpause()
                        pygame.mixer.unpause()
                if event.button == 1 and game_restart_rect.collidepoint(event.pos):
                    # 重新开始
                    main()


            # 鼠标放置坐标检测
            elif event.type == MOUSEMOTION:
                if paused_rect.collidepoint(event.pos):
                    if paussed:
                        paused_image = game_resume_pressed
                    else:
                        paused_image = game_pause_pressed
                else:
                    if paussed:
                        paused_image = game_resume_nor
                    else:
                        paused_image = game_pause_nor
       

                 
#            # 键盘按键检测
#            elif event.type == KEYDOWN:
#                if event.key == K_SPACE:
                    

        # 视情况提升等级
        if level < get_level(score) + 1:
            level += 1
            print('等级提升!')
            game_achievement_sound.play()
            # 增加一定批次的泡泡
            add_enemies('mini', bg_size, mini_enemise, enemies, 3)
            add_enemies('other', bg_size, other_enemise, enemies, 3)
            add_enemies('other2', bg_size, other2_enemise, enemies, 3)
            add_enemies('other3', bg_size, other3_enemise, enemies, 3)
            add_enemies('medium', bg_size, medium_enemise, enemies, 2) 

管理我方飞机的类

import pygame
from pygame.locals import *

class Plane(pygame.sprite.Sprite):

    
    # 初始化类
    def __init__(self,bg_size):
        # 初始化碰撞检测
        pygame.sprite.Sprite.__init__(self)
        # 加载飞机素材1
        self.plane1 = pygame.image.load("tuxiang/fsh.png").convert_alpha()
                # 最终输出的飞机
        self.plane = self.plane1
        # 获取飞机实际像素区域
        self.mask = pygame.mask.from_surface(self.plane)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        self.spirit1 = pygame.image.load("tuxiang/fsh.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/ys.png").convert_alpha()
        self.spirit3 = pygame.image.load("tuxiang/ys2.png").convert_alpha()
        # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 切换参数
        self.swich = True
        # 计数器总数
        self.count = 3
        # 计数器
        self.scaler = self.count
        # 获取图片矩形大小
        self.rect = self.plane1.get_rect()
        # 获取游戏区域 宽 和 高
        self.width, self.height = bg_size[0], bg_size[1]
        # 设置移动速度
        self.speed = 10
        # 初始化位置
        self.set_position()
        #初始化类别
        self.type_cls = 0
        
        
    # 上移
    def moveUp(self):
        if self.rect.top > 0:
            self.rect.top -= self.speed
        else:
            self.rect.top = 0

    # 下移
    def moveDown(self):
        if self.rect.bottom < self.height - 50:
            self.rect.bottom += self.speed
        else:
            self.rect.bottom =self.height - 50

    # 左移
    def moveLeft(self):
        if self.rect.left > 0:
            self.rect.left -= self.speed
        else:
            self.rect.left = 0

    # 右移
    def moveRight(self):
        if self.rect.right < self.width:
            self.rect.right += self.speed
        else:
            self.rect.right = self.width
                       
    #移动的总操作方法
    def move(self):
        # 获取用户键盘操作
        self.key_pressed = pygame.key.get_pressed()
        # 进行操作判断
        if self.key_pressed[K_w] or self.key_pressed[K_UP]:
            self.moveUp()
        if self.key_pressed[K_s] or self.key_pressed[K_DOWN]:
            self.moveDown()
        if self.key_pressed[K_a] or self.key_pressed[K_LEFT]:
            self.moveLeft()
        if self.key_pressed[K_d] or self.key_pressed[K_RIGHT]:
            self.moveRight()

            
            
            
        

            # 计数器判定
#        if self.scaler == 0:
#            self.swich = not self.swich
#            self.scaler = self.count
#        # 计数器计数
#        self.scaler -= 1

    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 连同精灵下标也归零
        self.spirits_index = 0
        # 设置飞机左侧坐标
        self.rect.left = (self.width - self.rect.width) / 2
        # 设置飞机的顶部坐标
        self.rect.top = self.height - self.rect.height - 50

子弹类

import pygame
from pygame.locals import *


class Bullet(pygame.sprite.Sprite): #定义子弹精灵

    # 初始化类
    def __init__(self, position):
        pygame.sprite.Sprite.__init__(self)
        # 加载子弹素材1
        self.type_cls = 0
        self.bullet1 = pygame.image.load("tuxiang/zidan1.png")
        # 加载子弹素材2
        self.bullet2 = pygame.image.load("tuxiang/zidan2.png")
        # 最终输出子弹
        self.bullet = self.bullet1
        # 获取子弹实际像素区域
        self.mask = pygame.mask.from_surface(self.bullet)
        # 获取图片矩形大小
        self.rect = self.bullet.get_rect()
        # 初始化子弹坐标
        self.set_position(position)
        # 设置子弹速度
        self.speed = 15

  
    # 移动方法,到达顶端就消失
    def move(self):
        self.rect.top -= self.speed
        if self.rect.top < 0:
            self.active = False


    # 设置子弹坐标
    def set_position(self, position):
        # 设置存在状态
        self.survival = True
        # 子弹坐标设置
        self.rect.left, self.rect.top = position


小型气泡类

import pygame
from random import *

# 小型气泡类
class MiniBubble(pygame.sprite.Sprite):
    
    # 初始化类
    def __init__(self,bg_size):
        pygame.sprite.Sprite.__init__(self)
        # 加载气泡素材
        self.bubble1 = pygame.image.load("tuxiang/bubble1.png").convert_alpha()
        self.bubble = self.bubble1
        # 获取气泡实际像素区域
        self.mask = pygame.mask.from_surface(self.bubble)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        
        self.spirit1 = pygame.image.load("tuxiang/bubble1.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/bubble1_down1.png").convert_alpha() #加载气泡炸裂的图片
        self.spirit3 = pygame.image.load("tuxiang/bubble1_down2.png").convert_alpha()
        
        # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 气泡尺寸
        self.rect = self.bubble1.get_rect()
        self.width, self.height = bg_size[0], bg_size[1]
        # 气泡速度
        self.speed = 2
        # 初始化位置
        self.set_position()

    # 气泡移动类,如果到屏幕底端还没有被子弹击中就消失
    def move(self):
        if self.rect.top < self.height:
            self.rect.top += self.speed
        else:
            self.set_position()


    # 定义气泡初始位置
    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 连同精灵下标也归零
        self.spirits_index = 0
        # 气泡出现时左侧坐标
        self.rect.left = randint(0, self.width - self.rect.width)
        # 气泡出现时顶部坐标
        self.rect.top = randint(-3 * self.height, 0)

# 一类气泡类
class OtherBubble(pygame.sprite.Sprite):
    
    # 初始化类
    def __init__(self,bg_size):
        pygame.sprite.Sprite.__init__(self)
        # 加载气泡素材
        self.bubble3 = pygame.image.load("tuxiang/bubble3.png").convert_alpha()
        self.bubble = self.bubble3
        # 获取气泡实际像素区域
        self.mask = pygame.mask.from_surface(self.bubble)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        
        self.spirit1 = pygame.image.load("tuxiang/bubble3.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/bubble3_down1.png").convert_alpha()
        self.spirit3 = pygame.image.load("tuxiang/bubble3_down2.png").convert_alpha()
        
        # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 气泡尺寸
        self.rect = self.bubble3.get_rect()
        self.width, self.height = bg_size[0], bg_size[1]
        # 气泡速度
        self.speed = 2
        # 初始化位置
        self.set_position()

    # 气泡移动类
    def move(self):
        if self.rect.top < self.height:
            self.rect.top += self.speed
        else:
            self.set_position()


    # 定义气泡初始位置
    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 连同精灵下标也归零
        self.spirits_index = 0
        # 气泡出现时左侧坐标
        self.rect.left = randint(0, self.width - self.rect.width)
        # 气泡出现时顶部坐标
        self.rect.top = randint(-3 * self.height, 0)

# 二类气泡类
class Other2Bubble(pygame.sprite.Sprite):
    
    # 初始化类
    def __init__(self,bg_size):
        pygame.sprite.Sprite.__init__(self)
        # 加载气泡素材
        self.bubble4 = pygame.image.load("tuxiang/bubble4.png").convert_alpha()
        self.bubble = self.bubble4
        # 获取气泡实际像素区域
        self.mask = pygame.mask.from_surface(self.bubble)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        
        self.spirit1 = pygame.image.load("tuxiang/bubble4.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/bubble4_down1.png").convert_alpha()
        self.spirit3 = pygame.image.load("tuxiang/bubble4_down2.png").convert_alpha()
        
        # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 气泡尺寸
        self.rect = self.bubble4.get_rect()
        self.width, self.height = bg_size[0], bg_size[1]
        # 气泡速度
        self.speed = 2
        # 初始化位置
        self.set_position()

    # 气泡移动类
    def move(self):
        if self.rect.top < self.height:
            self.rect.top += self.speed
        else:
            self.set_position()


    # 定义气泡初始位置
    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 连同精灵下标也归零
        self.spirits_index = 0
        # 气泡出现时左侧坐标
        self.rect.left = randint(0, self.width - self.rect.width)
        # 气泡出现时顶部坐标
        self.rect.top = randint(-3 * self.height, 0)

# 三类气泡类
class Other3Bubble(pygame.sprite.Sprite):
    
    # 初始化类
    def __init__(self,bg_size):
        pygame.sprite.Sprite.__init__(self)
        # 加载气泡素材
        self.bubble5 = pygame.image.load("tuxiang/bubble5.png").convert_alpha()
        self.bubble = self.bubble5
        # 获取气泡实际像素区域
        self.mask = pygame.mask.from_surface(self.bubble)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        
        self.spirit1 = pygame.image.load("tuxiang/bubble5.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/bubble5_down1.png").convert_alpha()
        self.spirit3 = pygame.image.load("tuxiang/bubble5_down2.png").convert_alpha()
        
        # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 气泡尺寸
        self.rect = self.bubble5.get_rect()
        self.width, self.height = bg_size[0], bg_size[1]
        # 气泡速度
        self.speed = 2
        # 初始化位置
        self.set_position()

    # 气泡移动类
    def move(self):
        if self.rect.top < self.height:
            self.rect.top += self.speed
        else:
            self.set_position()  #初始化位置


    # 定义气泡初始位置
    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 连同精灵下标也归零
        self.spirits_index = 0
        # 气泡出现时左侧坐标
        self.rect.left = randint(0, self.width - self.rect.width)
        # 气泡出现时顶部坐标
        self.rect.top = randint(-3 * self.height, 0)


# 中型气泡
class MediumBubble(pygame.sprite.Sprite):
    hp = 5

    # 初始化类
    def __init__(self,bg_size):
        pygame.sprite.Sprite.__init__(self)
        # 加载中型敌机素材
        self.bubble2 = pygame.image.load("tuxiang/bubble2.png").convert_alpha()
        self.bubble = self.bubble2
        # 加载被击中素材
        self.bubble_hit = pygame.image.load("tuxiang/bubble2_hit.png").convert_alpha()

        # 设置是否被击中的参数
        self.hit = False
        # 获取气泡实际像素区域
        self.mask = pygame.mask.from_surface(self.bubble)
        # 设置精灵列表
        self.death_spirits = list()
        # 加载精灵素材
        self.spirit1 = pygame.image.load("tuxiang/bubble2.png").convert_alpha()
        self.spirit2 = pygame.image.load("tuxiang/bubble2_down1.png").convert_alpha()
        self.spirit3 = pygame.image.load("tuxiang/bubble2_down2.png").convert_alpha()
        # # 将精灵存放进精灵列表中
        self.death_spirits.extend([self.spirit1, self.spirit2, self.spirit3])
        # 设置精灵列表播放下标
        self.spirits_index = 0
        # 气泡尺寸
        self.rect = self.bubble2.get_rect()
        self.width, self.height = bg_size[0], bg_size[1]
        # 气泡速度
        self.speed = 1.5
        # 初始化位置
        self.set_position()
    # 气泡移动类
    def move(self):
        if self.rect.top < self.height:
            self.rect.top += self.speed
        else:
            self.set_position()

    # 定义气泡初始位置
    def set_position(self):
        # 设置存活属性
        self.survival = True
        # 设置血量
        self.hp = MediumBubble.hp
       # 连同精灵下标也归零
        self.spirits_index = 0
        # 气泡出现时左侧坐标
        self.rect.left = randint(0, self.width - self.rect.width)
        # 气泡出现时顶部坐标
        self.rect.top = randint(-5 * self.height, -self.height)

class Bubble(pygame.sprite.Sprite):  #随机生成四种气泡
    def _init_(self):
        if random.random()<0.21:
            bubble()._init_("tuxiang/bubble1.png")
        elif random.random()>0.81:
            bubble()._init_("tuxiang/bubble4.png")
        elif random.random()>0.21 and random.random()<0.4:
            bubble._init_("tuxiang/bubble5.png")
        else:
            bubble()._init_("tuxiang/bubble3.png")
            
# 添加气泡组(气泡类型,背景大小,气泡组1,气泡组2,生成气泡数量)
def add_enemies(size,bg_size,group1,group2,num):
    for i in range(num):  #这里的num是指气泡的数量
        if(size == 'mini'):
            bubble = MiniBubble(bg_size) #创建小型气泡
        if(size == 'other'):
            bubble = OtherBubble(bg_size)
        if(size == 'other2'):
            bubble = Other2Bubble(bg_size)
        if(size == 'other3'):
            bubble = Other3Bubble(bg_size)
        if(size == 'medium'):
            bubble = MediumBubble(bg_size)
        group1.add(bubble)  #将气泡添加到组中
        group2.add(bubble)



# 控制气泡数量,分数越高,气泡越多
def get_level(num):
    result = 0
    if num >= 200:
        num2 = 1
        while num2 < num:
            num2 *= 2
            result += 1
        result -= 12
    return result

总结

其实实现起来并不是很难,就要看大家能不能好好仔细去琢磨
上面是部分代码实现过程,源码领取看相关文件

你可能感兴趣的:(python,python,游戏,pygame)