Python开心消消乐源代码
Python开心消消乐小游戏源代码,源代码由三个py文件和一个资源包组成,cfg.py为配置文件,配置打开游戏屏幕大小等,game.py拼图精灵类:首先通过配置文件中,获取方块精灵的路径,加载到游戏里。定义move()移动模块的函数,这个移动比较简单。模块之间,只有相邻的可以相互移动,xxls.py在主程序中,通过读取配置文件,引入项目资源:包括图片、音频等,并从我们的modules里引入所有我们的模块。完整程序代码及资源包请往Python代码大全公众号下载:
cfg.py
'''主配置文件'''
import os'''屏幕设置大小'''
SCREENSIZE = (700, 700)
'''元素尺寸'''
NUMGRID = 8
GRIDSIZE = 64
XMARGIN = (SCREENSIZE[0] - GRIDSIZE * NUMGRID) // 2
YMARGIN = (SCREENSIZE[1] - GRIDSIZE * NUMGRID) // 2
'''获取根目录'''
ROOTDIR = os.getcwd()
'''FPS'''
FPS = 30
xxls.py
'''
Function:消消乐
'''
import os
import sys
import cfg
import pygame
from XiaoXiaoLe import *
from XiaoXiaoLe.game import pacerGame'''主程序'''def main(game=None):pygame.init()screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('开心消消乐-Python代码大全')# 加载背景音乐pygame.mixer.init()pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "res/audios/bg.mp3"))pygame.mixer.music.set_volume(0.6)pygame.mixer.music.play(-1)# 加载音效sounds = {}sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'res/audios/badswap.wav'))sounds['match'] = []for i in range(6):sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'res/audios/match%s.wav' % i)))# 字体显示font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'res/font/font.TTF'), 25)# 星星pacer_imgs = []for i in range(1, 8):pacer_imgs.append(os.path.join(cfg.ROOTDIR, 'res/imgs/pacer%s.png' % i))# 循环game = pacerGame(screen, sounds, font, pacer_imgs, cfg)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 = Trueif flag:breakscreen.fill((136, 207, 236))text0 = 'Final score: %s' % scoretext1 = 'Press <R> to restart the game.'text2 = 'Press <Esc> to quit the game.'y = 150for 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 = (223, y)elif idx == 1:rect.left, rect.top = (133.5, y)else:rect.left, rect.top = (126.5, y)y += 99screen.blit(text_render, rect)pygame.display.update()game.reset()'''游戏运行'''
if __name__ == '__main__':main()
game.py
'''
Function:主游戏
'''
import sys
import time
import random
import pygame'''拼图精灵类'''class pacerSprite(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 = positionself.downlen = downlenself.target_x = position[0]self.target_y = position[1] + downlenself.type = img_path.split('/')[-1].split('.')[0]self.fixed = Falseself.speed_x = 9self.speed_y = 9self.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 getPosition(self):return self.rect.left, self.rect.top'''设置星星坐标'''def setPosition(self, position):self.rect.left, self.rect.top = position
'''主游戏类'''
class pacerGame():def __init__(self, screen, sounds, font, pacer_imgs, cfg, **kwargs):self.info = 'pacer'self.screen = screenself.sounds = soundsself.font = fontself.pacer_imgs = pacer_imgsself.cfg = cfgself.reset()'''开始游戏'''def start(self):clock = pygame.time.Clock()# 遍历整个游戏界面更新位置overall_moving = True# 指定某些对象个体更新位置individual_moving = False# 定义一些必要的变量pacer_selected_xy = Nonepacer_selected_xy2 = Noneswap_again = Falseadd_score = 0add_score_showtimes = 10time_pre = int(time.time())# 游戏主循环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.MOUSEBUTTONUP:if (not overall_moving) and (not individual_moving) and (not add_score):position = pygame.mouse.get_pos()if pacer_selected_xy is None:pacer_selected_xy = self.checkSelected(position)else:pacer_selected_xy2 = self.checkSelected(position)if pacer_selected_xy2:if self.swappacer(pacer_selected_xy, pacer_selected_xy2):individual_moving = Trueswap_again = Falseelse:pacer_selected_xy = Noneif overall_moving:overall_moving = not self.droppacers(0, 0)# 移动一次可能可以拼出多个3连块if not overall_moving:res_match = self.isMatch()add_score = self.removeMatched(res_match)if add_score > 0:overall_moving = Trueif individual_moving:pacer1 = self.getpacerByPos(*pacer_selected_xy)pacer2 = self.getpacerByPos(*pacer_selected_xy2)pacer1.move()pacer2.move()if pacer1.fixed and pacer2.fixed:res_match = self.isMatch()if res_match[0] == 0 and not swap_again:swap_again = Trueself.swappacer(pacer_selected_xy, pacer_selected_xy2)self.sounds['mismatch'].play()else:add_score = self.removeMatched(res_match)overall_moving = Trueindividual_moving = Falsepacer_selected_xy = Nonepacer_selected_xy2 = Noneself.screen.fill((135, 206, 235))self.drawGrids()self.pacers_group.draw(self.screen)if pacer_selected_xy:self.drawBlock(self.getpacerByPos(*pacer_selected_xy).rect)if add_score:if add_score_showtimes == 10:random.choice(self.sounds['match']).play()self.drawAddScore(add_score)add_score_showtimes -= 1if add_score_showtimes < 1:add_score_showtimes = 10add_score = 0self.remaining_time -= (int(time.time()) - time_pre)time_pre = int(time.time())self.showRemainingTime()self.drawScore()if self.remaining_time <= 0:return self.scorepygame.display.update()clock.tick(self.cfg.FPS)'''初始化'''def reset(self):# 随机生成各个块(即初始化游戏地图各个元素)while True:self.all_pacers = []self.pacers_group = pygame.sprite.Group()for x in range(self.cfg.NUMGRID):self.all_pacers.append([])for y in range(self.cfg.NUMGRID):pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+x*self.cfg.GRIDSIZE, self.cfg.YMARGIN+y*self.cfg.GRIDSIZE-self.cfg.NUMGRID*self.cfg.GRIDSIZE], downlen=self.cfg.NUMGRID*self.cfg.GRIDSIZE)self.all_pacers[x].append(pacer)self.pacers_group.add(pacer)if self.isMatch()[0] == 0:break# 得分self.score = 0# 拼出一个的奖励self.reward = 10# 时间self.remaining_time = 300'''显示剩余时间'''def showRemainingTime(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 = (self.cfg.SCREENSIZE[0]-201, 6)self.screen.blit(remaining_time_render, rect)'''显示得分'''def drawScore(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 drawAddScore(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 generateNewpacers(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]:pacer = self.getpacerByPos(*[each, start])if start == res_match[2]:self.pacers_group.remove(pacer)self.all_pacers[each][start] = Noneelif start >= 0:pacer.target_y += self.cfg.GRIDSIZEpacer.fixed = Falsepacer.direction = 'down'self.all_pacers[each][start+1] = pacerelse:pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+each*self.cfg.GRIDSIZE, self.cfg.YMARGIN-self.cfg.GRIDSIZE], downlen=self.cfg.GRIDSIZE)self.pacers_group.add(pacer)self.all_pacers[each][start+1] = pacerstart -= 1elif res_match[0] == 2:start = res_match[2]while start > -4:if start == res_match[2]:for each in range(0, 3):pacer = self.getpacerByPos(*[res_match[1], start+each])self.pacers_group.remove(pacer)self.all_pacers[res_match[1]][start+each] = Noneelif start >= 0:pacer = self.getpacerByPos(*[res_match[1], start])pacer.target_y += self.cfg.GRIDSIZE * 3pacer.fixed = Falsepacer.direction = 'down'self.all_pacers[res_match[1]][start+3] = pacerelse:pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+res_match[1]*self.cfg.GRIDSIZE, self.cfg.YMARGIN+start*self.cfg.GRIDSIZE], downlen=self.cfg.GRIDSIZE*3)self.pacers_group.add(pacer)self.all_pacers[res_match[1]][start+3] = pacerstart -= 1'''移除匹配的pacer'''def removeMatched(self, res_match):if res_match[0] > 0:self.generateNewpacers(res_match)self.score += self.rewardreturn self.rewardreturn 0'''游戏界面的网格绘制'''def drawGrids(self):for x in range(self.cfg.NUMGRID):for y in range(self.cfg.NUMGRID):rect = pygame.Rect((self.cfg.XMARGIN+x*self.cfg.GRIDSIZE, self.cfg.YMARGIN+y*self.cfg.GRIDSIZE, self.cfg.GRIDSIZE, self.cfg.GRIDSIZE))self.drawBlock(rect, color=(0, 0, 255), size=1)'''画矩形block框'''def drawBlock(self, block, color=(255, 0, 255), size=4):pygame.draw.rect(self.screen, color, block, size)'''下落特效'''def droppacers(self, x, y):if not self.getpacerByPos(x, y).fixed:self.getpacerByPos(x, y).move()if x < self.cfg.NUMGRID - 1:x += 1return self.droppacers(x, y)elif y < self.cfg.NUMGRID - 1:x = 0y += 1return self.droppacers(x, y)else:return self.isFull()'''是否每个位置都有拼图块了'''def isFull(self):for x in range(self.cfg.NUMGRID):for y in range(self.cfg.NUMGRID):if not self.getpacerByPos(x, y).fixed:return Falsereturn True'''检查有无拼图块被选中'''def checkSelected(self, position):for x in range(self.cfg.NUMGRID):for y in range(self.cfg.NUMGRID):if self.getpacerByPos(x, y).rect.collidepoint(*position):return [x, y]return None'''是否有连续一样的三个块(无--返回0/水平--返回1/竖直--返回2)'''def isMatch(self):for x in range(self.cfg.NUMGRID):for y in range(self.cfg.NUMGRID):if x + 2 < self.cfg.NUMGRID:if self.getpacerByPos(x, y).type == self.getpacerByPos(x+1, y).type == self.getpacerByPos(x+2, y).type:return [1, x, y]if y + 2 < self.cfg.NUMGRID:if self.getpacerByPos(x, y).type == self.getpacerByPos(x, y+1).type == self.getpacerByPos(x, y+2).type:return [2, x, y]return [0, x, y]'''根据坐标获取对应位置的拼图对象'''def getpacerByPos(self, x, y):return self.all_pacers[x][y]'''交换拼图'''def swappacer(self, pacer1_pos, pacer2_pos):margin = pacer1_pos[0] - pacer2_pos[0] + pacer1_pos[1] - pacer2_pos[1]if abs(margin) != 1:return Falsepacer1 = self.getpacerByPos(*pacer1_pos)pacer2 = self.getpacerByPos(*pacer2_pos)if pacer1_pos[0] - pacer2_pos[0] == 1:pacer1.direction = 'left'pacer2.direction = 'right'elif pacer1_pos[0] - pacer2_pos[0] == -1:pacer2.direction = 'left'pacer1.direction = 'right'elif pacer1_pos[1] - pacer2_pos[1] == 1:pacer1.direction = 'up'pacer2.direction = 'down'elif pacer1_pos[1] - pacer2_pos[1] == -1:pacer2.direction = 'up'pacer1.direction = 'down'pacer1.target_x = pacer2.rect.leftpacer1.target_y = pacer2.rect.toppacer1.fixed = Falsepacer2.target_x = pacer1.rect.leftpacer2.target_y = pacer1.rect.toppacer2.fixed = Falseself.all_pacers[pacer2_pos[0]][pacer2_pos[1]] = pacer1self.all_pacers[pacer1_pos[0]][pacer1_pos[1]] = pacer2return True'''信息显示'''def __repr__(self):return self.info
完整程序及资源包下载地址:https://pan.baidu.com/s/1dhSNWYXwV7FHknIszJmsgA,下载提供码关注:Python代码大全,回复:消消乐提取码。
更多Python源代码,请微信关注:Python代码大全
Python开心消消乐源代码相关推荐
- python编程游戏手机版_利用Python开发手机同款游戏:开心消消乐
手机上面的开心消消乐,我想大部分人都是玩过的吧,今天小编就教大家如何用python开发这款游戏 不过只有十个关卡,不像手机里面那么多的关卡!不过游戏的画面和bgm都是同款的哦~ 效果图 基本配置 wi ...
- 用Python写个开心消消乐小游戏!自己写的游戏就是好玩!
提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Python 来做个简单的消消乐小游戏. 实现 消消乐的构成主要包括 ...
- 用Python 写个 开心消消乐小游戏
源码在python学习交流q群:733089476 获取 提到开心消消乐这款小游戏,相信大家都不陌生,它曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Pytho ...
- python开心消消乐辅助_用Python写个开心消消乐小游戏
提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Python 来做个简单的消消乐小游戏. 实现 消消乐的构成主要包括 ...
- 【python学习】Python开心消消乐实现过程基础1
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Python开心消消乐实现过程基础1 前言 一.Block类 二.MagicBlock类 三.Tool类 前言 前几天,用Python ...
- 【附源码】Python小游戏 ——开心消消乐
目录 前言 开发工具 环境搭建 效果展示 选择关卡首页 游戏界面 过关 代码展示 模块导入 主函数 声音类 树类 元素类 数组类 前言 今天主要是给大家拿牌一个小游戏,开心消消乐 看看有没有小伙伴能够 ...
- 【小游戏合集】之用Python自己开发一个闯关小游戏——开心消消乐
导语: 今天这期小游戏是最适合小伙伴们一同挑战的精美手游,其因画面精美.上手简单.休闲有趣.有惊喜有挑战而获得广大玩家的喜爱...这款小游戏没错就是开心消消乐,相信大家都不陌生,其曾在 2015 年获 ...
- python实现消消乐游戏_用Python写个开心消消乐小游戏
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受 ...
- 【Python游戏】Python各大游戏合集(2):开心消消乐、坦克大战、Q版泡泡堂、愤怒的小鸟、拼图 | 附带源码
相关文件 关注小编,私信小编领取哟! 当然别忘了一件三连哟~~ 公众号:Python日志 可以关注小编公众号,会不定时的发布一下Python小技巧,还有很多资源可以免费领取哟!! 源码领取:加Pyth ...
- 利用Python开发手机同款游戏:开心消消乐
手机上面的开心消消乐,我想大部分人都是玩过的吧,今天小编就教大家如何用Python开发这款游戏 不过只有十个关卡,不像手机里面那么多的关卡!不过游戏的画面和BGM都是同款的哦~ 效果图 基本配置 Wi ...
最新文章
- linux-Tcp IP协议栈源码阅读笔记
- NYOJ 23 取石子(一)
- ansible基础-Jinja2模版 | 过滤器
- C语言编程笔记:关于 for循环 的那些不为人知的秘密
- sql查询结果字段名与字段值倒过来了
- 15_传智播客iOS视频教程_OC语言完全兼容C语言
- java初始块,java初始代码块
- python三级联动菜单_2分钟制作智能式联动下拉菜单,轻松搞定重复内容,录入不出错...
- android 崩溃,android 9出现崩溃
- c语言实现语音检测vad_AI大语音(二)——语音预处理
- linux下获取程序所在目录绝对路径
- centos-rpm
- 游戏服务器当中的唯一名设计方法
- 信息学奥赛一本通:1097:画矩形
- c语言pow的作用,c语言中pow函数的用法是什么?
- 2020年中国知识产权服务从业人员数、营业收入及发展前景分析[图]
- 实训日志(十)——达芬奇调色
- input值不可变、隐藏input(表单隐藏域)
- 使用scale缩放字体
- 解决方案|在线自习室
热门文章
- 极光im支持android手机系统,极光IM- JMessage 产品简介 - 极光文档
- 我们计划招收300名深度学习者,免费攻读傅里叶变换和MATLAB
- 掘金小册大众评审团流程
- 发那科机器人编程软件fanuc roboguide授权补丁_工业机器人离线编程与应用:ROBOGUIDE V8.3版本的工程文件创建...
- 发那科机器人点位编辑_发那科机器人指令编辑大全
- 最新app源码下载:200款优秀Android项目源码
- monkey命令常用参数与monkey事件百分比
- 黑客入侵WinXP常用七个技巧
- SoapUI接口测试实例(webservice接口)
- 开上帝视角,其实你也能