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

Detailed steps to expand LVM disk in Linux

1. Add a hard disk 2. Check the partition status:...

Getting Started Guide to Converting Vue to React

Table of contents design Component Communication ...

Summary of situations where MySQL indexes will not be used

Types of Indexes in MySQL Generally, they can be ...

Example of implementing QR code scanning effects with CSS3

Online Preview https://jsrun.pro/AafKp/ First loo...

How to use shell scripts in node

background During development, we may need some s...

Detailed analysis of mysql MDL metadata lock

Preface: When you execute a SQL statement in MySQ...

Media query combined with rem layout in CSS3 to adapt to mobile screens

CSS3 syntax: (1rem = 100px for a 750px design) @m...

CentOS8 network card configuration file

1. Introduction CentOS8 system update, the new ve...

Nginx+FastDFS to build an image server

Installation Environment Centos Environment Depen...

How to configure SSL certificate in nginx to implement https service

In the previous article, after using openssl to g...

Canonical enables Linux desktop apps with Flutter (recommended)

Google's goal with Flutter has always been to...

In-depth analysis of the Identifier Case Sensitivity problem in MySQL

In MySQL, you may encounter the problem of case s...

How to view the storage location of MySQL data files

We may have a question: After we install MySQL lo...