• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
Wednesday, February 11, 2026
newsaiworld
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
Morning News
No Result
View All Result
Home Artificial Intelligence

Implementing the Snake Sport in Python

Admin by Admin
February 11, 2026
in Artificial Intelligence
0
Snake.jpg
0
SHARES
2
VIEWS
Share on FacebookShare on Twitter

READ ALSO

The Proximity of the Inception Rating as an Analysis Criterion

The Loss of life of the “All the pieces Immediate”: Google’s Transfer Towards Structured AI


cellphone my mom had is carefully associated to the sport it had. Sure, the classical snake sport, so easy but so addicting. I bear in mind enjoying this sport on finish on my mom’s telephone, shedding after which attempting time and again!

On this article, we’ll study to construct a easy Snake Sport. We’ll use Python’s turtle module to be able to generate this sport. Notice that this can be a inexperienced persons to intermediate stage Python tutorial, and expects the reader to be accustomed to Python fundamentals reminiscent of features and loops, importing and accessing modules, and utilizing conditional statements. It additionally requires one to have a surface-level understanding of Object Oriented Programming, particularly creating objects cases from lessons. For the sake of simplicity, I’ll clarify every line of code. Let’s get began!

Snake Sport (Picture by Creator)

Understanding the Sport

The classical Snake sport includes a small snake with a plain background. Meals is supplied on the display. Because the snake eats the meals, it grows in dimension, and the rating will increase. As quickly because the snake collides with the boundary wall or itself, the sport ends, and one loses.

With the intention to code this sport in Python, we might want to deal with the next factors:

  1. Establishing the Sport Display – within the classical Snake sport, the background is a uninteresting neon yellow-green display
  2. Creating the Snake physique – the sport begins with a small black snake, which steadily will increase in dimension because it eats the meals
  3. Transferring the Snake – the snake can transfer within the 4 instructions: up, down, left, and proper by way of the arrow keys on the keyboard or corresponding buttons on the telephone
  4. Creating the Meals – the meals for the snake seems at random places on the display
  5. The Snake consuming the Meals – because the snake’s physique collides with the meals created, the rating is elevated in addition to the size of the snake, and new meals is generated randomly, and the sport continues.
  6. The Snake Colliding with itself or the Boundary Wall – if the snake’s physique collides with itself or the boundary of the sport display, the sport ends.

Allow us to begin coding.

Establishing the Sport Display

First issues first, we’ll create a brand new mission in our IDE, let’s name it “Snake Sport”. I’m utilizing PyCharm to code. Subsequent, we’ll create a brand new “snake sport.py” file. To begin with, we’ll import the Turtle module, particularly its Display and Turtle lessons.

from turtle import Display, Turtle

The Turtle Module is a built-in Python package deal that enables one to attract shapes, traces, patterns, and animations on a display by way of code. The module works as if there’s a turtle with a brush on its again, and no matter you command it to go to, it can go there, thereby creating drawings. You may ask the turtle to maneuver ahead, to show left by a sure angle, draw a circle and so forth. The turtle will draw precisely that, and it’s a straightforward software to visualise one’s code. It helps practising variables, loops, features, coordinates, and primary animation logic with on the spot visible outputs.

You may try the Turtle Official Documentation right here.

As will be seen within the line of code above, we’ve imported two components: Display and Turtle. These are lessons which can be outlined within the module. In Python, a category is a blueprint used to create objects. Turtle and Display are lessons which will likely be used to create corresponding objects. These objects may have attributes (variables) and strategies (features) as outlined of their blueprint, with the availability of customization.

Allow us to first create the background for our sport. We’ll use the Display class for this function and customise it based on our necessities. For reference, verify the Display strategies from the official documentation right here.

#Establishing the Sport Display
display = Display()
display.setup(width=600, peak=600)
display.bgcolor("inexperienced yellow")
display.title("Snake Sport")
display.tracer(0)

display.exitonclick()

As will be seen within the code above, we first created the display object from the Display Class. Subsequent, we’ve used the setup() methodology of the Display class and set the width of the Sport Display to 600×600. Now we have personalized the background colour to “inexperienced yellow” utilizing the bgcolor() methodology. The title of the colour will be discovered by way of this hyperlink. I chosen the colour that carefully resembled the colour within the unique sport. After that, we’ve named the display “Snake Sport” utilizing the title() methodology. The tracer() methodology from the Turtle class lets us management the animation. By giving an argument of “0”, we’ve turned it off. This will likely be higher understood after we create the snake and meals. Lastly, we’ve used the exitonclick() methodology to set the window to shut solely after we click on on it. In any other case, the window closes as quickly because it pops up and executes the entire code.

