Python made the first real mobile game in that year – Snake game

Time:2022-5-9

preface

Recently, many students have asked if they can make a little game in Python, and it’s best to clarify what each paragraph is for

OK, today I’ll explain how to make a snake game with Python pyGame

It is said that the snake game is a classic arcade game launched by gremlin company in 1976. Today’s Snake game made in Python is a pixel version. Although it is simple, it can still be played

What we need to do

  1. Create game window
  2. Draw greedy snakes and food
  3. Snakes eat food

Chessboard model of greedy snake


Let’s start our code now. First, import the module

import pygame
import random
import copy

 

1. Create a game window

1.1 game initialization

pygame.init()
clock = pygame. time. Clock() # set the game clock
pygame. display. set_ Caption ("greedy snake - answer, source code and relevant materials can be trusted me") # initialize the title
screen = pygame. display. set_ Mode ((500, 500)) # initializes the window. The size of the window is 500

 

1.2 initialize the position of the snake. The length of the snake is 10, that is, the X and Y coordinates of the snake

snake_list = [[10, 10]]

 

First, set a running direction of the snake, and then judge that the keyboard event is determining the running direction of the snake
The snake can run, so the next step is to eat food to increase its length and not eat food to display in different positions

Initial snake direction

move_up = False
move_down = False
move_left = False
move_right = True

 

1.3 initialize the location of food

x = random.randint(10, 490)
y = random.randint(10, 490)
food_point = [x, y]

 

1.4 start the game cycle

running = True
while running:
    #Game clock refresh rate
    clock.tick(20)

 

1.5 the filling background is white

screen.fill([255, 255, 255])

 

1.6 drawing background

for x in range(0, 501, 10):
    pygame.draw.line(screen, (195, 197, 199), (x, 0), (x, 500), 1)
    pygame.draw.line(screen, (195, 197, 199), (0, x), (500, x), 1)
    food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)

 

1.7 draw snake

snake_rect = []
for pos in snake_list:
    #1.7.1 draw the body of the snake
    snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))

 

2. Draw snake and food

2.1 get the length of the snake and move the body of the snake

pos = len(snake_list) - 1
while pos > 0:
    snake_list[pos] = copy.deepcopy(snake_list[pos - 1])
    pos -= 1

 

2.2 change snakehead position

if move_up:
    snake_list[pos][1] -= 10
    if snake_list[pos][1] < 0:
        snake_list[pos][1] = 500

if move_down:
    snake_list[pos][1] += 10
    if snake_list[pos][1] > 500:
        snake_list[pos][1] = 0

if move_left:
    snake_list[pos][0] -= 10
    if snake_list[pos][0] < 0:
        snake_list[pos][0] = 500

if move_right:
    snake_list[pos][0] += 10
    if snake_list[pos][0] > 500:
        snake_list[pos][0] = 0

 

2.3 keyboard control mobile position

for event in pygame.event.get():
    # print(event)
    #Judge the pressed key
    if event.type == pygame.KEYDOWN:
        #Up key
        if event.key == pygame.K_UP:
            move_up = True
            move_down = False
            move_left = False
            move_right = False
        #Down key
        if event.key == pygame.K_DOWN:
            move_up = False
            move_down = True
            move_left = False
            move_right = False
        #Left key
        if event.key == pygame.K_LEFT:
            move_up = False
            move_down = False
            move_left = True
            move_right = False
        #Right click
        if event.key == pygame.K_RIGHT:
            move_up = False
            move_down = False
            move_left = False
            move_right = True

 

2.4 get the length of the snake and move the body of the snake

pos = len(snake_list) - 1
while pos > 0:
    snake_list[pos] = copy.deepcopy(snake_list[pos - 1])
    pos -= 1

 

3. Snakes eat food

3.1 collision detection if the snake eats food

if food_rect.collidepoint(pos):
    #Greedy snakes eat food
    snake_list.append(food_point)
    #Reset food location
    food_point = [random.randint(10, 490), random.randint(10, 490)]
    food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)
    break

 

3.2 if the snake eats itself

head_rect = snake_rect[0]
count = len(snake_rect)
while count > 1:
    if head_rect.colliderect(snake_rect[count - 1]):
        running = False
    count -= 1

pygame.display.update()

 

Recommended Today

Dart series: Dancers in browsers use dart to send HTTP requests

brief introduction Dart: the HTML package provides dart with some necessary components for building the browser client. We mentioned the operations of HTML and DOM before. In addition, another common operation on the browser side is to use XMLHttpRequest to make asynchronous HTTP resource requests, that is, AJAX requests. Dart also provides a package similar […]