Friday, September 24, 2021

Python Snake Game

 

Snake Game in Python Pygame

If you have a basic beginner’s knowledge about python then creating a snake game in python is fairly easy. This blog is supposed to bring you up to speed with python pygame and help you advance your skills in python and pygame. I am not going to use Object Oriented Programming (OOP) model instead I will be using the procedural method.

                Let’s get into it-:

For our game, we are going to need three modules, i.e. pygame, time, and random. The time and random modules are usually preinstalled but you will have to install pygame manually using the pip install pygame command.  

import pygame

import time

import random

 

We now need to initialize the game using the .init() function.

pygame.init()

Next we declare the variables required for our game. We need variables containing the colors we will use. (Colors are in RGB format). The colors are stored in tuples. We also need the width and height of both our game window and the snake in variables.

white = (255255255)

yellow = (255255102)

black = (000)

red = (2135080)

green = (02550)

blue = (50153213)

 

dis_width = 600

dis_height = 400

 

snake_block = 10

snake_speed = 5

The next step is to set the size of the game window and also the ‘name’ of the game. It is also important that we make sure the game will run smoothly across different computers. Some computers are slow and others are quick so by using the pygame.time.clock() function we make sure that the game will run uniformly across all machines.

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

pygame.display.set_caption('Snake Game by Steve')

 

clock = pygame.time.Clock()

 

The next step is to initialize the fonts we are going to use in the game. Pygame has the ability to access system fonts using the pygame. font.Sysfont function.

font_style = pygame.font.SysFont("bahnschrift"25)

score_font = pygame.font.SysFont("comicsansms"35)

In the function, we give the font name as a string followed by its size as an integer.

Methods

A couple of methods are required to make sure the game runs properly.

        1. Score Method

We will need to display the score of the player as they play the game. As always pygame has us sorted out. It’s just a matter of writing down the inbuilt functions. First, we create a method called Your_Score with the parameter score. We then use the font.render() function to display the score in the game window. This creates a new Surface with the specified text rendered on it. Pygame provides no way to directly draw text on an existing Surface: instead, you must use Font.render() to create an image (Surface) of the text, then blit this image onto another surface. To blit the text, we use dis. blit(). It takes in the value(what you want to be displayed on the surface) and the location of the value. In our case, the location is point 0,0. You can change the locations to see how it changes. Note: The location should within 0 to 600 for the width and 0 to 400 for the height.

def Your_score(score):

    value = score_font.render("Your Score: " + str(score)True, yellow)

    dis.blit(value, [00])

2.  Snake Method

Next, we need to draw the snake. It will be a rectangle that increases in length as it ‘eats’. For this, we create an our_snake method. It has two parameters snake_block and snake_list. The snak_list will be expounded in the gameloop method. Inside the method, we loop the snake_list then we draw the snake using pygame.draw.rect() function. It draws a rectangle with the format rect(surface, color, rect). The parameters are as follows

  • surface to draw on
  • color (or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
  • rect -- rectangle to draw, position and dimensions
  • width (int)       

def our_snake(snake_blocksnake_list):

for x in snake_list:

pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) 

                 3. Message Method

This method takes the score method format. We create the message method with two parameters, the message and its color. In the blit function, the width and height are dived into two to make sure that the message appears at the middle of the surface.

def message(msgcolor):

    message = font_style.render(msg, True, color)

    dis.blit(message, [dis_width / 6, dis_height / 3])

   4. Gameloop method

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()

This method contains the functionality of the game. It is here that we program the snake to move, increase in size after successful collision with the ‘food’ and end the game if the player hits the walls. First, we initialize a couple of variables. The snake_list is initialized in at this point.  We need to create the food particles hence the foodx and foody variables. Next, we work with two while loops. The first one checks whether the game is over and the second checks whether the game is still running. Inside the second for loop, we set the background color of the game. We also work with if statements checking for events within the game. The pygame.event.get () function allows us to use the keyboard in the gameplay. We loop through various keys on the keyboard checking whether they have been pressed (KEYDOWN). If a key has been pressed say the left arrow key, we program the snake to move to the left-hand side of the surface. We do so by increasing the left coordinate location of the snake. The same case applies to other respective keys. It is also in this for loop that we check for successful collision of the snake and the food. If a collision has occurred, we need to increase the snake size, delete the food rectangle from that location and draw it somewhere else in the game surface. The random module comes in handy at this point as it allows us to randomly draw the food. We also call the other methods that we had previously created here. If the player his the walls of the game surface, the game stops and they asked whether they want to continue playing or to quit.

We finally end the game creation by calling the game loop method.

gameLoop()


Useful links

The code on GitHub



 

 

Labels: , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home