Pygame code to make a snake game

Pygame code to make a snake game

Pygame functions used

Functions used in the Snake game

Function describe
init() Initializing pygame
display.set_mode() Create a window with a tuple or list as argument
update() Update Screen
quit() pygame for deinitialization
set_caption() Set text at the top of the screen
event.get() Returns a list of all events
Surface.fill() Fill the screen with a solid color
time.Clock() Tracking time
font.Font() Setting the font

Creating a Screen

We use the function display.set_mode() to create the pygame window. At the same time, we also need to perform init() and quit() functions at the beginning and end of the program to ensure that the program can start and end correctly.

import pygame
pygame.init()
dis = pygame.display.set_mode((400,300))
pygame.display.update()
pygame.quit()
quit()


This requires us to run the program, and we can get the following:

But this code, our program creation will only flash by, let's add some code to keep the program window

import pygame
pygame.init()
dis = pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:
    for event in pygame.event.get():
        print(event) # Print out all events pygame.quit()
quit()


We have added the name of the game window and can also see all the events in the Python console as we operate on the pygame window.

Next we add a close response event

pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake')
game_over = False
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over=True

pygame.quit()
quit()


Now that our game window is set up, we can draw snake .

Creating a snake

We first create some color variables to represent snake , food , screen , etc.

pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake')

blue=(0,0,255)
red=(255,0,0)

game_over = False
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over=True

    pygame.draw.rect(dis, blue, [200, 150, 10, 10])
    pygame.display.update()

pygame.quit()
quit()


In this way, a snake is created, which is the little blue dot.

Make the snake move

In order to realize the movement of snake , the key event we need to use is KEYDOWN, which contains four key values, K_UP, K_DOWN, K_LEFT, and K_RIGHT, which represent up, down, left, and right respectively.

pygame.init()
pygame.display.set_caption('Snake')
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

dis = pygame.display.set_mode((800, 600))

game_over = False

x1 = 300
y1 = 300

x1_change = 0
y1_change = 0

clock = pygame.time.Clock()

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x1_change = -10
                y1_change = 0
            elif event.key == pygame.K_RIGHT:
                x1_change = 10
                y1_change = 0
            elif event.key == pygame.K_UP:
                y1_change = -10
                x1_change = 0
            elif event.key == pygame.K_DOWN:
                y1_change = 10
                x1_change = 0

    x1 += x1_change
    y1 += y1_change
    dis.fill(white)
    pygame.draw.rect(dis, black, [x1, y1, 10, 10])

    pygame.display.update()

    clock.tick(30)

pygame.quit()
quit()

I created x1_change and y1_change variables to update the x and y coordinates so that our snake can move.

Handling Game Over

For the Snake game, if snake moves out of the game screen, the game has failed. Let's deal with this part of the logic below.

import pygame
import time

pygame.init()
pygame.display.set_caption('Snake')
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_width))

game_over = False

x1 = dis_width / 2
y1 = dis_height / 2

snake_block = 10

x1_change = 0
y1_change = 0

clock = pygame.time.Clock()
snake_speed = 30

font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 2, dis_height / 2])


while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x1_change = -snake_block
                y1_change = 0
            elif event.key == pygame.K_RIGHT:
                x1_change = snake_block
                y1_change = 0
            elif event.key == pygame.K_UP:
                y1_change = -snake_block
                x1_change = 0
            elif event.key == pygame.K_DOWN:
                y1_change = snake_block
                x1_change = 0

    if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
        game_over = True

    x1 += x1_change
    y1 += y1_change
    dis.fill(white)
    pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])

    pygame.display.update()

    clock.tick(snake_speed)

message("You failed, please restart the game!", red)
pygame.display.update()
time.sleep(2)

pygame.quit()
quit()

Increase food

Since it is a greedy snake, of course it needs to be fed. Now let's deal with the food.

import pygame
import time
import random

pygame.init()
pygame.display.set_caption('Snake')

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)

dis_width = 800
dis_height = 600

dis = pygame.display.set_mode((dis_width, dis_height))

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 30

font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 3, dis_height / 3])


def gameLoop(): # creating a function
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(white)
            message("You failed, please restart the game!", red)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True

        x1 += x1_change
        y1 += y1_change
        dis.fill(white)
        pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])
        pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
        pygame.display.update()

        if x1 == foodx and y1 == foody:
            print("Good!")
        clock.tick(snake_speed)

    pygame.quit()
    quit()

gameLoop()

I created a function gameLoop as our main function, initialized the snake's food, and added the keyboard c and q keywords to restart and exit the game.

Snake Growth

Next, we will start to increase the length of the snake after snake eats the food. This is also the basic rule of the game.

import pygame
import time
import random

pygame.init()
pygame.display.set_caption('Snake')
font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)
score_font = pygame.font.Font("C:/Windows/Fonts/STCAIYUN.TTF", 30)

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15


def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You failed, please restart the game!", red)

            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()
    gameLoop()

Show score

Finally, let's display the score. After all, the player's score is still very important for the game.

import pygame
import time
import random

pygame.init()
pygame.display.set_caption('Snake')
font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)
score_font = pygame.font.Font("C:/Windows/Fonts/STCAIYUN.TTF", 30)

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15


def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])


def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You failed, please restart the game!", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()

Here we create a Your_score function to record the player's score

In this way, we have completed a simple snake game.

Finally, let's add background music to the game to make the game time more comfortable.

# Play music pygame.init()
pygame.mixer.music.load(r"Game.mp3")
pygame.mixer.music.play()


This is the end of this article about making a snake game with 100 lines of Pygame code. For more information about making a snake game with Pygame, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of implementing a snake game based on pygame
  • Implementing a simple snake game based on Pygame
  • Python Practice: Using Pygame to Implement the Snake Game (Part 2)
  • Python practical use of pygame to realize the snake game (I)
  • Use Python third-party library pygame to write a snake game
  • Python uses the pygame toolkit to implement the snake game (colorful version)
  • Pygame implements the snake game (Part 2)
  • Pygame implements the snake game (Part 1)

<<:  Introduction to the use of CSS3 filter attribute

>>:  How to create a MySQL master-slave database using Docker on MacOS

Recommend

How to configure nginx+php+mysql in docker

First, understand a method: Entering a Docker con...

Detailed explanation of MySQL combined query

Using UNION Most SQL queries consist of a single ...

A brief discussion on whether MySQL can have a function similar to Oracle's nvl

Use ifnull instead of isnull isnull is used to de...

Drop-down menu and sliding menu design examples

I found a lot of websites that use drop-down or sl...

JavaScript implements an input box component

This article example shares the specific code for...

JavaScript design pattern learning adapter pattern

Table of contents Overview Code Implementation Su...

When to use Map instead of plain JS objects

Table of contents 1. Map accepts any type of key ...

What to do if you forget your mysql password

Solution to forgetting MySQL password: [root@loca...

7 skills that web designers must have

Web design is both a science and an art. Web desi...

Detailed explanation of Vue component reuse and expansion

Table of contents Overview Is the extension neces...

InnoDB engine redo file maintenance method

If you want to adjust the size and number of Inno...

Detailed explanation of the use cases of Vue listeners

The first one is to use jQuery's ajax to send...

A detailed tutorial on using Docker to build a complete development environment

Introduction to DNMP DNMP (Docker + Nginx + MySQL...

Details of watch monitoring properties in Vue

Table of contents 1.watch monitors changes in gen...

Steps to run ASP.NET Core in Docker container

There are too much knowledge to learn recently, a...