Python开发一个滑雪小游戏
2021/7/9 14:36:01
本文主要是介绍Python开发一个滑雪小游戏,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
大家好,我是Lex 喜欢欺负超人那个Lex
擅长领域:Python开发一个小游戏
今日重点:一步步分析and越过亚马逊的反爬虫机制
不一会,游戏写好了
效果是这样的
一、如何搭建开发环境环境
一起来学pygame吧 游戏开发30例(开篇词)——环境搭建+游戏效果展示
windows系统,python3.6+ pip21+
安装游戏依赖模块 pip install pygame
二、完整开发流程
1、代码结构
首先,先整理一下项目的主结构,其实看一下主结构,基本就清晰了
modules:自己定义的模块 ——game.py:主程序 res:存放引用到的图片和音频等等 ——music: 音频 资源 ——imgs: 图片 资源 ——fonts: 字体 cfg.py:为主配置文件 skiing.py:主程序文件 requirements.txt:需要引入的python依赖包
2、详细配置
cfg.py
配置文件中,需要引入os模块,并且配置打开游戏的屏幕大小。将我们需要用到的图片、音频和字体文件全部引入到项目中。
'''配置文件''' import os '''FPS''' FPS = 40 '''游戏屏幕大小''' SCREENSIZE = (640, 640) '''图片路径''' SKIER_IMAGE_PATHS = [ os.path.join(os.getcwd(), 'res/imgs/game_forward.png'), os.path.join(os.getcwd(), 'res/imgs/game_right1.png'), os.path.join(os.getcwd(), 'res/imgs/game_right2.png'), os.path.join(os.getcwd(), 'res/imgs/game_left2.png'), os.path.join(os.getcwd(), 'res/imgs/game_left1.png'), os.path.join(os.getcwd(), 'res/imgs/game_fall.png') ] OBSTACLE_PATHS = { 'tree': os.path.join(os.getcwd(), 'res/imgs/tree.png'), 'flag': os.path.join(os.getcwd(), 'res/imgs/flag.png') } '''背景音乐路径''' BGMPATH = os.path.join(os.getcwd(), 'res/music/bgm.mp3') '''字体路径''' FONTPATH = os.path.join(os.getcwd(), 'res/font/FZSTK.TTF')
3、动画中引用到的图片
4、资源文件
包括游戏背景音频、图片和字体设计
res
music:游戏背景音乐
fonts:记分牌呀、显示呀的 相关字体
imgs:游戏动画里的静态图片,所谓动画都是图片
5、主程序
skiing.py
在主程序中,通过读取配置文件,引入项目资源:包括图片、音频等,并从我们的modules里引入所有我们的模块。
''' 类''' class lexGame(): def __init__(self, screen, sounds, font, lex_imgs, cfg, **kwargs): self.info = 'Gemlex —— hacklex' self.screen = screen self.sounds = sounds self.font = font self.lex_imgs = lex_imgs self.cfg = cfg self.reset() '''开始 ''' def start(self): clock = gamepy.time.Clock() # 遍历整个 界面更新位置 overall_moving = True # 指定某些对象个体更新位置 individual_moving = False # 定义一些必要的变量 lex_selected_xy = None lex_selected_xy2 = None swap_again = False add_score = 0 add_score_showtimes = 10 time_pre = int(time.time()) # 主循环 while True: for event in gamepy.event.get(): if event.type == gamepy.QUIT or (event.type == gamepy.KEYUP and event.key == gamepy.K_ESCAPE): gamepy.quit() sys.exit() elif event.type == gamepy.MOUSEBUTTONUP: if (not overall_moving) and (not individual_moving) and (not add_score): position = gamepy.mouse.get_pos() if lex_selected_xy is None: lex_selected_xy = self.checkSelected(position) else: lex_selected_xy2 = self.checkSelected(position) if lex_selected_xy2: if self.swapGem(lex_selected_xy, lex_selected_xy2): individual_moving = True swap_again = False else: lex_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: lex1 = self.getGemByPos(*lex_selected_xy) lex2 = self.getGemByPos(*lex_selected_xy2) lex1.move() lex2.move() if lex1.fixed and lex2.fixed: res_match = self.isMatch() if res_match[0] == 0 and not swap_again: swap_again = True self.swapGem(lex_selected_xy, lex_selected_xy2) self.sounds['mismatch'].play() else: add_score = self.removeMatched(res_match) overall_moving = True individual_moving = False lex_selected_xy = None lex_selected_xy2 = None self.screen.fill((154, 206, 235)) self.drawGrids() self.lexs_group.draw(self.screen) if lex_selected_xy: self.drawBlock(self.getGemByPos(*lex_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 gamepy.display.update() clock.tick(self.cfg.FPS) '''初始化''' def reset(self): # 随机生成各个块 while True: self.all_lexs = [] self.lexs_group = gamepy.sprite.Group() for x in range(self.cfg.NUMGRID): self.all_lexs.append([]) for y in range(self.cfg.NUMGRID): lex = lexSprite(img_path=random.choice(self.lex_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_lexs[x].append(lex) self.lexs_group.add(lex) 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, 99, 99)) 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]: lex = self.getGemByPos(*[each, start]) if start == res_match[2]: self.lexs_group.remove(lex) self.all_lexs[each][start] = None elif start >= 0: lex.target_y += self.cfg.GRIDSIZE lex.fixed = False lex.direction = 'down' self.all_lexs[each][start+1] = lex else: lex = lexSprite(img_path=random.choice(self.lex_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.lexs_group.add(lex) self.all_lexs[each][start+1] = lex 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): lex = self.getGemByPos(*[res_match[1], start+each]) self.lexs_group.remove(lex) self.all_lexs[res_match[1]][start+each] = None elif start >= 0: lex = self.getGemByPos(*[res_match[1], start]) lex.target_y += self.cfg.GRIDSIZE * 3 lex.fixed = False lex.direction = 'down' self.all_lexs[res_match[1]][start+3] = lex else: lex = lexSprite(img_path=random.choice(self.lex_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.lexs_group.add(lex) self.all_lexs[res_match[1]][start+3] = lex start -= 1 '''移除匹配的lex''' 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 = gamepy.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): gamepy.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_lexs[x][y] '''交换 ''' def swapGem(self, lex1_pos, lex2_pos): margin = lex1_pos[0] - lex2_pos[0] + lex1_pos[1] - lex2_pos[1] if abs(margin) != 1: return False lex1 = self.getGemByPos(*lex1_pos) lex2 = self.getGemByPos(*lex2_pos) if lex1_pos[0] - lex2_pos[0] == 1: lex1.direction = 'left' lex2.direction = 'right' elif lex1_pos[0] - lex2_pos[0] == -1: lex2.direction = 'left' lex1.direction = 'right' elif lex1_pos[1] - lex2_pos[1] == 1: lex1.direction = 'up' lex2.direction = 'down' elif lex1_pos[1] - lex2_pos[1] == -1: lex2.direction = 'up' lex1.direction = 'down' lex1.target_x = lex2.rect.left lex1.target_y = lex2.rect.top lex1.fixed = False lex2.target_x = lex1.rect.left lex2.target_y = lex1.rect.top lex2.fixed = False self.all_lexs[lex2_pos[0]][lex2_pos[1]] = lex1 self.all_lexs[lex1_pos[0]][lex1_pos[1]] = lex2 return True '''info''' def __repr__(self): return self.info
四、如何启动游戏
1、开发工具
如果你有配置了工具的环境VScode、sublimeText、notepad+、pycharm什么的,可以直接在工具中,运行游戏。
如果没配置,可以使用命令启动。
2、命令行
【两种方法获取完整源码】
1、资源下载:【pygame开发实战开发30例 完整源码】
一起来学pygame吧 游戏开发30例(二)——塔防游戏
一起来学pygame吧 游戏开发30例(四)——俄罗斯方块小游戏
推荐阅读
python实战
【python实战】前女友婚礼,python破解婚礼现场的WIFI,把名称改成了
【python实战】前女友发来加密的 “520快乐.pdf“,我用python破解开之后,却发现
【python实战】昨晚,我用python帮隔壁小姐姐P证件照 自拍,然后发现...
【python实战】女友半夜加班发自拍 python男友用30行代码发现惊天秘密
【python实战】python你TM太皮了——区区30行代码就能记录键盘的一举一动
【python实战】女神相册密码忘记了,我只用Python写了20行代码~~~
pygame系列文章【订阅专栏,获取完整源码】
一起来学pygame吧 游戏开发30例(二)——塔防游戏
一起来学pygame吧 游戏开发30例(四)——俄罗斯方块小游戏
***测试实战专栏
Windows AD/Exchange管理专栏
Linux高性能服务器搭建
PowerShell自动化专栏
这篇关于Python开发一个滑雪小游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-02Python编程基础
- 2024-11-01Python 基础教程
- 2024-11-01用Python探索可解与不可解方程的问题
- 2024-11-01Python编程入门指南
- 2024-11-01Python编程基础知识
- 2024-11-01Python编程基础
- 2024-10-31Python基础入门:理解变量与数据类型
- 2024-10-30Python股票自动化交易资料详解与实战指南
- 2024-10-30Python入行:新手必读的Python编程入门指南
- 2024-10-30Python入行:初学者必备的编程指南