Instructions for coding the game 'Snake of Prey' in Python

In this article, we will continue to learn about game coding in Python through the legendary Snake game.

In the previous article "Instructions for coding the game "Warrior Rabbit" in Python, we got acquainted with coding the game in Python. This time, we invite you to continue to learn more interesting things through the code guide for the game "Snake of Prey".

Step 1: Install Pygame

The first thing you need to do is install the Pygame library on your computer. You can visit pygame.org/download.shtml to download and install the version of Pygame that matches the Python version on your computer.

Step 2: Create game screen

To create a screen for the game "Snake of Prey" using the Pygame library, you need to use the display.set_mode() function . Additionally, you will also have to use the init() and quit() functions to initialize and uninitialize things at the beginning and end of the program. The update() function is used to update any changes made on the screen.

flip() is another function that works similarly to update() . The difference is that the update() function only updates the changes made while the flip() function redo the entire screen.

Below is the sample code:

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

Running the code you will have the following results:

Picture 1 of Instructions for coding the game 'Snake of Prey' in Python

However, this screen will close immediately. To fix this problem, you need to create a loop for the game by using while before actually exiting the game.

Sample code:

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) #in ra tất cả các hành động xuất hiện trên màn hình pygame.quit() quit()

When you run this code, you will see the same screen as above but it will not close. With the addition of the event.get() function , the screen will return all actions that appear on it. You can also set a screen title using the display.set_caption() function .

Results after running the program:

Picture 2 of Instructions for coding the game 'Snake of Prey' in Python

Now you have the screen for your "Snakes" game, but when you click the close button (X), the screen doesn't close. The reason is because you haven't set the screen to close when you press the close button. To do this, Pygame provides you with a command called QUIT and you can use it 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 the screen is all set up. The next part is to create the snake.

Step 3: Create the snake

To create a snake, you first need to define a few color variables for the snake, prey, screen. The color palette used in Pygame is RGB (Red Green Blue). In this case, if you set it all to 0 for RGB, you'll get black, and if you set it to 255, you'll get white.

In fact, our snake is a rectangle. To draw a rectangle in Pygame, you need to use the draw.rect() function and enter the size and color.

Sample code:

import pygame pygame.init() dis=pygame.display.set_mode((400,300)) pygame.display.set_caption('Snake game by Edureka') 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()

Result when running sample code:

Picture 3 of Instructions for coding the game 'Snake of Prey' in Python

As you can see, the blue snake has appeared on the screen. The next step is to create movement for the snake.

Step 4: Create movement for the snake

To move the snake, you need to create events in Pygame's KEYDOWN class. The events used here are K_UP, K_DOWN, K_LEFT and K_RIGHT, which correspond to up, down, left and right moves of the snake. From this step, the game screen will also be changed from the default black color to white using the fill() function . From this step, the snake also turns black and the game screen also doubles in size.

You also need to create two new variables x1_change and y1_change to hold the updated values ​​of the x and y coordinates. The sample code up to this section is as follows:

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

Result when running the program:

Picture 4 of Instructions for coding the game 'Snake of Prey' in Python

Step 5: Create a Game Over mechanism when the snake hits the edge of the screen

In the snake hunting game, the player will lose if the snake hits the edge of the screen. To do that, you add an if statement to define limits on the x and y coordinates so that they are less than or equal to the screen. You should also not use hardcodes but instead use variables so that you can easily modify them later if needed.

Sample code is as follows:

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

And here is the result when running the program and letting the snake hit the edge of the screen:

Picture 5 of Instructions for coding the game 'Snake of Prey' in Python

Step 6: Add prey

At this step, you add prey to the snake and when the snake passes over the bait, a message "Yummy!!" will appear. The game is also slightly adjusted in the sample code to add options to allow quitting or restarting after losing. Initially, the prey is set to be blue.

Sample code:

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

Here is the result of this step:

Picture 6 of Instructions for coding the game 'Snake of Prey' in Python

Step 7: Increase the length of the snake

In this step, we will add code that will increase the length of the snake after it eats its prey. In addition, another piece of code was added so that when the snake collides with its body, a message will appear indicating that the player has lost, press Q to exit or press C to play again. The length of the snake is essentially contained in a liset and the initial size is a block specified 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 Edureka') 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()

Result of this step:

Picture 7 of Instructions for coding the game 'Snake of Prey' in Python

You can see, to make the game's graphics more attractive, in this step the screen background has changed to blue, the prey has turned green and the snake remains black but the size has been changed. adjust.

Step 8: Display the score

Last but not least, you need to display the player's score on the screen. To do this, you create a new function named Your_score . This function will display the length of the snake minus the original length of 1.

The complete sample code of the game is as follows:

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

Final result when running the program:

Picture 8 of Instructions for coding the game 'Snake of Prey' in Python

So we just showed you how to code the game "Snake of Prey" in Python along with sample code. Hopefully this article will bring you more useful knowledge about the Python programming language.

To learn more about Python, you can visit: What is Python? Why choose Python? and to learn about Python functions, please visit: What are functions in Python? Functions in Python.

Update 09 August 2024
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile