Python is each enjoyable and simple to make use of. With a variety of libraries accessible, Python makes our lives simpler by simplifying the creation of video games and functions. On this article, we’ll create a basic sport that many people have doubtless performed in some unspecified time in the future in our lives – the snake sport. Should you haven’t skilled this sport earlier than, now’s your likelihood to discover and craft your very personal model with out the necessity to set up heavy libraries in your system. All it’s essential get began on making this nostalgic snake sport is a primary understanding of Python and a web-based coding editor like repl.it.
The snake sport is a timeless arcade basic the place the participant controls a snake that grows in size because it consumes meals. On this implementation, let’s break down the code to grasp how the sport is structured and the way the Turtle library is used for graphics and consumer interplay.
Utilizing Turtle Graphics for Easy Recreation Growth
The Turtle graphics library in Python gives a enjoyable and interactive technique to create shapes, draw on the display screen, and reply to consumer enter. It’s usually used for instructional functions, instructing programming ideas via visible suggestions. This code makes use of Turtle to create the sport components such because the snake, meals, and rating show.
On-line coding editor: Repl.it
An internet coding platform referred to as Repl.it permits you to develop, run, and collaborate on code instantly inside your internet browser. It helps many alternative programming languages and has built-in compilers and interpreters along with options like code sharing, model management, and teamwork. Builders extensively use it for studying, quick prototyping, and code sharing as a result of it’s easy to make use of and requires no setup.
Algorithm
Allow us to begin constructing our first sport with python. For doing so we have to comply with sure steps beneath:

Step1: Putting in the required libraries
This marks the preliminary step in creating the sport generally known as Snake. Turtle, random, and time are amongst of those.
- Turtle: We want this library to create the graphics in our sport. We’re capable of manipulate the actions of the meals and snake on the display screen and draw them.
- Random: To create random places for the meals on the display screen, we make the most of the random library. This ensures that each time the meals is eaten, it seems in a distinct place.
- Time: The snake strikes with a slight delay between every motion because of the time library. This makes the sport simpler to function and extra satisfying for gamers.
import turtle
import time
import random
Step2: Establishing the sport surroundings.
This consists of establishing the display screen’s dimensions, including a blue background, and including a small delay to make sure fluid gameplay. We additionally arrange variables like high_score to retain the very best rating attained, rating to watch the participant’s rating, and segments to trace the snake’s physique.
# Initialize the display screen
sc = turtle.Display()
sc.bgcolor("blue")
sc.setup(peak=1000, width=1000)
delay = 0.1
# Initialize variables
segments = []
rating = 0
high_score = 0

Step3: Creating the snake
A turtle object with a sq. type symbolizes the snake. We find the pen on the heart of the display screen (goto(0, 100)), set its shade to black, then elevate it to keep away from drawing strains. Initially set to “cease”, the snake’s route stays stationary till the participant begins to maneuver it.
# Create the snake
snake = turtle.Turtle()
snake.form("sq.")
snake.shade("black")
snake.penup()
snake.goto(0, 100)
snake.route = "cease"

Step4: Motion Features
We outline the snake’s motion features (transfer()) in response to its route at that second. These features management the snake’s capacity to maneuver up, down, left, and proper. They transfer the pinnacle of the snake 20 items within the applicable route when requested.
# Features to maneuver the snake
def transfer():
if snake.route == "up":
y = snake.ycor()
snake.sety(y + 20)
if snake.route == "down":
y = snake.ycor()
snake.sety(y - 20)
if snake.route == "left":
x = snake.xcor()
snake.setx(x - 20)
if snake.route == "proper":
x = snake.xcor()
snake.setx(x + 20)
Step5: Controlling the Snake
Utilizing sc.hear() and sc.onkey(), we configure key listeners to regulate the snake. The associated routines (go_up(), go_down(), go_left(), go_right()) alter the snake’s route in response to key presses on the w, s, a, or d keyboard.
# Features to hyperlink with the keys
def go_up():
snake.route = "up"
def go_down():
snake.route = "down"
def go_left():
snake.route = "left"
def go_right():
snake.route = "proper"
# Hear for key inputs
sc.hear()
sc.onkey(go_up, "w")
sc.onkey(go_down, "s")
sc.onkey(go_left, "a")
sc.onkey(go_right, "d")
Step6: Creating the Meals
The meals is represented by a round turtle object with a pink shade. Initially positioned at coordinates (100, 100), it serves because the goal for the snake to eat. When the snake collides with the meals, it “eats” the meals, and a brand new one seems at a random location.
# Create the meals
meals = turtle.Turtle()
meals.form("circle")
meals.shade("pink")
meals.penup()
meals.goto(100, 100)