Working the code above would output the next:

The Sport Display (Picture by Creator)

Creating the Snake Physique

As soon as we’ve created the Sport Display, the following activity is to create the snake. The snake can even be created utilizing the Turtle class. We’ll create 3 turtle objects that received’t resemble a turtle in any respect. Relatively, they are going to be sq. segments, and when positioned collectively, will resemble a snake’s physique, similar to within the sport. For this function, we’ll use a for loop to create the three segments. Every section will likely be positioned at a specified place. Allow us to code this:

#Creating the Snake
segments = []
starting_positions = [(0,0), (-20,0), (-40,0)]
for place in starting_positions:
    new_segment = Turtle("sq.")
    new_segment.colour("black")
    new_segment.penup()
    new_segment.shapesize(1,1)
    new_segment.goto(place)
    segments.append(new_segment)

display.replace()

Within the code above, we first created an empty listing of segments. This listing will comprise the snake segments. As soon as the snake segments are created, it can consist of three segments, and each time the snake eats its meals, the variety of segments will improve. Now we have created a tuple starting_positions. This can comprise 3 positions specified when it comes to their x and y coordinates, and would be the positions the place the snake segments will likely be created. We’ll create the primary section at (0,0), the second at (-20,0), and the third section at (-40,0). Utilizing the for loop, we’ve created 3 segments from the variable new_segment as a turtle object, of sq. form and customary dimension 20×20. The arguments to shapesize() methodology is given as 1×1 because it stretches the scale of the drawing cursor relative to its default 20×20 pixel dimension. The penup() methodology permits us to cover the pen, and simply output the form of the turtle object. The goto() methodology permits us to create the form ranging from that place. Lastly, we’ve appended the newly created section to the empty listing we created at first of this code block. On this approach, 2 extra segments will likely be created as there are 2 extra positions within the starting_positions tuple.

Ultimately, we’ll replace our display in order that it now exhibits each the personalized display and the newly created snake. This would be the output:

Creating the Snake Physique (Picture by Creator)

Discover that we’ve created the segments utilizing simply the for loop. As we go forward in our program, we might want to improve the snake’s segments because it eats the meals. With the intention to make this addition handy to us, allow us to modify the code block and add a operate referred to as add_segments, to create the snake in addition to use it later when including segments to the snake when it eats the meals. This will likely be a greater strategy to programming within the present situation:

#Creating the Snake
segments = []
starting_positions = [(0,0), (-20,0), (-40,0)]

#Including Segments Perform
def add_segments(place):
    new_segment = Turtle("sq.")
    new_segment.colour("black")
    new_segment.penup()
    new_segment.goto(place)
    segments.append(new_segment)

for place in starting_positions:
    add_segments(place)

display.replace()

Within the above code block, we’ve carried out precisely what we have been beforehand doing, that’s, creating the snake physique, besides that we’ve used a Python operate to take action. Now we have outlined a operate referred to as add_segments, whose function is simply so as to add the segments to the snake’s physique, and the segments listing. Furthermore, now’s the place the display’s tracer() methodology comes to make use of. Should you remark out the display.tracer() line that we added within the begining you will notice the animation of the snake’s physique being created one section at a time (and we don’t need that in our sport!). This will higher be visualized by first importing the time module and utilizing the sleep() operate. The animation will likely be extra seen.

import time

#Maintain the remainder of the code similar

for place in starting_positions:
    add_segments(place)
    time.sleep(1)
display.replace()

Snake Motion

The subsequent activity is to code the snake’s motion. To start with, allow us to simply make the snake transfer ahead. We’ll first create a variable game_is_on that will likely be True so long as the sport is operating, and will likely be switched to False as soon as we lose or the sport ends. This variable will likely be used within the whereas loop. So long as the sport is on, the snake will proceed transferring, and we’ll solely have the ability to change its course utilizing the arrow keys. That is going to be the a part of our program that can hold the sport on.

Now comes the advanced half. To maneuver the snake ahead, we have to transfer all of its segments forward. The way in which to make your complete snake physique transfer ahead is by making every section, apart from the primary one, to maneuver to the one earlier than it. Which means at first, when the snake is simply 3 segments lengthy, section 3 will transfer to the place of section 2, and section 2 will transfer to the place of section 1, and section 1 will transfer ahead utilizing the turtle ahead() methodology. This may be coded within the for loop, by giving it a beginning worth of the final aspect of the listing, which is the aspect on the 2nd place (listing components begin from 0, thus 0, 1, 2) when the snake is created (having 3 segments) or in any other case calculated because the size of the segments, minus 1. The for loop will finish at place 0, and as it’s transferring in reverse, we’ll give it a step dimension of -1. This complete situation is coded as under:

