etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Python snake game code with Pygame

In this article, you will learn how to develop a snake game program using Python Pygame. We hope you have played the snake game. This is one of the loveliest games for kids. Have you thought? How to develop this game? Here, we have mentioned the step-by-step process for developing the snake game.





Install Pygame

Pygame is totally dependent on Python. We hope Python is already available on your system, and if you do not have it, first install the latest version of Python. Pygame is a cross-platform set of Python modules designed for composing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. The given command instals the pygame using the pip tool.

pip install pygame


Import required modules

In Python, all the necessary modules of the project need to be imported at the top. We have included the following modules for the snake game development and initialised the pygame using the pygame.init() method.

import pygame, time, random
pygame.init()
…….
…..
pygame.quit()
quit()

Finally, we need to uninitialised everything. So, we have used the quit() method at the end of the code.





Create the screen and set caption

The pygame.display.set_mode() function is used to create the screen surface and return the surface object. The set_mode() function accepts two arguments width and height of the window, and pygame.display.set_caption() function sets the window screen caption.

width = 700
height = 500
 
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Python Snake Game by Etutorialspoint')


Define the Clock

The pygame.time.Clock() function helps us to create an object for tracking time.

clock = pygame.time.Clock()


Create the snake

We have used the pygame.draw.rect() method to draw the rectangle that represents the snake. It doubles every time with the new score. The '[x[0], x[1], snake_block, snake_block]' defines the position and dimension of the snake.

snake_color = (0, 0, 0)
snake_block = 10

def snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, snake_color, [x[0], x[1], snake_block, snake_block])




Move the snake

To move the snake, we need key input from the user. The pygame KEYDOWN class gets the event when the keyword buttons are pressed. The events that we have used here are K_LEFT, K_RIGHT, K_UP, and K_DOWN. These keys represent the arrow keys to move the snake left, right, up and down.

while game_close == True:    
   game_over = False
    game_close = False

    x1 = width / 2
    y1 = height / 2
 
    x1_move = 0
    y1_move = 0

 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_move = -snake_block
                    y1_move = 0
                elif event.key == pygame.K_RIGHT:
                    x1_move = snake_block
                    y1_move = 0
                elif event.key == pygame.K_UP:
                    y1_move = -snake_block
                    x1_move = 0
                elif event.key == pygame.K_DOWN:
                    y1_move = snake_block
                    x1_move = 0


Game Over: when users hit the boundaries

When the snake hits any boundary of the window, the user loses the game. For this, we have defined a variable game_close. When it is set to TRUE, it asks you to either play again or quit the game.

if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
        game_close = True

while game_close == True:
            screen.fill(green)
            message("You Lost The Game! Press A to Play Again OR Q to Quit", red)
            total_score(snake_length - 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_a:
                        main()




Create snake food

We have created the snake food using the pygame.draw.circle() method and defined it in a function draw_food. The x and y attributes are the position of the food.

def draw_food(x, y, radius):
    pygame.draw.circle(screen, food_color, [int(x), int(y)], radius)


Increasing the length of the snake

We have increased the size of the snake when it eats food. The variable snake_length contains the length of the snake, and snake_list contains the coordinates of the snake. We have defined a new list, snake_head which will be appended to the snake_list to increase the snake length.

        foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10
        foody = round(random.randrange(0, height - snake_block) / 10.0) * 10
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)

        if len(snake_list) > snake_length:
            del snake_list[0]
 
        for x in snake_list[:-1]:
            if x == snake_head:
                game_close = True
 
        snake(snake_block, snake_list)
        total_score(snake_length - 1)
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
            snake_length += 1




Define message

Here, we have defined a message to display when the game over.

# Display message when Game Over 
def message(msg, color):
    mesg = msg_font.render(msg, True, color)
    screen.blit(mesg, [width / 10, height / 3])




Complete Code: Python snake game with pygame

Above, we have explained the snake game code in chunks. Here, we have merged them all to get the complete code.

import pygame, time, random
 
pygame.init()
 
score_color = (8, 6, 154)
snake_color = (0, 0, 0)
red = (213, 50, 80)
green = (4, 216, 2)
food_color = (218, 93, 0)
 
width = 700
height = 500
 
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Python Snake Game by Etutorialspoint')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 15
 
msg_font = pygame.font.SysFont("Courier", 20)
score_font = pygame.font.SysFont("Times New Roman", 30)
 
# Draw Snake 
def snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, snake_color, [x[0], x[1], snake_block, snake_block])

# Get Total Score
def total_score(score):
    value = score_font.render("Total Score: " + str(score), True, score_color)
    screen.blit(value, [0, 0])        

# Display message when Game Over 
def message(msg, color):
    mesg = msg_font.render(msg, True, color)
    screen.blit(mesg, [width / 10, height / 3])

# Draw Food
def draw_food(x, y, radius):
    pygame.draw.circle(screen, food_color, [int(x), int(y)], radius)
 
# Main Game Loop 
def main():
    game_over = False
    game_close = False
 
    x1 = width / 2
    y1 = height / 2
 
    x1_move = 0
    y1_move = 0
 
    snake_list = []
    snake_length = 1
 
    foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10
    foody = round(random.randrange(0, height - snake_block) / 10.0) * 10
 
    while not game_over:
 
        while game_close == True:
            screen.fill(green)
            message("You Lost The Game! Press A to Play Again OR Q to Quit", red)
            total_score(snake_length - 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_a:
                        main()
 
        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_move = -snake_block
                    y1_move = 0
                elif event.key == pygame.K_RIGHT:
                    x1_move = snake_block
                    y1_move = 0
                elif event.key == pygame.K_UP:
                    y1_move = -snake_block
                    x1_move = 0
                elif event.key == pygame.K_DOWN:
                    y1_move = snake_block
                    x1_move = 0
 
        if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
            game_close = True
        x1 += x1_move
        y1 += y1_move

        # Fill Screen Background
        screen.fill(green)
        
        draw_food(foodx, foody, 6)
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)
        if len(snake_list) > snake_length:
            del snake_list[0]
 
        for x in snake_list[:-1]:
            if x == snake_head:
                game_close = True
 
        snake(snake_block, snake_list)
        total_score(snake_length - 1)
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
            snake_length += 1
 
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
# Call Main Game Loop 
main()

When, you will run the above code, it returns the following -

Your browser does not support the video tag.



Related Articles

Convert list to dictionary Python
Dictionary inside list Python
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python JSON Tutorial - Create, Read, Parse JSON file
How to draw different shapes using Python Pygame
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
How to encrypt password in PHP
-----------------
Characteristics of a Good Computer Program
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple way to send SMTP mail using Node.js
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Simple PHP File Cache
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
To check whether a year is a leap year or not in php
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.