Step7: Displaying Rating
A turtle object (pen) shows the participant’s rating and the very best rating achieved. This info updates every time the snake eats the meals.
# Create the rating show
pen = turtle.Turtle()
pen.penup()
pen.goto(0, 100)
pen.hideturtle()
pen.write("Rating: 0 Excessive Rating: 0", align="heart", font=("Arial", 30, "regular")

Step8: Important Recreation Loop
The core of the Snake sport is the first sport loop. It manages consumer enter, updates the display screen, strikes the snake, appears to be like for collisions, and regulates how the sport performs out. Let’s study the particular features of every part of the primary loop in additional element:
whereas True:
sc.replace() # Replace the display screen
transfer() # Transfer the snake
time.sleep(delay) # Introduce a slight delay for clean gameplay
- sc.replace() : updates the display screen to replicate any adjustments made within the sport. With out this, the display screen wouldn’t refresh, and gamers wouldn’t see the snake transfer or the rating replace.
transfer()
: This operate controls the snake’s motion primarily based on its present route. It strikes the snake’s head by 20 items within the route specified by the participant’s enter. The snake constantly strikes within the route it was final directed till the participant adjustments its route.- time.sleep(delay): introduces a slight delay between every motion of the snake. The
delay
variable is ready to0.1
initially of the code. The aim of this delay is to regulate the pace of the sport. With out it, the snake would transfer too shortly for the participant to react, making the sport tough to play.
Consuming Meals and Rising the Snake
if snake.distance(meals) < 20:
x = random.randint(-200, 200)
y = random.randint(-200, 200)
meals.penup()
meals.goto(x, y)
meals.pendown()
# Improve the size of the snake
new_segment = turtle.Turtle()
new_segment.form("sq.")
new_segment.shade("gray")
new_segment.penup()
segments.append(new_segment)
rating += 1
# Replace rating and excessive rating
if rating > high_score:
high_score = rating
pen.clear()
pen.write("Rating: {} Excessive Rating: {}".format(rating, high_score), align="heart", font=("Arial", 30, "regular"))
Consuming Meals
- When the snake’s head (
snake
) comes inside a distance of 20 items from the meals (meals
), it means the snake has “eaten” the meals. - The meals’s place is then reset to a brand new random location on the display screen utilizing
random.randint()
. - This motion generates the phantasm of the meals “reappearing” in numerous spots every time it’s eaten.
Rising the snake physique
- When the snake eats the meals, the code provides a brand new section to the snake’s physique to make it develop.
- A brand new turtle object (
new_segment
) is created, which turns into a part of thesegments
record. - This record retains monitor of all of the segments that make up the snake’s physique.
- The participant’s rating is incremented (
rating += 1
) every time the snake eats meals.
Rating Updation
- After consuming meals and updating the rating, the rating show is up to date utilizing the
pen
object. - The
pen.clear()
operate clears the earlier rating show. - Then, the up to date rating and excessive rating are written to the display screen utilizing
pen.write()
.
Shifting the Snake’s Physique
for i in vary(len(segments) - 1, 0, -1):
x = segments[i - 1].xcor()
y = segments[i - 1].ycor()
segments[i].goto(x, y)
# Transfer the primary section to comply with the pinnacle
if len(segments) > 0:
x = snake.xcor()
y = snake.ycor()
segments[0].goto(x, y)
- This part of code is chargeable for making the snake’s physique comply with its head.
- It iterates via the
segments
record, ranging from the final section (len(segments) - 1
) all the way down to the second section (0
), shifting every section to the place of the section in entrance of it. - This creates the impact of the snake’s physique following the pinnacle because it strikes.
Updating the First Section (Head)
- After shifting all of the physique segments, the place of the primary section (the pinnacle) is up to date to match the present place of the snake (
snake
). - This ensures that the snake’s head continues to guide the physique because it strikes.
Finish Be aware
This code gives a primary construction for a Snake sport utilizing the Turtle graphics library. The sport entails controlling a snake to eat meals and develop longer whereas avoiding collisions with partitions and its personal tail. It’s an incredible newbie undertaking for studying about sport improvement ideas, primary Python programming, and dealing with consumer enter and graphics. Be happy to customise and develop upon this code so as to add options like collision detection, growing problem, or including ranges to make your Snake sport much more thrilling!
If you wish to be taught extra about python then enroll in our free python course.
Additionally learn our extra articles associated to python right here:
Podcast: Play in new window | Obtain