game_is_on = True
whereas game_is_on:
    display.replace()
    time.sleep(0.1)
    for seg_num in vary(len(segments)-1, 0, -1):
        new_x = segments[seg_num - 1].xcor()
        new_y = segments[seg_num - 1].ycor()
        segments[seg_num].goto(new_x, new_y)
    segments[0].ahead(20)

Discover that we’ve added the display’s replace() methodology, in addition to outlined the pace of the snake utilizing the time module’s sleep() operate. By giving it an argument of 0.1, the snake segments will transfer ahead with a time delay of 0.1 seconds, and this pace will be adjusted. If given an argument of 1, the time delay will likely be 1 second, and the pace of the snake will likely be gradual. You may experiment with the snake’s pace by altering the values given to the sleep() operate.

The within of the for loop elaborates how the segments will transfer to the earlier segments’ place utilizing its coordinates. And on the finish, we’ve the primary section of our snake transferring forward by 20 utilizing the turtle’s ahead() methodology. Working our code would output a transferring snake:

Snake Transferring Ahead (Picture by Creator)

Controlling the Snake

Now that we’ve seen make the snake transfer, the following factor is to regulate the up/down/left/proper actions of the snake. For this, we’ll use the display listeners. We’ll code this system in order that on urgent the up, down, left, and proper keys, the snake will transfer accordingly by altering its head.

Another characteristic that we have to add, taking it from the unique snake sport, is that when the snake is transferring left, it can’t immediately flip proper, when it’s transferring up, it can’t immediately flip downwards. In brief, the snake can’t flip 180 levels from the place it’s transferring. Allow us to add this characteristic to our code. Ensure that so as to add these traces of code earlier than the sport’s whereas loop we coded earlier.


#Controlling the Snake
display.pay attention()
def turn_up():
    if segments[0].heading() != 270:
        segments[0].setheading(90)
def turn_down():
    if segments[0].heading() != 90:
        segments[0].setheading(270)
def turn_left():
    if segments[0].heading() != 0:
        segments[0].setheading(180)
def turn_right():
    if segments[0].heading() != 180:
        segments[0].setheading(0)

display.onkey(turn_up, "Up")
display.onkey(turn_down, "Down")
display.onkey(turn_left, "Left")
display.onkey(turn_right, "Proper")

As will be seen above, we first used the display’s pay attention() methodology that lets us take heed to the display’s enter keys. Subsequent, we’ve outlined features which will likely be referred to as later within the display’s onkey() methodology, which calls a operate based mostly on a keyboard key pressed. Now we have outlined 4 features, every to show to a course apart from the exact opposite, utilizing the turtle’s methodology setheading(). This methodology units the pinnacle of the turtle, which is the primary section or section[0] to 0, 90, 180, or 270, that’s, proper, up, left, or down. The if conditional statements in every operate ensure that the snake doesn’t flip in its other way, as we are able to see within the unique sport.

Working the whole code with this code block addition will allow us to transfer our snake:

Controlling Snake’s Motion with Arrow Keys (Picture by Creator)

Meals Creation

As soon as the snake has been created and programmed to maneuver utilizing the arrow keys, the following activity is to create the meals which the snake will eat and develop. This meals can even be created as a turtle object in a round form, in purple. We’ll set the shapesize to 0.5 so the meals is 10×10 pixels on the display. Now we have additionally set the pace() to “quickest” so the animation is quick, and there’s no delay in meals creation. Right here, we’ll import Python’s random module to create the meals at random positions on the sport display. Now we have set the boundary of meals as -275 to 275 on each the x and y axes. That is in order that it’s simpler for the snake to eat its meals with out colliding with the outer display boundary.

Furthermore, each time the snake eats its meals, new meals must be generated. For this function, we’ll outline a operate refresh() and generate new random coordinates the place the turtle object referred to as meals will transfer to. Try the code under:

#Creating the Meals
import random
meals = Turtle()
meals.colour("purple")
meals.form("circle")
meals.penup()
meals.shapesize(stretch_len=0.5, stretch_wid=0.5)
meals.pace("quickest")
random_x = random.randint(-275, 275)
random_y = random.randint(-275, 275)
meals.goto(random_x, random_y)

def refresh():
    random_x = random.randint(-275, 275)
    random_y = random.randint(-275, 275)
    meals.goto(random_x, random_y)
Meals Creation (Picture by Creator)

Detect Collision with Meals

