环境搭建博客链接
一起来学pygame吧 游戏开发30例(开篇词)——环境搭建+游戏效果展示
windows系统,python3.6+ pip21+
安装游戏依赖模块 pip install pygame
消消乐应该大家都玩过,或者看过。这个实现起来 相对比较简单。主要要求:设计多种小图形,每次打开 各种图形随机分配成一张图。
通过鼠标点击 来移动相邻的两个图形,如果产生三个或更多的相同图形相邻,则自动消除。消除之后,随机填充。
首先,先整理一下项目的主结构,其实看一下主结构,基本就清晰了
modules:存放自己写的python类 ——game.py:主模块目录 resources:存放引用到的图片、音频等等 ——audios:音频资源 ——images:图片资源 ——fonts:字体 cfg.py:为主配置文件 xxl.py:主程序文件 requirements.txt:需要引入的python依赖包
cfg.py
配置文件中,需要引入os模块,并且配置打开游戏的屏幕大小。
'''配置文件''' import os '''屏幕大小''' SCREENSIZE = (600, 600) '''游戏元素尺寸''' NUMGRID = 8 GRIDSIZE = 64 XMARGIN = (SCREENSIZE[0] - GRIDSIZE * NUMGRID) // 2 YMARGIN = (SCREENSIZE[1] - GRIDSIZE * NUMGRID) // 2 '''根目录''' ROOTDIR = os.getcwd() '''FPS''' FPS = 30
game.py:第一部分
把整个项目放在一整个game.py模块下了,把这个代码文件拆开解读一下。
拼图精灵类:首先通过配置文件中,获取方块精灵的路径,加载到游戏里。
定义move()移动模块的函数,这个移动比较简单。模块之间,只有相邻的可以相互移动。
''' Function: 定义游戏 Author: Lex 微信公众号: hacklex ''' import sys import time import random import pygame '''拼图精灵类''' class gemSprite(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.downlen = 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 getPosition(self): return self.rect.left, self.rect.top '''设置坐标''' def setPosition(self, position): self.rect.left, self.rect.top = position
game.py 第二部分
详细注释,都写在代码里了。大家一定要看一遍,不要跑起来,就不管了哦
'''游戏类''' class gemGame(): def __init__(self, screen, sounds, font, gem_imgs, cfg, **kwargs): self.info = 'Gemgem —— hacklex' self.screen = screen self.sounds = sounds self.font = font self.gem_imgs = gem_imgs self.cfg = cfg self.reset() '''开始游戏''' def start(self): clock = pygame.time.Clock() # 遍历整个游戏界面更新位置 overall_moving = True # 指定某些对象个体更新位置 individual_moving = False # 定义一些必要的变量 gem_selected_xy = None gem_selected_xy2 = None swap_again = False add_score = 0 add_score_showtimes = 10 time_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 gem_selected_xy is None: gem_selected_xy = self.checkSelected(position) else: gem_selected_xy2 = self.checkSelected(position) if gem_selected_xy2: if self.swapGem(gem_selected_xy, gem_selected_xy2): individual_moving = True swap_again = False else: gem_selected_xy = None if overall_moving: overall_moving = not self.dropGems(0, 0) # 移动一次可能可以拼出多个3连块 if not overall_moving: res_match = self.isMatch() add_score = self.removeMatched(res_match) if add_score > 0: overall_moving = True if individual_moving: gem1 = self.getGemByPos(*gem_selected_xy) gem2 = self.getGemByPos(*gem_selected_xy2) gem1.move() gem2.move() if gem1.fixed and gem2.fixed: res_match = self.isMatch() if res_match[0] == 0 and not swap_again: swap_again = True self.swapGem(gem_selected_xy, gem_selected_xy2) self.sounds['mismatch'].play() else: add_score = self.removeMatched(res_match) overall_moving = True individual_moving = False gem_selected_xy = None gem_selected_xy2 = None self.screen.fill((135, 206, 235)) self.drawGrids() self.gems_group.draw(self.screen) if gem_selected_xy: self.drawBlock(self.getGemByPos(*gem_selected_xy).rect) if add_score: if add_score_showtimes == 10: random.choice(self.sounds['match']).play() self.drawAddScore(add_score) add_score_showtimes -= 1 if add_score_showtimes < 1: add_score_showtimes = 10 add_score = 0 self.remaining_time -= (int(time.time()) - time_pre) time_pre = int(time.time()) self.showRemainingTime() self.drawScore() if self.remaining_time <= 0: return self.score pygame.display.update() clock.tick(self.cfg.FPS) '''初始化''' def reset(self): # 随机生成各个块(即初始化游戏地图各个元素) while True: self.all_gems = [] self.gems_group = pygame.sprite.Group() for x in range(self.cfg.NUMGRID): self.all_gems.append([]) for y in range(self.cfg.NUMGRID): gem = gemSprite(img_path=random.choice(self.gem_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_gems[x].append(gem) self.gems_group.add(gem) 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 generateNewGems(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]: gem = self.getGemByPos(*[each, start]) if start == res_match[2]: self.gems_group.remove(gem) self.all_gems[each][start] = None elif start >= 0: gem.target_y += self.cfg.GRIDSIZE gem.fixed = False gem.direction = 'down' self.all_gems[each][start+1] = gem else: gem = gemSprite(img_path=random.choice(self.gem_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.gems_group.add(gem) self.all_gems[each][start+1] = gem 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): gem = self.getGemByPos(*[res_match[1], start+each]) self.gems_group.remove(gem) self.all_gems[res_match[1]][start+each] = None elif start >= 0: gem = self.getGemByPos(*[res_match[1], start]) gem.target_y += self.cfg.GRIDSIZE * 3 gem.fixed = False gem.direction = 'down' self.all_gems[res_match[1]][start+3] = gem else: gem = gemSprite(img_path=random.choice(self.gem_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.gems_group.add(gem) self.all_gems[res_match[1]][start+3] = gem start -= 1 '''移除匹配的gem''' def removeMatched(self, res_match): if res_match[0] > 0: self.generateNewGems(res_match) self.score += self.reward return self.reward return 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 dropGems(self, x, y): if not self.getGemByPos(x, y).fixed: self.getGemByPos(x, y).move() if x < self.cfg.NUMGRID - 1: x += 1 return self.dropGems(x, y) elif y < self.cfg.NUMGRID - 1: x = 0 y += 1 return self.dropGems(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.getGemByPos(x, y).fixed: return False return True '''检查有无拼图块被选中''' def checkSelected(self, position): for x in range(self.cfg.NUMGRID): for y in range(self.cfg.NUMGRID): if self.getGemByPos(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.getGemByPos(x, y).type == self.getGemByPos(x+1, y).type == self.getGemByPos(x+2, y).type: return [1, x, y] if y + 2 < self.cfg.NUMGRID: if self.getGemByPos(x, y).type == self.getGemByPos(x, y+1).type == self.getGemByPos(x, y+2).type: return [2, x, y] return [0, x, y] '''根据坐标获取对应位置的拼图对象''' def getGemByPos(self, x, y): return self.all_gems[x][y] '''交换拼图''' def swapGem(self, gem1_pos, gem2_pos): margin = gem1_pos[0] - gem2_pos[0] + gem1_pos[1] - gem2_pos[1] if abs(margin) != 1: return False gem1 = self.getGemByPos(*gem1_pos) gem2 = self.getGemByPos(*gem2_pos) if gem1_pos[0] - gem2_pos[0] == 1: gem1.direction = 'left' gem2.direction = 'right' elif gem1_pos[0] - gem2_pos[0] == -1: gem2.direction = 'left' gem1.direction = 'right' elif gem1_pos[1] - gem2_pos[1] == 1: gem1.direction = 'up' gem2.direction = 'down' elif gem1_pos[1] - gem2_pos[1] == -1: gem2.direction = 'up' gem1.direction = 'down' gem1.target_x = gem2.rect.left gem1.target_y = gem2.rect.top gem1.fixed = False gem2.target_x = gem1.rect.left gem2.target_y = gem1.rect.top gem2.fixed = False self.all_gems[gem2_pos[0]][gem2_pos[1]] = gem1 self.all_gems[gem1_pos[0]][gem1_pos[1]] = gem2 return True '''info''' def __repr__(self): return self.info
包括游戏背景音频、图片和字体设计
resources
audios:加载游戏背景音乐
fonts:记分牌相关字体
images:这个是关键了哦。如果这个加载不了,我们的消消乐 就啥都没得了
xxl.py
在主程序中,通过读取配置文件,引入项目资源:包括图片、音频等,并从我们的modules里引入所有我们的模块。
''' Function: 消消乐小游戏 Author: Lex 微信公众号: hacklex ''' import os import sys import cfg import pygame from modules import * '''游戏主程序''' def main(): pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Gemgem —— hacklex') # 加载背景音乐 pygame.mixer.init() pygame.mixer.music.load(os.path.join(cfg.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(cfg.ROOTDIR, 'resources/audios/badswap.wav')) sounds['match'] = [] for i in range(6): sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i))) # 加载字体 font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25) # 图片加载 gem_imgs = [] for i in range(1, 8): gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i)) # 主循环 game = gemGame(screen, sounds, font, gem_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 = 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() '''run''' if __name__ == '__main__': main()
如果你配置了开发工具的环境VScode、sublimeText、notepad+、pycharm什么的,可以直接在工具中,运行游戏。
如果没配置,可以使用命令启动。
brutecrack工具[WIFIPR中文版]及wpa/wpa2字典
brutecrack工具[WIFIPR中文版]及wpa/wpa2字典_wifipr-其它文档类资源-CSDN下载
Kali字典文件/纯数字/电话号码/弱/常用/Wifi等各种类型字典【解压后共计60G+字典文件】
Kali字典文件/纯数字/电话号码/弱/常用/Wifi等各种类型字典【解压后共计60G+字典文件】_kali字典下载-系统安全文档类资源-CSDN下载
【kali常用工具】brutecrack工具[WIFIPR中文版]及wpa/wpa2字典
brutecrack工具[WIFIPR中文版]及wpa/wpa2字典_wifipr-其它文档类资源-CSDN下载
【kali常用工具】EWSA 5.1.282-破包工具
【kali常用工具】EWSA5.1.282-破包工具_linux跑包工具-管理软件文档类资源-CSDN下载
【kali常用工具】Realtek 8812AU KALI网卡驱动及安装教程
【kali常用工具】Realtek8812AUKALI网卡驱动及安装教程_kalirtl8812au-网络设备文档类资源-CSDN下载
【kali常用工具】无线信号搜索工具_kali更新
【kali常用工具】无线信号搜索工具_kali更新_kali更新-互联网文档类资源-CSDN下载
【kali常用工具】MAC地址修改工具 保护终端不暴露
【kali常用工具】MAC地址修改工具保护终端不暴露_mac修改工具下载-Linux文档类资源-CSDN下载
【kali常用工具】脚本管理工具 php和jsp页面 接收命令参数 在服务器端执行
脚本管理工具php和jsp页面接收命令参数在服务器端执行_搜索引擎语法lexsaints-网络安全文档类资源-CSDN下载
【kali常用工具】上网行为监控工具
上网行为工具_搜索引擎语法lexsaints-网络安全文档类资源-CSDN下载
【kali常用工具】抓包工具Charles Windows64位 免费版
抓包工具CharlesWindows64位免费版_charleswindows-网络监控文档类资源-CSDN下载
【kali常用工具】图印工具stamp.zip
图印工具stamp.zip_搜索引擎语法lexsaints-制造文档类资源-CSDN下载
【python实战】女友半夜加班发自拍 python男友用30行代码发现惊天秘密
【渗透案例】上班摸鱼误入陌生网址——结果被XSS劫持了
【渗透测试】python你TM太皮了——区区30行代码就能记录键盘的一举一动
【渗透实战】女神相册密码忘记了,我只用Python写了20行代码~~~
【渗透测试】密码暴力破解工具——九头蛇(hydra)使用详解及实战
【渗透学习】Web安全渗透详细教程+学习线路+详细笔记【全网最全+建议收藏】
【渗透案例】如何用ssh工具连接前台小姐姐的“小米手机”——雷总看了直呼内行!!!
【渗透测试】密暴力破解工具——九头蛇(hydra)使用详解及实战
一起来学pygame吧 游戏开发30例(二)——塔防游戏
一起来学pygame吧 游戏开发30例(三)——射击外星人小游戏
一起来学pygame吧 游戏开发30例(四)——俄罗斯方块小游戏
一起来学pygame吧 游戏开发30例(五)——消消乐 小游戏
一起来学pygame吧 游戏开发30例(六)——高山滑雪 小游戏
CSDN出的Python和Java的全栈知识图谱,太强了,推荐给大家!