Python版《消消乐》,附源码

news2024/10/5 2:41:25

曾经风靡一时的消消乐,至今坐在地铁上都可以看到很多人依然在玩,想当年我也是大军中的一员,那家伙,吃饭都在玩,进入到高级的那种胜利感还是很爽的,连续消,无限消,哈哈,现在想想也是很带劲的。今天就来实现一款简易版的,后续会陆续带上高阶版的,先来尝试一把。
首先我们需要准备消消乐的素材,会放在项目的resource文件夹下面,具体我准备了7种,稍后会展示给大家看的。

开心消消乐

先初始化消消乐的游戏界面参数,就是具体显示多大,每行显示多少个方块,每个方块大小,这里我们按照这个大小来设置,数量和大小看着都还挺舒服的:


'''初始化消消乐的参数'''
WIDTH = 600
HEIGHT = 640
NUMGRID = 12
GRIDSIZE = 48
XMARGIN = (WIDTH - GRIDSIZE * NUMGRID) // 2
YMARGIN = (HEIGHT - GRIDSIZE * NUMGRID) // 2
ROOTDIR = os.getcwd()
FPS = 45

每行显示12个,每个方块48个,看看效果

接下来,我们开始实现消除的逻辑:

初始化消消乐的方格:


class elimination_block(pygame.sprite.Sprite):
    def __init__(self, img_path, size, position, downlen, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(img_path)
        self.image = pygame.transform.smoothscale(self.image, size)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = position
        self.down_len = downlen
        self.target_x = position[0]
        self.target_y = position[1] + downlen
        self.type = img_path.split('/')[-1].split('.')[0]
        self.fixed = False
        self.speed_x = 10
        self.speed_y = 10
        self.direction = 'down'

移动方块:


'''拼图块移动'''

    def move(self):
        if self.direction == 'down':
            self.rect.top = min(self.target_y, self.rect.top + self.speed_y)
            if self.target_y == self.rect.top:
                self.fixed = True
        elif self.direction == 'up':
            self.rect.top = max(self.target_y, self.rect.top - self.speed_y)
            if self.target_y == self.rect.top:
                self.fixed = True
        elif self.direction == 'left':
            self.rect.left = max(self.target_x, self.rect.left - self.speed_x)
            if self.target_x == self.rect.left:
                self.fixed = True
        elif self.direction == 'right':
            self.rect.left = min(self.target_x, self.rect.left + self.speed_x)
            if self.target_x == self.rect.left:
                self.fixed = True

获取方块的坐标:

     '''获取坐标'''

    def get_position(self):
        return self.rect.left, self.rect.top

    '''设置坐标'''

    def set_position(self, position):
        self.rect.left, self.rect.top = position

绘制得分,加分,还有倒计时:


'''显示剩余时间'''

    def show_remained_time(self):
        remaining_time_render = self.font.render('CountDown: %ss' % str(self.remaining_time), 1, (85, 65, 0))
        rect = remaining_time_render.get_rect()
        rect.left, rect.top = (WIDTH - 201, 6)
        self.screen.blit(remaining_time_render, rect)

    '''显示得分'''

    def show_score(self):
        score_render = self.font.render('SCORE:' + str(self.score), 1, (85, 65, 0))
        rect = score_render.get_rect()
        rect.left, rect.top = (10, 6)
        self.screen.blit(score_render, rect)

    '''显示加分'''

    def add_score(self, add_score):
        score_render = self.font.render('+' + str(add_score), 1, (255, 100, 100))
        rect = score_render.get_rect()
        rect.left, rect.top = (250, 250)
        self.screen.blit(score_render, rect)

生成方块:


'''生成新的拼图块'''

    def generate_new_blocks(self, res_match):
        if res_match[0] == 1:
            start = res_match[2]
            while start > -2:
                for each in [res_match[1], res_match[1] + 1, res_match[1] + 2]:
                    block = self.get_block_by_position(*[each, start])
                    if start == res_match[2]:
                        self.blocks_group.remove(block)
                        self.all_blocks[each][start] = None
                    elif start >= 0:
                        block.target_y += GRIDSIZE
                        block.fixed = False
                        block.direction = 'down'
                        self.all_blocks[each][start + 1] = block
                    else:
                        block = elimination_block(img_path=random.choice(self.block_images), size=(GRIDSIZE, GRIDSIZE),
                                                position=[XMARGIN + each * GRIDSIZE, YMARGIN - GRIDSIZE],
                                                downlen=GRIDSIZE)
                        self.blocks_group.add(block)
                        self.all_blocks[each][start + 1] = block
                start -= 1
        elif res_match[0] == 2:
            start = res_match[2]
            while start > -4:
                if start == res_match[2]:
                    for each in range(0, 3):
                        block = self.get_block_by_position(*[res_match[1], start + each])
                        self.blocks_group.remove(block)
                        self.all_blocks[res_match[1]][start + each] = None
                elif start >= 0:
                    block = self.get_block_by_position(*[res_match[1], start])
                    block.target_y += GRIDSIZE * 3
                    block.fixed = False
                    block.direction = 'down'
                    self.all_blocks[res_match[1]][start + 3] = block
                else:
                    block = elimination_block(img_path=random.choice(self.block_images), size=(GRIDSIZE, GRIDSIZE),
                                            position=[XMARGIN + res_match[1] * GRIDSIZE, YMARGIN + start * GRIDSIZE],
                                            downlen=GRIDSIZE * 3)
                    self.blocks_group.add(block)
                    self.all_blocks[res_match[1]][start + 3] = block
                start -= 1

绘制拼图,移除,匹配,下滑的效果等:


'''移除匹配的block'''

    def clear_matched_block(self, res_match):
        if res_match[0] > 0:
            self.generate_new_blocks(res_match)
            self.score += self.reward
            return self.reward
        return 0

    '''游戏界面的网格绘制'''

    def draw_grids(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                rect = pygame.Rect((XMARGIN + x * GRIDSIZE, YMARGIN + y * GRIDSIZE, GRIDSIZE, GRIDSIZE))
                self.draw_block(rect, color=(0, 0, 255), size=1)

    '''画矩形block框'''

    def draw_block(self, block, color=(255, 0, 255), size=4):
        pygame.draw.rect(self.screen, color, block, size)

    '''下落特效'''

    def draw_drop_animation(self, x, y):
        if not self.get_block_by_position(x, y).fixed:
            self.get_block_by_position(x, y).move()
        if x < NUMGRID - 1:
            x += 1
            return self.draw_drop_animation(x, y)
        elif y < NUMGRID - 1:
            x = 0
            y += 1
            return self.draw_drop_animation(x, y)
        else:
            return self.is_all_full()

    '''是否每个位置都有拼图块了'''

    def is_all_full(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if not self.get_block_by_position(x, y).fixed:
                    return False
        return True

绘制匹配规则,绘制拼图交换效果:


'''检查有无拼图块被选中'''

    def check_block_selected(self, position):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if self.get_block_by_position(x, y).rect.collidepoint(*position):
                    return [x, y]
        return None

    '''是否有连续一样的三个块(无--返回0/水平--返回1/竖直--返回2)'''

    def is_block_matched(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if x + 2 < NUMGRID:
                    if self.get_block_by_position(x, y).type == self.get_block_by_position(x + 1, y).type == self.get_block_by_position(x + 2,
                                                                                                          y).type:
                        return [1, x, y]
                if y + 2 < NUMGRID:
                    if self.get_block_by_position(x, y).type == self.get_block_by_position(x, y + 1).type == self.get_block_by_position(x,
                                                                                                          y + 2).type:
                        return [2, x, y]
        return [0, x, y]

    '''根据坐标获取对应位置的拼图对象'''

    def get_block_by_position(self, x, y):
        return self.all_blocks[x][y]

    '''交换拼图'''

    def swap_block(self, block1_pos, block2_pos):
        margin = block1_pos[0] - block2_pos[0] + block1_pos[1] - block2_pos[1]
        if abs(margin) != 1:
            return False
        block1 = self.get_block_by_position(*block1_pos)
        block2 = self.get_block_by_position(*block2_pos)
        if block1_pos[0] - block2_pos[0] == 1:
            block1.direction = 'left'
            block2.direction = 'right'
        elif block1_pos[0] - block2_pos[0] == -1:
            block2.direction = 'left'
            block1.direction = 'right'
        elif block1_pos[1] - block2_pos[1] == 1:
            block1.direction = 'up'
            block2.direction = 'down'
        elif block1_pos[1] - block2_pos[1] == -1:
            block2.direction = 'up'
            block1.direction = 'down'
        block1.target_x = block2.rect.left
        block1.target_y = block2.rect.top
        block1.fixed = False
        block2.target_x = block1.rect.left
        block2.target_y = block1.rect.top
        block2.fixed = False
        self.all_blocks[block2_pos[0]][block2_pos[1]] = block1
        self.all_blocks[block1_pos[0]][block1_pos[1]] = block2
        return True

准备工作差不多了,开始主程序吧:

def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption('开心消消乐')
    # 加载背景音乐
    pygame.mixer.init()
    pygame.mixer.music.load(os.path.join(ROOTDIR, "resources/audios/bg.mp3"))
    pygame.mixer.music.set_volume(0.6)
    pygame.mixer.music.play(-1)
    # 加载音效
    sounds = {}
    sounds['mismatch'] = pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/badswap.wav'))
    sounds['match'] = []
    for i in range(6):
        sounds['match'].append(pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/match%s.wav' % i)))
    # 加载字体
    font = pygame.font.Font(os.path.join(ROOTDIR, 'resources/font.TTF'), 25)
    # 图片加载
    block_images = []
    for i in range(1, 8):
        block_images.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))
    # 主循环
    game = InitGame(screen, sounds, font, block_images)
    while True:
        score = game.start()
        flag = False
        # 一轮游戏结束后玩家选择重玩或者退出
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYUP and event.key == pygame.K_r:
                    flag = True
            if flag:
                break
            screen.fill((135, 206, 235))
            text0 = 'Final score: %s' % score
            text1 = 'Press <R> to restart the game.'
            text2 = 'Press <Esc> to quit the game.'
            y = 150
            for idx, text in enumerate([text0, text1, text2]):
                text_render = font.render(text, 1, (85, 65, 0))
                rect = text_render.get_rect()
                if idx == 0:
                    rect.left, rect.top = (212, y)
                elif idx == 1:
                    rect.left, rect.top = (122.5, y)
                else:
                    rect.left, rect.top = (126.5, y)
                y += 100
                screen.blit(text_render, rect)
            pygame.display.update()
        game.reset()


'''test'''
if __name__ == '__main__':
    main()

运行main.py就可以开始游戏了,看看效果吧!

玩了一下,还可以,可能是电脑原因,初始化的时候存在卡顿的情况,后续会优化一下,初始化8个,64大小的方块是最佳情况,大家可以尝试改下配置文件就好了。后续会退出各个小游戏的进阶版,欢迎大家关注,及时获取最新内容。

需要游戏素材,和完整代码,点**开心消消乐**获取。

今天的分享就到这里,希望感兴趣的同学关注我,每天都有新内容,不限题材,不限内容,你有想要分享的内容,也可以私聊我!

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1789154.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Kotlin中的StateFlow和SharedFlow有什么区别?

本文首发于公众号“AntDream”&#xff0c;欢迎微信搜索“AntDream”或扫描文章底部二维码关注&#xff0c;和我一起每天进步一点点 在Kotlin的协程库kotlinx.coroutines中&#xff0c;StateFlow和SharedFlow是两种用于处理事件流的API&#xff0c;它们有相似之处&#xff0c;但…

MySQL中获取时间的方法

大家好&#xff0c;在MySQL数据库开发中&#xff0c;获取时间是一个常见的需求。MySQL提供了多种方法来获取当前日期、时间和时间戳&#xff0c;并且可以对时间进行格式化、计算和转换。 以下是一些常用的MySQL时间函数及其示例&#xff1a; 1、NOW()&#xff1a;用于获取当前…

GPT-4与GPT-4O的区别详解:面向小白用户

1. 模型介绍 在人工智能的语言模型领域&#xff0c;OpenAI的GPT-4和GPT-4O是最新的成员。这两个模型虽然来源于相同的基础技术&#xff0c;但在功能和应用上有着明显的区别。 GPT-4&#xff1a;这是一个通用型语言模型&#xff0c;可以理解和生成自然语言。无论是写作、对话还…

MySQL 关键特性一:插入缓冲、双写缓冲

前言 ​ 本文主要介绍 mysql 的几大特性之几&#xff0c;如&#xff1a;双写缓冲和插入缓存。 双写缓冲 基本概念 ​ 双写缓冲&#xff08;doublewrite buffer&#xff09;是MySQL/InnoDB中用于支持原子页面更新的一种机制。在传统的数据库系统中&#xff0c;为了保证数据的…

小米商城格式化检测点

小米商城格式化检测点&#xff1a; var a function () {var x !0;return function (a, t) {var e x ? function () {if (t) {var x t.apply(a, arguments);t null;return x;}} : function () {};x !1;return e;};}();var t {};function e(n) {var r a(this, function…

数据持久化第七课-URL重写与Ajax

数据持久化第七课-URL重写与Ajax 一.预习笔记 1.URL重写(对网页地址进行保护) 首先编写module,实现对网络地址的处理 其次就是module的配置 最后验证url重写技术 2.Ajax数据交互 编写后端响应数据 处理跨域的配置问题 运行项目得到后端响应数据的地址 编写前端ajax进行数据请…

珈和科技携手浙江省气候中心,打造农业气象数字化服务新标杆!

古谚有云&#xff1a;春耕夏种秋收冬藏&#xff0c;皆在天时。可天有不测风云&#xff0c;农有“旦夕祸福”。寒潮、干旱、洪涝等气象灾害频繁发生&#xff0c;给农业生产带来了巨大挑战。 气候变化直接影响着农业生产&#xff0c;数字化时代&#xff0c;如何依靠科技手段降低…

解决 clickhouse jdbc 偶现 failed to respond 问题

背景 Clickhouse集群版本为 Github Clickhouse 22.3.5.5&#xff0c; clickhouse-jdbc 版本为 0.2.4。 问题表现 随着业务需求的扩展&#xff0c;基于Clickhouse 需要支持更多任务在期望的时效内完成&#xff0c;于是将业务系统和Clickhouse交互的部分都提交给可动态调整核心…

【面试笔记】单片机软件工程师,工业控制方向(储能)

文章目录 1. 基础知识1.1 C语言笔试题1.1.1 用宏定义得到一个数组所含的元素个数1.1.2 定义函数指针从程序固定地址(0)开始执行1.1.3 volatile的含义及作用1.1.4 32位系统&#xff0c;整数7和-7&#xff0c;分别以大端和小端存储&#xff0c;请示意说明 1.2 嵌入式基础1.2.1 简…

知识图谱应用---智慧金融

文章目录 智慧金融典型应用 智慧金融 智慧金融作为一个有机整体&#xff0c;知识图谱提供了金融领域知识提取、融合、分析、推断、决策等功能&#xff0c;如下图所示。在场景方面&#xff0c;智慧金融涵盖智慧支付、智慧财富管理、智慧银行、智慧证券、智慧保险、智慧风控等诸多…

【教程】使用 Tailchat 搭建团队内部聊天平台,Slack 的下一个替代品!

前言 多人协作&#xff0c;私有聊天一直是团队协作的关键点&#xff0c;现在有很多专注于团队协作的应用和平台&#xff0c;比如飞书、企业微信和Slack等。这期教程将带你手把手的搭建一个在线的团队协作向聊天室&#xff0c;希望对你有所帮助! 本期聊天室使用TailChat作为服务…

Rust 第三方库创建和导入(cargo --lib)

前言 日常开发过程中&#xff0c;难免会有一些工具方法&#xff0c;多个项目之间可能会重复使用。 所以将这些方法集成到一个第三方包中方便后期维护和管理&#xff0c; 比如工具函数如果需要修改&#xff0c;多个项目可能每个都需要改代码&#xff0c; 抽离到单独的包中只需要…

esp32-c6所有配套教程

1.介绍 本文是esp32-c6所有资料的介绍 如果需要详细代码的话请访问下面这个链接 esp32-c6使用教程wifi&#xff08;espidf修改成arduino&#xff09;附带代码websocket&#xff0c;舵机&#xff0c;点灯【2024年】-CSDN博客 配置环境 视频教程 0-2设置开发环境_哔哩哔哩_bi…

【python】成功解决“ImportError: cannot import name ‘triu’ from ‘scipy.linalg’”错误的全面指南

成功解决“ImportError: cannot import name ‘triu’ from ‘scipy.linalg’”错误的全面指南 在Python编程中&#xff0c;尤其是在使用scipy这个科学计算库时&#xff0c;可能会遇到ImportError错误&#xff0c;提示无法从scipy.linalg模块中导入名为triu的函数。这个错误通…

Linux入门教程笔记(一文带你了解Linux并精通)

文章目录 一、Linux概述二、Linux目录结构&#xff08;重点&#xff09;2.1 Linux文件系统的类型2.2 Linux文件系统的结构2.3 具体的目录结构2.3.1 Linux 根目录2.3.2 Linux /usr目录2.3.3 Linux /var 目录2.3.4 tar包存放目录:crossed_swords: 三、vi和vim编辑器四、Lnux开机&…

SpringMVC接收数据

SpringMVC接收数据 SpringMVC处理请求流程 SpringMVC涉及组件理解&#xff1a; DispatcherServlet : SpringMVC提供&#xff0c;我们需要使用web.xml配置使其生效&#xff0c;它是整个流程处理的核心&#xff0c;所有请求都经过它的处理和分发&#xff01;[ CEO ]HandlerMappi…

16个常用的思维模型

01.机会成本 02.沉没成本 03.直觉思维 04.决策树 05.非SR模型 06.确认性偏差 07.易得性偏差 08.逆向思维 09.六顶思考帽 10.101010旁观思维 11.升级思维 11.笛卡尔模型 13.第一性原理 14.奥卡姆剃刀理论 15.马斯洛需求层次理论 16.反脆弱思维 来源&#xff1a;16个常用的思维模…

基于最大重叠离散小波变换的PPG信号降噪(MATLAB 2018)

光电容积脉搏波PPG信号结合相关算法可以用于人体生理参数检测&#xff0c;如血压、血氧饱和度等&#xff0c;但采集过程中极易受到噪声干扰&#xff0c;对于血压、血氧饱和度测量的准确性造成影响。随着当今社会医疗保健技术的发展&#xff0c;可穿戴监测设备对于PPG信号的质量…

WSDM 2023 推荐系统相关论文整理(三)

WSDM 2023的论文录用结果已出&#xff0c;推荐系统相关的论文方向包含序列推荐&#xff0c;点击率估计等领域&#xff0c;涵盖图学习&#xff0c;对比学习&#xff0c;因果推断&#xff0c;知识蒸馏等技术&#xff0c;累计包含近四十篇论文&#xff0c;下文列举了部分论文的标题…

Source Insight 4.0安装和使用

文章目录 一、前言二、新建工程2.1 新建工程2.2 同步工程 3 Source Insight怎么生成函数调用关系图&#xff1f;3.1 打开关系窗口3.2 打开关系函数3.3 修改关系属性3.4设置 Relation Window Options3.5 设置Levels3.6 修改显示模式 4 下载地址 一、前言 Source Insight 4.0 是每…