Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How did Python realize the labyrinth Mini Game

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how Python achieved the labyrinth Mini Game. I hope you will get something after reading this article. Let's discuss it together.

Development tools

Python version: 3.6.4

Related modules:

Pygame module

And some modules that come with Python.

Environment building

Install Python and add it to the environment variable, and pip installs the relevant modules you need.

Brief introduction of principle

Rules of the game:

Players through the ↑↓←→ key to control the action of the protagonist, so that the protagonist from the starting point (upper left corner) around the maze, to the end (lower right corner) is the victory of the game.

Step by step:

First of all, of course, to create a maze, for convenience, here is randomly generated maze way (artificial design is really a waste of eyes, get half do not want to do, interested can try their own.) . The idea is actually very simple: divide the game interface into multiple cell, something like this:

Then an algorithm is designed to traverse all the cell, and each traversed cell opens a wall in some random direction (that is, removing the lines that split the cell) and ok.

The main code''randomly generates the maze class' '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) # start and end marks showText (screen, self.font, 'slots, (255,0,0), (self.border_size [0]-10) Self.border_ Size [1]) showText (screen, self.font, 'Downs, (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))' 'create a maze' @ 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 # View above 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 # View below 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 # View right 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

The next step is to define the role class. The role class needs to move up and down according to the user's operation, and at the same time, ensure that the movement cannot cross the wall. Specifically, the code is implemented as follows:

Define 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''move' '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 in Hero.move...'% direction)' bind to screen''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)

Finally, write down the main cycle of the game, which is actually very simple, as long as each time you load a randomly generated maze map and instantiate a protagonist, then constantly press the key to detect, and move the protagonist according to the result of the keystroke detection, and finally update the interface data according to the action result OK ~ of course, if the protagonist reaches the end point, then enter the level switching interface.

Specifically, the code implementation is as follows:

'' main function''def main (cfg): # initialize 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-Wechat official account: Charles Pikachu') font = pygame.font.SysFont ('Consolas' 15) # start interface Interface (screen, cfg, 'game_start') # record the number of levels num_levels = 0 # record the minimum number of steps used best_scores =' None' # level cycle switching while True: num_levels + = 1 clock = pygame.time.Clock () screen = pygame.display.set_mode (cfg.SCREENSIZE) #-randomly generate level map maze_now = RandomMaze (cfg.MAZESIZE Cfg.BLOCKSIZE, cfg.BORDERSIZE) #-generate hero hero_now = Hero (cfg.HEROPICPATH, [0,0], cfg.BLOCKSIZE, cfg.BORDERSIZE) #-Statistical steps num_steps = 0 #-main cycle in the level while True: dt = clock.tick (cfg.FPS) screen.fill ((255,255) Is_move = False #-↑↓←→ Control 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) #-display some information showText (screen, font, 'LEVELDONE:% d'% num_levels, (255,0,0), (10,10)) showText (screen, font,' BESTSCORE:% s'% best_scores, (255,0,0), 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) If (hero_now.coordinate [0] = = cfg.MAZESIZE [1]-1) and (hero_now.coordinate [1] = = cfg.MAZESIZE [0]-1): break pygame.display.update () # Update Best score if best_scores = = 'None': best_scores = num_steps else: if best_ Scores > num_steps: best_scores = num_steps # level switching Interface (screen Cfg, mode='game_switch') finished reading this article I believe you have a certain understanding of "how Python realized the labyrinth Mini Game". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report