the Snake game in Python
Tags: beginners, python, gamedev, programming
Published: 2021-11-06 20:50:06

#1. Installing Pygame

The first thing we need to do is install the Pygame library. This can be done by simply running the following command:

pip install pygame

After doing this, just import this library and start developing the game. But before that, let's take a look at the main functions of this library, which we will use when creating a game.

|Function|Description|
| ------------- |:-------------:| -----:|
|init()|Initializes all Pygame modules (returns a tuple in case of success or failure).|
|display.set_mode()|To create a surface, it takes either a list or a tuple as a parameter (a tuple is preferable).|
|update()|Refreshes the screen.|
|quit()|Used to initialize all modules.|
|set_caption()|Sets the title text at the top of the screen|
|event.get()|Returns a list of all events.|
|Surface.fill()|Fills the space with a solid colour.|
|time.Clock()|Time tracking|
|font.SysFont()|Sets the Pygame font using system resources.|

#2. Creating a screen

To create a screen using Pygame, you need to use the **display.set_mode()** function. You also need to use the **init()** method to initialize the screen at the beginning of the code and the **quit()** method to close it at the end. The **update()** method is used to apply any changes to the screen. There is also a **flip()** method that works in a similar way to **update()**. The only difference is that the **flip()** method rewrites the entire screen, and the **update()** method applies exactly the changes (although if it is used without parameters, it also rewrites the entire screen).

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

However, when you run this code, the screen will appear only for a moment, and then disappear. To fix this error, we will use the **while** loop, which will run until the end of the game:

```import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Pythonist')
game_over=False
while not game_over:
    for event in pygame.event.get():
        print(event)
 pygame.quit()
quit()```

Now, by running this code, you will see that the screen does not disappear as before. It will display all the actions of the game. We achieved this thanks to the **event.get()** function. Also, using the **display.set_caption()** function, we displayed the title of our screen — 'Snake game by Pythonist’.
Now we have a screen for the game, but when you click on the close button, the screen will not close. This is because we have not provided for such behaviour. To solve this problem, Pygame provides a "QIUT" event, which we use as follows:

```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():
        if event.type==pygame.QUIT:
            game_over=True
 pygame.quit()
quit()```
Now that our screen is fully prepared, we have to draw a snake on it. The following section is devoted to this.

#3. Creating a snake
Before creating a snake, we initiate several colour variables to colourize the snake itself, the food and the screen. Pygame uses the RGB colour scheme (RED, GREEN, BLUE). Setting all colors to **0** corresponds to black, and **255** corresponds to white, respectively.
In fact, our snake is a rectangle. To draw a rectangle in Pygame, you can use the **draw.rect()** function, which will draw us a rectangle of a given color and size.

```import pygame
pygame.init()
dis=pygame.display.set_mode((400,300)) 
pygame.display.set_caption('Snake game by Pythonist')
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()```
As you can see, the snake is created in the form of a blue rectangle. Now we need to teach her to move.

#4. Snake Movement
To move the snake, we will use key events from the **KEYDOWN** class of the Pygame library. The **K_UP**, **K_DOWN**, **K_LEFT**, and **K_RIGHT** events will cause the snake to move up, down, left, and right, respectively. Also, the display colour changes from black (by default) to white using the **fill()** method.
To save the **x** and **y** coordinate changes, we have created two new variables: **x1_change** and **y1_change**.

```import pygame
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
dis = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake game by Pythonist')
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()```

#5. "Game over" when the snake reaches the border.
In the snake game, the player loses if he touches the border of the screen. To set this behaviour, we must use the **if** statement, which will make sure that the x and y coordinates are smaller than the screen size. We will use variables for this, so that you can then, on occasion, easily make any changes to the game.

```import pygame
import time
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
dis_width = 800
dis_height  = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake game by Pythonist')
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.SysFont(None, 50)
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 lost",red)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()```

#6. Adding Food

Now we will add some food for the snake, and when it crosses it, we will display the message "Yummy!! In addition, we will make small changes that will allow the player to stop the game, as well as start it again in case of defeat.

```import pygame
import time
import random
pygame.init()
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))
pygame.display.set_caption('Snake Game by Edureka')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 30
font_style = pygame.font.SysFont(None, 30)
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 Lost! Press Q-Quit or C-Play Again", 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("Yummy!!")
        clock.tick(snake_speed)
    pygame.quit()
    quit()
gameLoop()```

#7. Increasing the length of the snake

The following code will increase the length of the snake after it has absorbed food. Also, if the snake collides with its tail, the game ends and the message is displayed“ "You Lost! Press Q-Quit or C-Play Again“. The length of the snake is stored in the list, and the base values are set in the following code.

```import pygame
import time
import random
pygame.init()
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))
pygame.display.set_caption('Snake Game by Pythonist')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
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 Lost! Press C-Play Again or Q-Quit", 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()```

#8. Displaying the invoice on the screen

Last but not least, you need to display the player's score. To do this, we created the **Your_score** function. This function will show the size of the snake minus **1** (since this is the initial size of the snake).

```import pygame
import time
import random
pygame.init()
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))
pygame.display.set_caption('Snake Game by Pythonist')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
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 Lost! Press C-Play Again or Q-Quit", 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()```