Python实现过迷宫小游戏示例详解
程序员文章站
2022-06-17 08:24:28
目录前言开发工具环境搭建原理简介主要代码前言今天为大家带来解闷用的过迷宫小游戏分享给大家好了。让我们愉快地开始吧~开发工具python版本: 3.6.4相关模块:pygame模块;以及一些python...
前言
今天为大家带来解闷用的过迷宫小游戏分享给大家好了。让我们愉快地开始吧~
开发工具
python版本: 3.6.4
相关模块:
pygame模块;
以及一些python自带的模块。
环境搭建
安装python并添加到环境变量,pip安装需要的相关模块即可。
原理简介
游戏规则:
玩家通过↑↓←→键控制主角行动,使主角从出发点(左上角)绕出迷宫,到达终点(右下角)即为游戏胜利。
逐步实现:
首先,当然是创建迷宫啦,为了方便,这里采用随机生成迷宫的方式(人工设计真的费眼睛,弄到一半不想弄了,有兴趣的可以自行尝试。)。思路其实很简单,就是把游戏界面划分成多个cell,类似这样子:
然后设计算法遍历所有的cell,每个被遍历到的cell在某几个随机的方向上打开一堵墙(就是去掉分割cell的线条)就ok啦~
主要代码
'''随机生成迷宫类''' class randommaze(): def __init__(self, maze_size, block_size, border_size, **kwargs): self.block_size = block_size self.border_size = border_size self.maze_size = maze_size self.blocks_list = randommaze.createmaze(maze_size, block_size, border_size) self.font = pygame.font.sysfont('consolas', 15) '''画到屏幕上''' def draw(self, screen): for row in range(self.maze_size[0]): for col in range(self.maze_size[1]): self.blocks_list[row][col].draw(screen) # 起点和终点标志 showtext(screen, self.font, 's', (255, 0, 0), (self.border_size[0]-10, self.border_size[1])) showtext(screen, self.font, 'd', (255, 0, 0), (self.border_size[0]+(self.maze_size[1]-1)*self.block_size, self.border_size[1]+self.maze_size[0]*self.block_size+5)) '''创建迷宫''' @staticmethod def createmaze(maze_size, block_size, border_size): def nextblock(block_now, blocks_list): directions = ['top', 'bottom', 'left', 'right'] blocks_around = dict(zip(directions, [none]*4)) block_next = none count = 0 # 查看上边block if block_now.coordinate[1]-1 >= 0: block_now_top = blocks_list[block_now.coordinate[1]-1][block_now.coordinate[0]] if not block_now_top.is_visited: blocks_around['top'] = block_now_top count += 1 # 查看下边block if block_now.coordinate[1]+1 < maze_size[0]: block_now_bottom = blocks_list[block_now.coordinate[1]+1][block_now.coordinate[0]] if not block_now_bottom.is_visited: blocks_around['bottom'] = block_now_bottom count += 1 # 查看左边block if block_now.coordinate[0]-1 >= 0: block_now_left = blocks_list[block_now.coordinate[1]][block_now.coordinate[0]-1] if not block_now_left.is_visited: blocks_around['left'] = block_now_left count += 1 # 查看右边block if block_now.coordinate[0]+1 < maze_size[1]: block_now_right = blocks_list[block_now.coordinate[1]][block_now.coordinate[0]+1] if not block_now_right.is_visited: blocks_around['right'] = block_now_right count += 1 if count > 0: while true: direction = random.choice(directions) if blocks_around.get(direction): block_next = blocks_around.get(direction) if direction == 'top': block_next.has_walls[1] = false block_now.has_walls[0] = false elif direction == 'bottom': block_next.has_walls[0] = false block_now.has_walls[1] = false elif direction == 'left': block_next.has_walls[3] = false block_now.has_walls[2] = false elif direction == 'right': block_next.has_walls[2] = false block_now.has_walls[3] = false break return block_next blocks_list = [[block([col, row], block_size, border_size) for col in range(maze_size[1])] for row in range(maze_size[0])] block_now = blocks_list[0][0] records = [] while true: if block_now: if not block_now.is_visited: block_now.is_visited = true records.append(block_now) block_now = nextblock(block_now, blocks_list) else: block_now = records.pop() if len(records) == 0: break return blocks_list
接下来就是定义角色类啦,角色类需要根据用户的操作进行上下左右的移动,同时,保证移动是不能跨越墙的就ok了~具体而言,代码实现如下:
'''定义hero''' class hero(pygame.sprite.sprite): def __init__(self, imagepath, coordinate, block_size, border_size, **kwargs): pygame.sprite.sprite.__init__(self) self.image = pygame.image.load(imagepath) self.image = pygame.transform.scale(self.image, (block_size, block_size)) self.rect = self.image.get_rect() self.rect.left, self.rect.top = coordinate[0] * block_size + border_size[0], coordinate[1] * block_size + border_size[1] self.coordinate = coordinate self.block_size = block_size self.border_size = border_size '''移动''' def move(self, direction, maze): blocks_list = maze.blocks_list if direction == 'up': if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[0]: return false else: self.coordinate[1] = self.coordinate[1] - 1 return true elif direction == 'down': if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[1]: return false else: self.coordinate[1] = self.coordinate[1] + 1 return true elif direction == 'left': if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[2]: return false else: self.coordinate[0] = self.coordinate[0] - 1 return true elif direction == 'right': if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[3]: return false else: self.coordinate[0] = self.coordinate[0] + 1 return true else: raise valueerror('unsupport direction <%s> in hero.move...' % direction) '''绑定到屏幕''' def draw(self, screen): self.rect.left, self.rect.top = self.coordinate[0] * self.block_size + self.border_size[0], self.coordinate[1] * self.block_size + self.border_size[1] screen.blit(self.image, self.rect)
最后,就是写下游戏主循环,这个其实也很简单,只要每次载入一个随机生成的迷宫地图和实例化一个主角,然后不断进行按键检测,并根据按键检测的结果移动主角,最后根据行动结果更新界面数据就ok了~当然,若主角到达了终点,则进入关卡切换界面。
具体而言,代码实现如下:
'''主函数''' def main(cfg): # 初始化 pygame.init() pygame.mixer.init() pygame.font.init() pygame.mixer.music.load(cfg.bgmpath) pygame.mixer.music.play(-1, 0.0) screen = pygame.display.set_mode(cfg.screensize) pygame.display.set_caption('maze - 微信公众号: charles的皮卡丘') font = pygame.font.sysfont('consolas', 15) # 开始界面 interface(screen, cfg, 'game_start') # 记录关卡数 num_levels = 0 # 记录最少用了多少步通关 best_scores = 'none' # 关卡循环切换 while true: num_levels += 1 clock = pygame.time.clock() screen = pygame.display.set_mode(cfg.screensize) # --随机生成关卡地图 maze_now = randommaze(cfg.mazesize, cfg.blocksize, cfg.bordersize) # --生成hero hero_now = hero(cfg.heropicpath, [0, 0], cfg.blocksize, cfg.bordersize) # --统计步数 num_steps = 0 # --关卡内主循环 while true: dt = clock.tick(cfg.fps) screen.fill((255, 255, 255)) is_move = false # ----↑↓←→控制hero for event in pygame.event.get(): if event.type == pygame.quit: pygame.quit() sys.exit(-1) elif event.type == pygame.keydown: if event.key == pygame.k_up: is_move = hero_now.move('up', maze_now) elif event.key == pygame.k_down: is_move = hero_now.move('down', maze_now) elif event.key == pygame.k_left: is_move = hero_now.move('left', maze_now) elif event.key == pygame.k_right: is_move = hero_now.move('right', maze_now) num_steps += int(is_move) hero_now.draw(screen) maze_now.draw(screen) # ----显示一些信息 showtext(screen, font, 'leveldone: %d' % num_levels, (255, 0, 0), (10, 10)) showtext(screen, font, 'bestscore: %s' % best_scores, (255, 0, 0), (210, 10)) showtext(screen, font, 'usedsteps: %s' % num_steps, (255, 0, 0), (410, 10)) showtext(screen, font, 's: your starting point d: your destination', (255, 0, 0), (10, 600)) # ----判断游戏是否胜利 if (hero_now.coordinate[0] == cfg.mazesize[1] - 1) and (hero_now.coordinate[1] == cfg.mazesize[0] - 1): break pygame.display.update() # 更新最优成绩 if best_scores == 'none': best_scores = num_steps else: if best_scores > num_steps: best_scores = num_steps # 关卡切换 interface(screen, cfg, mode='game_switch')
到此这篇关于python实现过迷宫小游戏示例详解的文章就介绍到这了,更多相关python过迷宫小游戏内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!