As soon as we’ve created the meals, we now need to create a mechanism whereby the snake eats the meals. Which means each time the snake touches the meals, the meals vanishes, and the snake grows by one section. We’ll code this situation such that each time the snake and meals are in shut proximity, in order that their distance is lower than 15, it means the snake has eaten the meals. We’ll make use of the turtle module’s distance() methodology that calculates the gap between a turtle and a particular level or one other turtle object. If this distance is lower than 15 (by way of trial and error), it might imply the snake has touched or eaten its meals, and the meals ought to now transfer to a brand new location for sport continuity. Therefore, we’ll now name the refresh() operate that we outlined earlier to maneuver the meals object to a brand new location. Consuming the meals ought to improve the snake’s dimension by a section. For this, we’ll outline a operate referred to as prolong() exterior the whereas loop and name it contained in the if conditional assertion when the snake eats the meals.

#Snake extending
def prolong():
    add_segments(segments[-1].place())

As will be seen, the prolong() operate will add a brand new section to the final section of the snake’s physique. Now transferring on to the principle sport’s loop:


game_is_on = True
whereas game_is_on:
    ...
    #Retain the unique code right here
    ...
    #Detect Collision with Meals
    if segments[0].distance(meals) < 15:
        refresh()
        prolong()
Snake Consuming Meals and Extending (Picture by Creator)

Scoreboard and Rating Updation

Subsequent is to create a scoreboard that may show the rating. To do that, we’ll code exterior the whereas loop. We’ll create this scoreboard and the rating as 2 turtle objects utilizing turtle’s write() methodology, which permits us to show textual content on display. First, we’ll initialize a variable referred to as rating as 0. Because the snake eats its meals, the rating variable will likely be elevated by 1 every time. Subsequent, we’ll create 2 turtle cases, scoreboard and my_score. The scoreboard object will show the textual content on display “Rating = “, whereas the my_score object will show the rating variable, which is able to change because the snake eats its meals. As will be seen within the code under, each of those turtle objects have been personalized for the display textual content show based on the necessity.

#Creating the Scoreboard & Rating
rating = 0

scoreboard = Turtle()
scoreboard.colour("black")
scoreboard.penup()
scoreboard.hideturtle()
scoreboard.goto(0,250)
scoreboard.write("Rating = ", True, align="heart", font=("Arial", 12, "regular"))

my_score = Turtle()
my_score.colour("black")
my_score.penup()
my_score.hideturtle()

As soon as we’ve created the above, we’ll now proceed so as to add the availability of fixing the core throughout the whereas loop of the sport, contained in the if conditional assertion when the snake collides with the meals. Examine the code under and replace the precise traces of code:

game_is_on = True
whereas game_is_on:
    ...
    #Retain the unique code right here
    ...
    #Detect Collision with Meals
    if segments[0].distance(meals) < 20:
        refresh()
        prolong()
        rating = rating + 1
        my_score.goto(40, 250)
        my_score.clear()
        my_score.write(rating, True, align="heart", font=("Arial", 12, "regular"))

The next is displayed on the display after operating this system with the above additions:

Scoreboard and Rating Show (Picture by Creator)

Sport Ending

When the sport ends, we have to inform the consumer that the sport is over, quite than simply closing the show display. For this we’ll outline a operate and name it each time the sport ends: both by collision with a wall or by collision with tail. We’ll use the turtle object for this as effectively. That is the operate, and will probably be referred to as when game_is_on variable turns to False.

#Sport Over Pop Up
def game_over():
    game_over = Turtle()
    game_over.colour("black")
    game_over.penup()
    game_over.hideturtle()
    game_over.write("GAME OVER", True, align="heart", font=("Arial", 40, "regular"))

Detect Collision with Wall

One other situation of the sport’s continuity is to verify the snake doesn’t collide with the boundary wall of the display. With the intention to code this, and figuring out that the sport’s display is 600×600, we’ll contemplate the boundary wall a sq. with its corners to be at these factors: (290, 290), (290, -290), (-290, -290) and (-290, 290). The wall detection block will likely be throughout the sport loop in a separate if conditional assertion as follows:

game_is_on = True
whereas game_is_on:
    ...
    #Retain the unique code right here
    ... 
    # Detect Collision with Wall
    if segments[0].xcor() > 290 or segments[0].xcor() < -290 or segments[0].ycor() > 290 or segments[0].ycor() < -290:
        game_is_on = False
        game_over()
 

Within the above traces of code, we’ve accessed the x and y coordinates of the primary section of the snake and checked whether or not it falls inside or exterior of the boundary wall.

Detect Collision with Tail

