current position:Home>Python game development, python to achieve Snake games and eat beans with source code

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

2022-02-02 09:47:38 Programming simplicity

development tool

Python edition : 3.6.4

Related modules :

pygame modular ;

As well as some Python Built in modules .

Environment building

install Python And add to environment variable ,pip Install the relevant modules required .

Introduction of the principle

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

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

Then define a greedy snake :

''' Greedy for snakes '''
class Snake(pygame.sprite.Sprite):
  def __init__(self, cfg, **kwargs):
    pygame.sprite.Sprite.__init__(self)
    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 

among head_coord Used to record the location of the snake head , and tail_coords Is a two-dimensional array , Used to record the position of all snakes . In limine , Greedy snakes grow into 3, And the location is randomly generated . User pass ↑↓←→ Key to control the action of greedy snake :

# -- Key detection 
for event in pygame.event.get():
  if event.type == pygame.QUIT:
    pygame.quit()
    sys.exit()
  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 180° Big turn , Can only 90° Ground turning . For example, a voracious snake moving to the left cannot instantly turn into a right . To be specific , The code implementation is as follows :

''' Set the 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 it is necessary to ensure that the position of the food is not the same as that of the greedy snake :

''' Food '''
class Apple(pygame.sprite.Sprite):
  def __init__(self, cfg, snake_coords, **kwargs):
    pygame.sprite.Sprite.__init__(self)
    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:
        break
    self.color = (255, 0, 0)
  ''' Draw it on the 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)
    pygame.draw.circle(screen, self.color, (cx, cy), self.cfg.BLOCK_SIZE//2-2)
#  Randomly generate a food 
apple = Apple(cfg, snake.coords)
 Copy code 

When updating the snake , If it eats food , Then the length of the snake increases by one , Otherwise, simply act in a given direction without changing the length of the snake :

''' Update snake '''
def update(self, apple):
  #  Move 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
  #  Judge if you have eaten food 
  if self.head_coord == apple.coord:
    return True
  else:
    self.tail_coords = self.tail_coords[:-1]
    return False
 Copy code 

meanwhile , When the snake gets food , Need to regenerate a new food :

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

Last , When a greedy snake touches a wall or a snake's head touches a snake's body , Game over :

''' Determine if the game is over '''
@property
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 :

Players go through ↑↓←→ Key control game protagonist eat beans man eat all beans hidden in the maze , And can't be caught by ghosts .

If you can finish all the beans in the maze without being caught by the ghost , Then the game wins , Otherwise the game will fail .

Step by step :

Step1: Define the game sprite class

First , Let's first clarify which game sprites the game needs .

① Wall class

② Food ( Beans )

③ Character class

Character categories include pac man and ghost , Ghosts are controlled by computers , Pac man is controlled by players .

obviously , They all need to have the ability to update the character's position and change the direction of the character's movement , Its source code is as follows :

Step2: Design game maps

utilize Step1 The game spirit class defined in , We can start designing game maps . Due to limited time , I only wrote a game map of a level , Interested partners can expand on this basis ( It is very convenient to extend my source code ~). The design of the game map includes the following four aspects :

① Create walls

② Creating doors ( In the beginning, it was for ghosts )

image.gif

③ Create the role

④ Create food

Because food can't touch the wall 、 The positions of the door and the character overlap , So for the convenience of designing game maps , To create the wall first 、 Create food after doors and characters :

Step3: Design the main loop of the game

Next, we start to design the main loop of the game . The first is initialization :

Then define the main function :

among startLevelGame Function is used to start a certain level of the game , Its source code is as follows :

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 , Thanks for watching , Remember to like and pay attention to the next article to share Xiaole games

To thank readers , I want to share with you some of my recent collections of programming dry goods , Every reader , I hope I can help you .

copyright notice
author[Programming simplicity],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020947373703.html

Random recommended