Python game development, python to achieve Snake games and eat beans with source code

development tool

Python version: 3.6 four

Related modules:

pygame module;

And some Python built-in modules.

Environment construction

Install Python and add it to the environment variable. pip can install the relevant modules required.

Principle introduction

I don't need to introduce the rules of the snake game, T_T. Writing a snake game is actually very simple. First, let's initialize the game:

screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Greedy Snake - WeChat official account:Charles Picchu')
clock = pygame.time.Clock()
Copy code

Then define a greedy Snake:

'''Voracious snakes'''
class Snake(pygame.sprite.Sprite):
  def __init__(self, cfg, **kwargs):
    self.cfg = cfg
    self.head_coord = [random.randint(5, cfg.GAME_MATRIX_SIZE[0]-6), random.randint(5, cfg.GAME_MATRIX_SIZE[1]-6)]
    self.tail_coords = []
    for i in range(1, 3):
      self.tail_coords.append([self.head_coord[0]-i, self.head_coord[1]])
    self.direction = 'right'
    self.head_colors = [(0, 80, 255), (0, 255, 255)]
    self.tail_colors = [(0, 155, 0), (0, 255, 0)]
Copy code

Where head_coord is used to record the location of the snake head, while tail_coords is a two-dimensional array used to record the position of all snake bodies. At first, the greedy snake was 3 long and its position was randomly generated. The user controls the action of greedy snake by pressing ↑↓←→ key:

# --Key detection
for event in pygame.event.get():
  if event.type == pygame.QUIT:
  elif event.type == pygame.KEYDOWN:
    if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
      snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
Copy code

It should be noted that greedy snakes cannot turn 180 ° and can only turn 90 °. For example, a voracious snake moving to the left cannot instantly turn into a right. Specifically, the code implementation is as follows:

'''Set direction'''
def setDirection(self, direction):
  assert direction in ['up', 'down', 'right', 'left']
  if direction == 'up':
    if self.head_coord[1]-1 != self.tail_coords[0][1]:
      self.direction = direction
  elif direction == 'down':
    if self.head_coord[1]+1 != self.tail_coords[0][1]:
      self.direction = direction
  elif direction == 'left':
    if self.head_coord[0]-1 != self.tail_coords[0][0]:
      self.direction = direction
  elif direction == 'right':
    if self.head_coord[0]+1 != self.tail_coords[0][0]:
      self.direction = direction
 Copy code

Then, we need to randomly generate a food and ensure that the position of the food is not the same as that of the greedy Snake:

'''Food category'''
class Apple(pygame.sprite.Sprite):
  def __init__(self, cfg, snake_coords, **kwargs):
    self.cfg = cfg
    while True:
      self.coord = [random.randint(0, cfg.GAME_MATRIX_SIZE[0]-1), random.randint(0, cfg.GAME_MATRIX_SIZE[1]-1)]
      if self.coord not in snake_coords:
    self.color = (255, 0, 0)
  '''Draw to screen'''
  def draw(self, screen):
    cx, cy = int((self.coord[0] + 0.5) * self.cfg.BLOCK_SIZE), int((self.coord[1] + 0.5) * self.cfg.BLOCK_SIZE), self.color, (cx, cy), self.cfg.BLOCK_SIZE//2-2)
# Randomly generate a food
apple = Apple(cfg, snake.coords)
Copy code

When updating the greedy snake, if it eats food, the snake length will be increased by one, otherwise it will simply act in a given direction without changing the snake length:

'''Update greedy snake'''
def update(self, apple):
  # Moves in the specified direction
  self.tail_coords.insert(0, copy.deepcopy(self.head_coord))
  if self.direction == 'up':
    self.head_coord[1] -= 1
  elif self.direction == 'down':
    self.head_coord[1] += 1
  elif self.direction == 'left':
    self.head_coord[0] -= 1
  elif self.direction == 'right':
    self.head_coord[0] += 1
  # Determine whether you have eaten food
  if self.head_coord == apple.coord:
    return True
    self.tail_coords = self.tail_coords[:-1]
    return False
 Copy code

At the same time, when the greedy snake eats food, it needs to regenerate a new food:

apple = Apple(cfg, snake.coords)
Copy code

Finally, when the greedy snake touches the wall or the snake's head touches the snake's body, the game ends:

'''Determine whether the game is over'''
def isgameover(self):
  if (self.head_coord[0] < 0) or (self.head_coord[1] < 0) or \
     (self.head_coord[0] >= self.cfg.GAME_MATRIX_SIZE[0]) or \
     (self.head_coord[1] >= self.cfg.GAME_MATRIX_SIZE[1]):
    return True
  if self.head_coord in self.tail_coords:
    return True
  return False
 Copy code

And display the game end interface:

endInterface(screen, cfg)
Copy code

Effect display

Introduction to the principle of classic bean eating games

Effect display

Introduction to the game:

The player controls the protagonist of the game through the ↑↓←→ key. The bean eater eats all the beans hidden in the maze and cannot be caught by the ghost.

If you can eat all the beans in the maze without being caught by the ghost, the game will win, otherwise the game will fail.

Step by step:

Step 1: define the game sprite class

First of all, let's make it clear which game sprites the game needs.

① Wall class

② Food (i.e. beans)

③ Role class

The character category includes pac man and ghost. The ghost's trajectory is controlled by the computer, and the pac man's trajectory is controlled by the player.

Obviously, they all need the ability to update the character's position and change the character's motion direction. The source code is as follows:

Step 2: design game map

Using the game wizard class defined in step 1, we can start designing the game map. Due to the limited time, I only wrote a game map of a level. Interested partners can expand on this basis (it is very convenient to expand on the basis of my source code ~). The design of game map includes the following four aspects:

① Create wall

② Create a door (used to close the ghost at the beginning)


③ Create role

④ Create food

Because food cannot overlap with the positions of walls, doors and characters, in order to facilitate the design of game maps, you should create walls, doors and characters before creating food:

Step 3: design the main loop of the game

Next, start designing the game main loop. The first is initialization:

Then define the main function:

The startLevelGame function is used to start a level game, and its source code is as follows:

The showText function is used to display prompt text in the game interface at the end of the game or level switching. Its source code is as follows:

This is the end of the article. Thank you for watching. Remember to like and pay attention to the next article to share Xiaole games

In order to thank the readers, I would like to share some of my recent collection of programming dry goods with you. Every reader hopes to help you.

Keywords: Python Programmer pygame

Added by faheemhameed on Sat, 18 Dec 2021 05:53:41 +0200