This is my first day of the August Challenge

preface

Today TO share the snake game, no more nonsense, let’s begin happily ~

Results show

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

The rules of the snake game don’t need any more introduction. Writing a snake game is actually very simple. First, let’s initialize the game:

pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(Greedy Snake -- Wechat Official Account :Charles' Pikachu)
clock = pygame.time.Clock()
Copy the code

Then define a greedy snake:

Gluttonous snake
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 the code

Head_coord is used to record the position of the snake’s head, and tail_coords is a two-dimensional array that records the position of all the snake’s bodies. In the beginning, snake length is 3, and the position is randomly generated. Users can control the actions of the snake by pressing ↑, ↓, ←→ :

# -- 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 the code

It should be noted that the snake can not 180° big turn, can only 90° to turn. For example, a snake that is moving to the left cannot suddenly turn to the right. Specifically, the code is implemented 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 the code

Then, we need to randomly generate a food, and we need to ensure that the location of the food is not the same as the location of the snake:

Food category
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 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)
    pygame.draw.circle(screen, self.color, (cx, cy), self.cfg.BLOCK_SIZE//2-2)
# Generate a random food
apple = Apple(cfg, snake.coords)
Copy the code

When updating a snake, if it eats food, the snake’s length is increased by one, otherwise it simply moves in the given direction without changing the snake’s length:

"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
  # Determine if food has been eaten
  if self.head_coord == apple.coord:
    return True
  else:
    self.tail_coords = self.tail_coords[:-1]
    return False
Copy the code

At the same time, when the snake eats food, it has to create a new food:

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

Finally, the game ends when the snake hits the wall or the head hits the body:

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 the code

And display the game over screen:

endInterface(screen, cfg)
Copy the code

That’s the end of this article, thank you for watching Python24 minesweeper minesweeper next article

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.

All done~ private message to get complete source code.

Review past

Python 2048 small games

Python to achieve gobang online games

Python to achieve bomb people small game

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 a maze of small games

Python to achieve whack-a-mole games