Lastly, we’ll finish this program with one other situation of the sport, which is that if the snake’s head collides with itself, that’s, the primary section collides with every other section, the sport ends. We’ll use the for loop to code this situation:

game_is_on = True
whereas game_is_on:
    ...
    #Retain the unique code right here
    ...   
    # Detect Tail Collision
    for section in segments[1:]:
        if segments[0].distance(section) < 10:
            game_is_on = False
            game_over()
 

When the sport ends, we have to inform the consumer that the sport is over, quite than simply closing the show display. For this, we’ll name the game_over operate we outlined earlier.

Sport Over (Picture by Creator)

Conclusion

On this tutorial, we’ve efficiently applied the snake sport in Python. Now we have used our understanding of Python fundamentals, reminiscent of defining and calling features, utilizing lists and tuples, utilizing for and whereas loops in addition to conditional statements. Now we have additionally applied our primary understanding of Object Oriented Programming to create objects from a module’s lessons. When you’ve got any queries concerning any piece of code or a suggestion to make the code extra sturdy and environment friendly, be at liberty to remark and share your concepts. Till then, code, play, and problem your pals to the Snake Sport you’ve got designed!

Tags: GameimplementingPythonSnake

Related Posts

Image 184.jpg
Artificial Intelligence

The Proximity of the Inception Rating as an Analysis Criterion

February 10, 2026
Chatgpt image jan 6 2026 02 46 41 pm.jpg
Artificial Intelligence

The Loss of life of the “All the pieces Immediate”: Google’s Transfer Towards Structured AI

February 9, 2026
Title 1 scaled 1.jpg
Artificial Intelligence

Plan–Code–Execute: Designing Brokers That Create Their Personal Instruments

February 9, 2026
Annie spratt kdt grjankw unsplash.jpg
Artificial Intelligence

TDS E-newsletter: Vibe Coding Is Nice. Till It is Not.

February 8, 2026
Jonathan chng hgokvtkpyha unsplash 1 scaled 1.jpg
Artificial Intelligence

What I Am Doing to Keep Related as a Senior Analytics Marketing consultant in 2026

February 7, 2026
Cover.jpg
Artificial Intelligence

Pydantic Efficiency: 4 Tips about Validate Massive Quantities of Information Effectively

February 7, 2026
Next Post
Cloud mining bitcoin mobile 5.jpg

Methods to Win the Customized Mansory Jesko Spartans Version – CryptoNinjas

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

Chainlink Link And Cardano Ada Dominate The Crypto Coin Development Chart.jpg

Chainlink’s Run to $20 Beneficial properties Steam Amid LINK Taking the Helm because the High Creating DeFi Challenge ⋆ ZyCrypto

May 17, 2025
Image 100 1024x683.png

Easy methods to Use LLMs for Highly effective Computerized Evaluations

August 13, 2025
Gemini 2.0 Fash Vs Gpt 4o.webp.webp

Gemini 2.0 Flash vs GPT 4o: Which is Higher?

January 19, 2025
Blog.png

XMN is accessible for buying and selling!

October 10, 2025
0 3.png

College endowments be a part of crypto rush, boosting meme cash like Meme Index

February 10, 2025

EDITOR'S PICK

Bitcoin needs to drop down to 8000 for 5 years to jeopardize balance sheet strategy inc 2 1.webp.webp

Technique Says Steadiness Sheet Secure Till BTC Hits $8K for 5Yrs

February 9, 2026
1qv7ftzi8rjyor4kztokpbw.png

LangChain’s Father or mother Doc Retriever — Revisited | by Omri Eliyahu Levy

November 22, 2024
Red.jpg

R.E.D.: Scaling Textual content Classification with Professional Delegation

March 21, 2025
Cnj okx referral code featured image.png

Steps to Signal Up and Earn Bonus in 2026

January 17, 2026

About Us

Welcome to News AI World, your go-to source for the latest in artificial intelligence news and developments. Our mission is to deliver comprehensive and insightful coverage of the rapidly evolving AI landscape, keeping you informed about breakthroughs, trends, and the transformative impact of AI technologies across industries.

Categories

  • Artificial Intelligence
  • ChatGPT
  • Crypto Coins
  • Data Science
  • Machine Learning

Recent Posts

  • Methods to Win the Customized Mansory Jesko Spartans Version – CryptoNinjas
  • Implementing the Snake Sport in Python
  • The right way to Mannequin The Anticipated Worth of Advertising Campaigns
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

© 2024 Newsaiworld.com. All rights reserved.

No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us

© 2024 Newsaiworld.com. All rights reserved.

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?