Close Menu
    Trending
    • AI algorithm enables tracking of vital white matter pathways | MIT News
    • A “QuitGPT” campaign is urging people to cancel their ChatGPT subscription
    • How to Model The Expected Value of Marketing Campaigns
    • Pain Points, Fixes, and Best Practices
    • Implementing the Snake Game in Python
    • How to Personalize Claude Code
    • 3 Questions: Using AI to help Olympic skaters land a quint | MIT News
    • How a Human-in-the-Loop Approach Improves AI Data Quality
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » Implementing the Snake Game in Python
    Artificial Intelligence

    Implementing the Snake Game in Python

    ProfitlyAIBy ProfitlyAIFebruary 10, 2026No Comments19 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    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, dropping after which making an attempt many times!

    On this article, we are going to study to construct a easy Snake Sport. We are going to use Python’s turtle module in an effort to generate this sport. Be aware that it is a newbies to intermediate stage Python tutorial, and expects the reader to be acquainted with Python fundamentals akin to 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 courses. For the sake of simplicity, I’ll clarify every line of code. Let’s get began!

    Snake Sport (Picture by Writer)

    Understanding the Sport

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

    In an effort to code this sport in Python, we might want to handle the next factors:

    1. Organising the Sport Display – within the classical Snake sport, the background is a boring neon yellow-green display screen
    2. Creating the Snake physique – the sport begins with a small black snake, which steadily will increase in measurement because it eats the meals
    3. Shifting the Snake – the snake can transfer within the 4 instructions: up, down, left, and proper by the arrow keys on the keyboard or corresponding buttons on the telephone
    4. Creating the Meals – the meals for the snake seems at random areas on the display screen
    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 screen, the sport ends.

    Allow us to begin coding.

    Organising the Sport Display

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

    from turtle import Display, Turtle

    The Turtle Module is a built-in Python package deal that permits one to attract shapes, strains, patterns, and animations on a display screen by 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 is going to go there, thereby creating drawings. You possibly can ask the turtle to maneuver ahead, to show left by a sure angle, draw a circle and so on. The turtle will draw precisely that, and it’s a simple software to visualise one’s code. It helps practising variables, loops, features, coordinates, and fundamental animation logic with on the spot visible outputs.

    You possibly can try the Turtle Official Documentation here.

    As might be seen within the line of code above, now we have imported two components: Display and Turtle. These are courses which are outlined within the module. In Python, a category is a blueprint used to create objects. Turtle and Display are courses 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 are going to use the Display class for this objective and customise it in keeping with our necessities. For reference, test the Display strategies from the official documentation here.

    #Organising the Sport Display
    display screen = Display()
    display screen.setup(width=600, top=600)
    display screen.bgcolor("inexperienced yellow")
    display screen.title("Snake Sport")
    display screen.tracer(0)
    
    display screen.exitonclick()

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

    Operating the code above would output the next:

    The Sport Display (Picture by Writer)

    Creating the Snake Physique

    As soon as now we have created the Sport Display, the following activity is to create the snake. The snake may also be created utilizing the Turtle class. We are going to create 3 turtle objects that gained’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 objective, we are going to 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 screen.replace()

    Within the code above, we first created an empty record of segments. This record will comprise the snake segments. As soon as the snake segments are created, it is going to consist of three segments, and at any time when the snake eats its meals, the variety of segments will improve. We’ve 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 are going to create the primary section at (0,0), the second at (-20,0), and the third section at (-40,0). Utilizing the for loop, now we have created 3 segments from the variable new_segment as a turtle object, of sq. form and customary measurement 20×20. The arguments to shapesize() methodology is given as 1×1 because it stretches the dimensions of the drawing cursor relative to its default 20×20 pixel measurement. 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, now we have appended the newly created section to the empty record we created to start with of this code block. On this means, 2 extra segments will likely be created as there are 2 extra positions within the starting_positions tuple.

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

    Creating the Snake Physique (Picture by Writer)

    Discover that now we have 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. In an effort to make this addition handy to us, allow us to modify the code block and add a perform 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 method to programming within the present state of affairs:

    #Creating the Snake
    segments = []
    starting_positions = [(0,0), (-20,0), (-40,0)]
    
    #Including Segments Operate
    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 screen.replace()

    Within the above code block, now we have executed precisely what we had been beforehand doing, that’s, creating the snake physique, besides that now we have used a Python perform to take action. We’ve outlined a perform referred to as add_segments, whose objective is simply so as to add the segments to the snake’s physique, and the segments record. Furthermore, now’s the place the display screen’s tracer() methodology comes to make use of. If you happen to remark out the display screen.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 could higher be visualized by first importing the time module and utilizing the sleep() perform. The animation will likely be extra seen.

    import time
    
    #Hold the remainder of the code similar
    
    for place in starting_positions:
        add_segments(place)
        time.sleep(1)
    display screen.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 are going to 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 shifting, and we are going to solely have the ability to change its path utilizing the arrow keys. That is going to be the a part of our program that may maintain 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 the complete snake physique transfer ahead is by making every section, apart from the primary one, to maneuver to the one earlier than it. Because of this originally, 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 ingredient of the record, which is the ingredient on the 2nd place (record 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 shifting in reverse, we are going to give it a step measurement of -1. This complete state of affairs is coded as beneath:

    game_is_on = True
    whereas game_is_on:
        display screen.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 now we have added the display screen’s replace() methodology, in addition to outlined the pace of the snake utilizing the time module’s sleep() perform. 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 might 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 sluggish. You possibly can experiment with the snake’s pace by altering the values given to the sleep() perform.

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

    Snake Shifting Ahead (Picture by Writer)

    Controlling the Snake

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

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

    
    #Controlling the Snake
    display screen.hear()
    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 screen.onkey(turn_up, "Up")
    display screen.onkey(turn_down, "Down")
    display screen.onkey(turn_left, "Left")
    display screen.onkey(turn_right, "Proper")

    As might be seen above, we first used the display screen’s hear() methodology that lets us take heed to the display screen’s enter keys. Subsequent, now we have outlined features which will likely be referred to as later within the display screen’s onkey() methodology, which calls a perform based mostly on a keyboard key pressed. We’ve outlined 4 features, every to show to a path 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 perform be sure that the snake doesn’t flip in its wrong way, as we are able to see within the authentic sport.

    Operating the entire code with this code block addition will allow us to transfer our snake:

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

    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 may also be created as a turtle object in a round form, in crimson. We are going to set the shapesize to 0.5 so the meals is 10×10 pixels on the display screen. We’ve additionally set the pace() to “quickest” so the animation is quick, and there’s no delay in meals creation. Right here, we are going to import Python’s random module to create the meals at random positions on the sport display screen. We’ve 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 screen boundary.

    Furthermore, at any time when the snake eats its meals, new meals must be generated. For this objective, we are going to outline a perform refresh() and generate new random coordinates the place the turtle object referred to as meals will transfer to. Try the code beneath:

    #Creating the Meals
    import random
    meals = Turtle()
    meals.colour("crimson")
    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 Writer)

    Detect Collision with Meals

    As soon as now we have created the meals, we now need to create a mechanism whereby the snake eats the meals. Because of this at any time when the snake touches the meals, the meals vanishes, and the snake grows by one section. We are going to code this state of affairs such that at any time when 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 are going to make use of the turtle module’s distance() methodology that calculates the space between a turtle and a particular level or one other turtle object. If this distance is lower than 15 (by trial and error), it could 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 are going to now name the refresh() perform that we outlined earlier to maneuver the meals object to a brand new location. Consuming the meals ought to improve the snake’s measurement by a section. For this, we are going to outline a perform referred to as prolong() outdoors 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 might be seen, the prolong() perform will add a brand new section to the final section of the snake’s physique. Now shifting 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 Writer)

    Scoreboard and Rating Updation

    Subsequent is to create a scoreboard that might show the rating. To do that, we are going to code outdoors the whereas loop. We are going to create this scoreboard and the rating as 2 turtle objects utilizing turtle’s write() methodology, which permits us to show textual content on display screen. First, we are going to 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 are going to create 2 turtle cases, scoreboard and my_score. The scoreboard object will show the textual content on display screen “Rating = “, whereas the my_score object will show the rating variable, which can change because the snake eats its meals. As might be seen within the code beneath, each of those turtle objects have been personalized for the display screen textual content show in keeping with 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="middle", font=("Arial", 12, "regular"))
    
    my_score = Turtle()
    my_score.colour("black")
    my_score.penup()
    my_score.hideturtle()
    

    As soon as now we have created the above, we are going to now proceed so as to add the availability of adjusting the core inside the whereas loop of the sport, contained in the if conditional assertion when the snake collides with the meals. Test the code beneath and replace the particular strains 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="middle", font=("Arial", 12, "regular"))

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

    Scoreboard and Rating Show (Picture by Writer)

    Sport Ending

    When the sport ends, we have to inform the person that the sport is over, somewhat than simply closing the show display screen. For this we are going to outline a perform and name it at any time when the sport ends: both by collision with a wall or by collision with tail. We are going to use the turtle object for this as effectively. That is the perform, and it is going to 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="middle", font=("Arial", 40, "regular"))
    

    Detect Collision with Wall

    One other situation of the sport’s continuity is to ensure the snake doesn’t collide with the boundary wall of the display screen. In an effort to code this, and figuring out that the sport’s display screen is 600×600, we are going to take into account 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 inside 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 strains of code, now we have accessed the x and y coordinates of the primary section of the snake and checked whether or not it falls inside or outdoors of the boundary wall.

    Detect Collision with Tail

    Lastly, we are going to 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 another section, the sport ends. We are going to use the for loop to code this state of affairs:

    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 person that the sport is over, somewhat than simply closing the show display screen. For this, we are going to name the game_over perform we outlined earlier.

    Sport Over (Picture by Writer)

    Conclusion

    On this tutorial, now we have efficiently carried out the snake sport in Python. We’ve used our understanding of Python fundamentals, akin to defining and calling features, utilizing lists and tuples, utilizing for and whereas loops in addition to conditional statements. We’ve additionally carried out our fundamental understanding of Object Oriented Programming to create objects from a module’s courses. In case you have any queries concerning any piece of code or a suggestion to make the code extra strong and environment friendly, be happy to remark and share your concepts. Till then, code, play, and problem your pals to the Snake Sport you’ve designed!



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHow to Personalize Claude Code
    Next Article Pain Points, Fixes, and Best Practices
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    AI algorithm enables tracking of vital white matter pathways | MIT News

    February 10, 2026
    Artificial Intelligence

    How to Model The Expected Value of Marketing Campaigns

    February 10, 2026
    Artificial Intelligence

    How to Personalize Claude Code

    February 10, 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Why the Moltbook frenzy was like Pokémon

    February 9, 2026

    AI Is Impacting the Job Market

    November 4, 2025

    Landing your First Machine Learning Job: Startup vs Big Tech vs Academia

    June 3, 2025

    New McKinsey Report Shows Mostly Experimentation, Not Transformation, With AI So Far

    November 21, 2025

    Shaip Partners with Databricks to Deliver De-Identified EHR & Physician Dictation Data for AI in Healthcare

    November 13, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    ChatGPT Now Recommends Products and Prices With New Shopping Features

    April 29, 2025

    Modular Arithmetic in Data Science

    August 19, 2025

    Why Open Source is No Longer Optional — And How to Make it Work for Your Business

    June 18, 2025
    Our Picks

    AI algorithm enables tracking of vital white matter pathways | MIT News

    February 10, 2026

    A “QuitGPT” campaign is urging people to cancel their ChatGPT subscription

    February 10, 2026

    How to Model The Expected Value of Marketing Campaigns

    February 10, 2026
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.