怎么用Python编写一个宝石消消乐小游戏

发布时间:2022-01-06 14:31:05 作者:iii
来源:亿速云 阅读:153

本篇内容介绍了“怎么用Python编写一个宝石消消乐小游戏”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

开发工具

python版本:3.6.4

相关模块:

pygame;以及一些python自带的模块。

环境搭建

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

原理简介

游戏规则:

玩家通过鼠标交换相邻的拼图,若交换后水平/竖直方向存在连续三个相同的拼图,则这些拼图消失,玩家得分,同时生成新的拼图以补充消失的部分,否则,交换失败,玩家不得分。玩家需要在规定时间内获取尽可能高的得分。

实现过程:

首先加载一些必要的游戏素材:

加载背景音乐:

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)

图片加载:

gem_imgs = []
    for i in range(1, 8):
        gem_imgs.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))

接着我们就要设置一下游戏的主循环吧

主要循环:

game = gemGame(screen, sounds, font, gem_imgs)
    while True:
        score = game.start()
        flag = False

我给大家讲一下原理:

逻辑其实很简单,就是不断检测是否有鼠标点击事件发生,如果有,则判断鼠标点击时的位置是否在某拼图块的位置区域内,若在,则选中该拼图块,否则不选中。

当有第二块拼图块被选中时,则判断两个拼图块是否满足拼图交换的条件,若满足,则交换拼图块,并获得奖励,否则不交换并取消选这两个拼图块的选中状态。

最后肯定就是设置游戏的结束和退出啦:

游戏倒计时结束后,进入游戏结束界面,界面显示用户当前得分。同时,若用户键入R键则重新开始游戏,键入ESC键则退出游戏。

游戏结束后玩家选择重开或退出:源码如下

        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()

上面就是一步一步来讲代码思路理清楚的讲解啦 下面我把源码放到下面:

import os
import pygame
from utils import *
from config import *
 
 
'''游戏主程序'''
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption('Gemgem-Python交流群:932574150)
    # 加载背景音乐
    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)
    # 图片加载
    gem_imgs = []
    for i in range(1, 8):
        gem_imgs.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))
    # 主循环
    game = gemGame(screen, sounds, font, gem_imgs)
    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()

“怎么用Python编写一个宝石消消乐小游戏”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. C语言实现宾果消消乐
  2. PHP实现开心消消乐的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何进行基于Docker的可持续交付问题分析

下一篇:如何进行JSONP跨域请求原理的深入解析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》