Review past

Python to achieve classic pac-man games

Python to achieve elimination of music games

Python real dinosaur jump a jump small game is

Python simple version of the aircraft war games

Python tetris small game implementation

Python alien invasion to achieve small games

Python to achieve “little rabbit and Bun” game

Python eight notes to achieve small games

Python to achieve the puzzle game

Python to achieve ski games

Python for classic 90 tank wars

Python FlappyBird implementation of small games

Python to achieve tower defense games

Python to achieve fruit and gold coins small games

Python to achieve a small game push box

Python to achieve 24 small games

Python to achieve table tennis games

Python brick to achieve small games

Python to achieve bomb people small game

preface

Today for you to bring boredom with the maze of small games to share with you. Let’s get started happily ~

The development tools

Python version: 3.6.4

Related modules:

Pygame module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required modules.

Introduction of the principle

Rules of the game:

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

Step by step:

First, of course, is to create the maze, for convenience, here is a random maze generation method (artificial design is really an eye, half do not want to do, interested can try it on their own). . The idea is simple: divide the game interface into multiple cells, something like this:

Then the algorithm is designed to traverse all the cells, and each traversed cell opens a wall in some random directions (that is, remove the lines that divide the cell)

Specifically, the code is implemented as follows:

Randomly generated 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)
  "Draw to screen"
  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 finish marks
    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))
  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
      # Check the top 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
      # Check the block below
      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
      # Look at the left 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
      # See the block on the right
      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
    returnBlocks_list defines the role class, which moves up, down, left, and right according to the user's actions, while making sure that the movement does not cross the wall"' definition of 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 <%s> 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)] screen.blit(self.image, self.rect) Finally update the interface data according to the action result is OK ~ of course, if the protagonist reaches the end, then enter the level switch interface. Specifically, the code is implemented as follows: ' 'pythonMain function
def main(cfg) :
  # initialization
  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 screen
  Interface(screen, cfg, 'game_start')
  Record the number of levels
  num_levels = 0
  Record the minimum number of steps to complete the game
  best_scores = 'None'
  # Level loop switch
  while True:
    num_levels += 1
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    # -- Generate level maps randomly
    maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)
    # -- generate a hero
    hero_now = Hero(cfg.HEROPICPATH, [0.0], cfg.BLOCKSIZE, cfg.BORDERSIZE)
    # -- Count the steps
    num_steps = 0
    # -- The main loop inside the level
    while True:
      dt = clock.tick(cfg.FPS)
      screen.fill((255.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)
      # ---- Displays some information
      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))
      # ---- Determine if the game is successful
      if (hero_now.coordinate[0] == cfg.MAZESIZE[1] - 1) and (hero_now.coordinate[1] == cfg.MAZESIZE[0] - 1) :break
      pygame.display.update()
    # Update the 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')
Copy the code

That’s the end of this article. Thanks for watching Python24 games. Next post will be whack-a-mole

To thank the readers, I’d like to share some of my recent programming gems to give back to each and every one of you.

① More than 2000 Python ebooks (both mainstream and classic)

Python Standard Library (Chinese version)

(3) project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis videos (suitable for small white learning)

⑤Python Learning Roadmap

⑥ Two days of Python crawler boot camp live permissions

All done~ see personal home profile or private message for complete source code.