Snake game is one of the most popular arcade games in history. In this game, the player's main goal is to catch the maximum amount of fruit without hitting the wall or hitting the wall. When learning Python or Pygame, you can see creating a snake game as a challenge. This is one of the best beginner friendly projects that every novice programmer should accept. Learning to build video games is an interesting and interesting learning.
We will use Pygame to create this snake game. Pygame is an open source library designed for making video games. It has a built-in graphics and sound library. It is also beginner friendly and cross platform.
๐ฌ install
To install Pygame, you need to open the terminal or command prompt and enter the following command:
pip install pygame
After installing Pygame, we can create our cool Snake game.
๐ฐ Step by step method for creating Snake game with Pygame:
๐ Step 1: first, we are importing the necessary libraries.
- After that, we will define the width and height of the window in which the game will run.
- And define the color we will use to display text in the game in RGB format.
# Import library import pygame import time import random snake_speed = 15 # Window size window_x = 720 window_y = 480 # define color black = pygame.Color(0, 0, 0) white = pygame.Color(255, 255, 255) red = pygame.Color(255, 0, 0) green = pygame.Color(0, 255, 0) blue = pygame.Color(0, 0, 255)
๐ Step 2: after importing the library, we need to use Pygame The init() method initializes Pygame.
- Create a game window with the width and height defined in the previous step.
- Here is pyGame time. Clock () will be further used in the main logic of the game to change the speed of the snake.
# Initialize pygame pygame.init() # Initialize game window pygame.display.set_caption('GeeksforGeeks Snakes') game_window = pygame.display.set_mode((window_x, window_y)) # FPS controller fps = pygame.time.Clock()
๐ฏ Step 3: initialize the location and size of the snake.
- After initializing the snake position, randomly initialize the fruit position at any position of the defined height and width.
- By setting the direction to RIGHT, we ensure that whenever the user runs the program / game, the Snake must move to the RIGHT on the screen.
# Define default location snake_position = [100, 50] # Define the first 4 blocks of the snake body snake_body = [ [100, 50], [90, 50], [80, 50], [70, 50] ] # Fruit location fruit_position = [random.randrange(1, (window_x//10)) * 10, random.randrange(1, (window_y//10)) * 10] fruit_spawn = True # Sets the default snake direction to the right direction = 'RIGHT' change_to = direction
๐ฅ Step 4: create a function to display the player's score.
- In this function, we first create a font object, that is, the font color will appear here.
- Then we use rendering to create a background surface, and whenever our score is updated, we change it.
- Create a rectangular object for the text surface object (the text will refresh here)
- Then, we use BLIT to display our scores. BLIT requires two parameters screen blit(background,(x,y))
# Initial score score = 0 # Display scoring function def show_score(choice, color, font, size): # Create font object score_font score_font = pygame.font.SysFont(font, size) # Create a display surface object core_surface score_surface = score_font.render('Score : ' + str(score), True, color) # Creates a rectangular object for the text surface object score_rect = score_surface.get_rect() # display text game_window.blit(score_surface, score_rect)
๐ด Step 5: now create a game end function, which will represent the score after the snake is hit by the wall or itself.
- In the first line, we created a font object to display the score.
- Then we create a text surface to render the score.
- After that, we will set the position of the text in the middle of the playable area.
- Use blit to display the score and update the score by updating the surface with flip().
- We use sleep(2) to wait 2 seconds before closing the window with quit().
# Game end function def game_over(): # Create font object my_font my_font = pygame.font.SysFont('times new roman', 50) # Creates a text surface on which text will be drawn game_over_surface = my_font.render('Your Score is : ' + str(score), True, red) # Creates a rectangular object for the text surface object game_over_rect = game_over_surface.get_rect() # Set text position game_over_rect.midtop = (window_x/2, window_y/4) # blit draws text on the screen game_window.blit(game_over_surface, game_over_rect) pygame.display.flip() # We will exit the program in 2 seconds time.sleep(2) # Deactivate pygame Library pygame.quit() # Exit program quit()
โฐ Step 6: now we will create our main function, which will do the following:
- We will verify the key responsible for the snake movement, and then we will create a special condition that the snake is not allowed to move in the opposite direction immediately.
- After that, if the snake collides with the fruit, we will increase the score by 10 and the new fruit will be crossed.
- After that, we are checking whether the snake was hit by the wall. If a snake hits the wall, we will call the game end function.
- If the snake hits itself, the game end function will be called.
- Finally, we will use the show we created earlier_ The score function displays the score.
# Main function while True: # Handling critical events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: change_to = 'UP' if event.key == pygame.K_DOWN: change_to = 'DOWN' if event.key == pygame.K_LEFT: change_to = 'LEFT' if event.key == pygame.K_RIGHT: change_to = 'RIGHT' # If you press both keys at the same time # We don't want the snake to move in both directions at the same time if change_to == 'UP' and direction != 'DOWN': direction = 'UP' if change_to == 'DOWN' and direction != 'UP': direction = 'DOWN' if change_to == 'LEFT' and direction != 'RIGHT': direction = 'LEFT' if change_to == 'RIGHT' and direction != 'LEFT': direction = 'RIGHT' # Mobile snake if direction == 'UP': snake_position[1] -= 10 if direction == 'DOWN': snake_position[1] += 10 if direction == 'LEFT': snake_position[0] -= 10 if direction == 'RIGHT': snake_position[0] += 10 # Snake growth mechanism # If the fruit collides with the snake, the score will increase by 10 snake_body.insert(0, list(snake_position)) if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]: score += 10 fruit_spawn = False else: snake_body.pop() if not fruit_spawn: fruit_position = [random.randrange(1, (window_x//10)) * 10, random.randrange(1, (window_y//10)) * 10] fruit_spawn = True game_window.fill(black) for pos in snake_body: pygame.draw.rect(game_window, green, pygame.Rect( pos[0], pos[1], 10, 10)) pygame.draw.rect(game_window, white, pygame.Rect( fruit_position[0], fruit_position[1], 10, 10)) # Game end condition if snake_position[0] < 0 or snake_position[0] > window_x-10: game_over() if snake_position[1] < 0 or snake_position[1] > window_y-10: game_over() # Touch the snake for block in snake_body[1:]: if snake_position[0] == block[0] and snake_position[1] == block[1]: game_over() # Continuous display of scores show_score(1, white, 'times new roman', 20) # Refresh game screen pygame.display.update() # Frames per second / refresh rate fps.tick(snake_speed)
The following is the implementation
Quick summary - Python Snake game
In fact, the source code has been listed, but there must be some small partners who want to get the complete code directly. If they need it, they can leave a message in the comment area. For the time being, they haven't put it on GitHub. If they put it directly in the article, they feel that the code is too long
This article is a series of articles. We will continue to update the games made by Python, Java, HTML, etc. I hope this series of tutorials can help you. Bloggers are also learning. If there are any mistakes, please criticize and correct them. If you like this article and are interested in seeing more of it, you can check out my CSDN home page here: Hai Yong And GitHub repositories: Github Here is a summary of all my original works and source code. Follow me to see more information.
๐งต More related articles
If you really learn something new from this article, like it, collect it and share it with your little friends. ๐ค Finally, don't forget โค or ๐ Support