- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Private Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Walrus Operator
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Floating Points
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Conditional User Inputs
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Packing and Unpacking
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Namedtuple
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Multiple Inheritance
- Python - Multilevel Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python - Data Classes
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Warnings
- Python - Built-in Exceptions
- Python - Debugger (PDB)
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Generator Expressions
- Python - Lambda Expressions
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - Odds and Ends
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python - Domain Specific Language (DSL)
- Python - Data Model
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Snake Game Using pygame Module
The snake game is one of the most ancient games which were introduced on arcade and accepted by generations of people who prefer playing. In this tutorial, we'll learn to develop a simple snake game with start screen, bordered play area and working snake.
Installations
First, you have to install pygame module. The pygame is a Python library that is used for developing games. You can install it using pip −
pip install pygame
Python Code to Design Snake Game
Here is the complete code to design snake game using pygame module −
import pygame
import time
import random
# Initialize Pygame
pygame.init()
# Define colors
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# Define display dimensions
dis_width = 800
dis_height = 600
# Create the display
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.setCaption('Snake Game by Souvik')
# Set the clock for controlling the game speed
clock = pygame.time.Clock()
# Define snake block size and speed
snake_block = 10
snake_speed = 15
# Define font style and size
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
# Function to display the score
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
# Function to draw the snake
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])
# Function to display message
def message(msg, color, position):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, position)
# Start screen
def start_screen():
start = True
while start:
dis.fill(blue)
message("Welcome to Snake Game", white, [dis_width / 6, dis_height / 3])
message("Press S to Start or Q to Quit", white, [dis_width / 6, dis_height / 2])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
if event.key == pygame.K_s:
start = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
# The game loop
def gameLoop():
start_screen()
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
# Generate food coordinates
foodx = round(random.randrange(10, dis_width - snake_block - 10) / 10.0) * 10.0
foody = round(random.randrange(10, dis_height - snake_block - 10) / 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, [dis_width / 6, dis_height / 3])
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 - 10 or x1 < 10 or y1 >= dis_height - 10 or y1 < 10:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
# Draw the border
pygame.draw.rect(dis, white, [10, 10, dis_width - 20, dis_height - 20], 5)
# Draw the food
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
# Move the snake
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(10, dis_width - snake_block - 10) / 10.0) * 10.0
foody = round(random.randrange(10, dis_height - snake_block - 10) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# Run the game
gameLoop()
Code Explanation
Some of the procedures used in developing the game are as follows −
- Initialize pygame − The basics, to begin with, one has to import pygame and then start it up with init().
- Set Up the Display − Clear the screen size and obtain the size of the window to be used in displaying the content.
- Define Colors and Fonts − Include all the colors that is to be used in the game and all the fonts to be used for the textual part of the game.
- Create the Start Screen − The start_screen() function prints a message to the console with information to the player starting soon and waits for the user’s input to begin the game.
- Game Loop − The gameLoop() function deals with the motion, check for collision, and scoring of points. It has logic that helps in controlling the snake, creation of the food and determination of when the game is over.
- Bordered Play Area − Since pygame is used here to design the play area, a white border is created around the area. draw. bend it as well so that the snake cannot escape the area that has been enclosed by the stick.
- End the Game − This continues till the snake hits the border or even the snake’s own tail; thus, the game is over. At the end of the game the player can decide to play the game again or quit.
Output
When you run the game, you'll start with a welcome screen prompting you to press 'S' to start the game or 'Q' to quit.
Once the game starts, the snake will move inside a bordered area. The goal is to eat the food (green block) and grow the snake while avoiding collisions with the walls or the snake's own body.
After game is over you can play again or quit option