Hello readers, let’s build a game using Python. Yes, you heard that right! We will be building a simple snake game using the pygame library.
Remember old days, when everyone used to play the iconic snake game. Let’s revive those old days and build one on our own! So, in this tutorial, we will be building that iconic game.
So, let’s start building our game. We will do it step by step to get a clear understanding of every part of the game and what purpose it has in our game! So, let’s begin:
First, of all, we need to import the libraries into our code which will be used to build the game. We will need the below-mentioned libraries to build and run our game.
import pygame
import time
import random
**pygame: **This library will help us get all the graphical components to build the game.
random: This library will help us in spawning the food at random locations in the game.
time: This helps us with time-related functionalities in the game, as the speed of the snake.
Now, let’s begin building the actual part of the game. We will first initialise the game to have a window with us in which the game will be played.
pygame.init()
Then we would love to define the colours we would be using in the game with the help of RGB notations. Get the RGB codes from the internet and put these as co-ordinates for the colour variables. We have defined 6 colours in our game but you are free to use any colour of your choice. Make sure the colour combinations are good for playing the game.
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
Next, we should define the size of the display in which our game would be running. So, in this case, we would define the height to be 600px and width to be 800px.
width = 800
height = 600
Next, we will set our display with the defined width and height variables as input and we would describe the name of the game to be displayed as a caption for our game.
dis = pygame.display.set_mode((width, height))
pygame.display.set_caption(‘Shubham Snake Game’)
Now, we will initialise our clock variable which will make use of the time package which we imported earlier. This variable ‘clock’ will take care of all time-related queries in our complete code.
clock = pygame.time.Clock()
Now, let’s define the speed of our snake and also the size of the snake’s block i.e. the width of the snake. This is purely based on user choice and I have also chosen some numbers which I felt like a good fit for the game.
snake_block = 10
snake_speed = 12
Next, we describe the font size and font style for score display and for the display of other information such as to notify that you lost the game or you want to play again.
font_style = pygame.font.SysFont(“bahnschrift”, 25)
score_font = pygame.font.SysFont(“comicsansms”, 35)
#python #programming #coding #game-development #python-programming