avatarAayushi Johari

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9621

Abstract

lass="hljs-string">"left"</span>: head.direction = <span class="hljs-string">"right"</span>

<span class="hljs-function">def <span class="hljs-title">go_left</span>(): <span class="hljs-keyword">if</span> head.direction !</span>= <span class="hljs-string">"right"</span>: head.direction = <span class="hljs-string">"left"</span></pre></div><p id="63a9">We need the system to listen to our control key presses. We add a function called <b>win.listen() </b>that listens to the key presses. Every keypress needs to be bound to a function that carries out an action. We use the function <b>win.onkeypress(function, “key”)</b> for the same.</p><div id="95ae"><pre># keyboard bindings <span class="hljs-keyword">win</span>.listen() <span class="hljs-keyword">win</span>.onkey(go_up, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">win</span>.onkey(go_down, <span class="hljs-string">"s"</span>) <span class="hljs-keyword">win</span>.onkey(go_right, <span class="hljs-string">"d"</span>) <span class="hljs-keyword">win</span>.onkey(go_left, <span class="hljs-string">"a"</span>)</pre></div><figure id="8043"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*PgleOyZq8zCXym6nZb2LLw.png"><figcaption></figcaption></figure><h2 id="c46a">Add Some Food</h2><p id="d6de">Food again is a turtle that remains stationary until it’s been touched(eaten). Once the snake eats the food, it takes up another random position and the game continuous. Let’s go ahead and create a turtle for food in a similar way. We are going to use the same functions as we used for creating the snakehead.</p><div id="46d7"><pre><span class="hljs-comment"># Snake food</span> <span class="hljs-attribute">food</span> = turtle.Turtle() <span class="hljs-attribute">food</span>.speed(<span class="hljs-number">0</span>) <span class="hljs-attribute">food</span>.shape(<span class="hljs-string">"circle"</span>) <span class="hljs-attribute">food</span>.color(<span class="hljs-string">"red"</span>) <span class="hljs-attribute">food</span>.penup() <span class="hljs-attribute">food</span>.shapesize(<span class="hljs-number">0</span>.<span class="hljs-number">50</span>, <span class="hljs-number">0</span>.<span class="hljs-number">50</span>) <span class="hljs-attribute">food</span>.goto(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)</pre></div><figure id="6ee9"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ke0z5XQwZB2XrfkfxwafDA.png"><figcaption></figcaption></figure><p id="887b">Now that we’ve created the snakehead and the food and given functionalities to move, the snake is supposed to eat the food when it touches it and the food needs to take up a new position. I am going to calculate the distance between the two objects with the function <b>head.distance(food)</b>. If the distance is less than 15(food and head come in contact), the food is re-positioned to a random position anywhere within the window. Let’s go ahead and add this feature in the main game loop.</p><div id="8afa"><pre><span class="hljs-attribute">if</span> head.distance(food) <<span class="hljs-number">15</span>: <span class="hljs-comment"># move the food to a random position on screen</span> <span class="hljs-attribute">x</span> = random.randint(-<span class="hljs-number">290</span>, <span class="hljs-number">290</span>) <span class="hljs-attribute">y</span> = random.randint(-<span class="hljs-number">290</span>, <span class="hljs-number">290</span>) <span class="hljs-attribute">food</span>.goto(x, y)</pre></div><h2 id="a771">Build Snake’s Body</h2><p id="3609">Now we need a functionality that increases the snake body every time it touches food. We use arrays for this purpose. We create an array called segments, which is initialized to empty.</p><div id="21e5"><pre><span class="hljs-attribute">segments</span> <span class="hljs-operator">=</span> []</pre></div><p id="eb0f">We need to add a segment to the snake’s body every time it touches the food. We already have a condition that checks for the head’s collision with food. Create a new turtle and name it <i>new_segment, </i>define its speed, shape, and color and append it to the segments array.</p><div id="611a"><pre><span class="hljs-meta"># add a segment</span> <span class="hljs-keyword">new</span><span class="hljs-type">_segment</span> = turtle.Turtle() <span class="hljs-keyword">new</span><span class="hljs-type">_segment</span>.speed(<span class="hljs-number">0</span>) <span class="hljs-keyword">new</span><span class="hljs-type">_segment</span>.shape(<span class="hljs-string">"square"</span>) <span class="hljs-keyword">new</span><span class="hljs-type">_segment</span>.color(<span class="hljs-string">"grey"</span>) <span class="hljs-keyword">new</span><span class="hljs-type">_segment</span>.penup() segments.append(<span class="hljs-keyword">new</span><span class="hljs-type">_segment</span>)</pre></div><p id="87a2">Adding the segment to the snakehead is not enough. Those segments need to move when the snakehead moves. The logic I’ve used moves the last segment which is in the position x to x-1 and x-1 to x-2 and so on.</p><div id="0d62"><pre># <span class="hljs-keyword">move</span> the <span class="hljs-keyword">end</span> segment <span class="hljs-keyword">in</span> <span class="hljs-keyword">reverse</span> <span class="hljs-keyword">order</span> <span class="hljs-keyword">for</span> <span class="hljs-keyword">index</span> <span class="hljs-keyword">in</span> range(len(segments)<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">-1</span>): x = segments[<span class="hljs-keyword">index</span><span class="hljs-number">-1</span>].xcor() y = segments[<span class="hljs-keyword">index</span><span class="hljs-number">-1</span>].ycor() segments[<span class="hljs-keyword">index</span>].goto(x, y)</pre></div><p id="3dad">But the segment which is right above the head is a special case. Where does that go? It goes in the place of the head.</p><div id="81b1"><pre># Move segment <span class="hljs-number">0</span> to where the head is if <span class="hljs-built_in">len</span>(segments) &amp;gt; <span class="hljs-number">0</span>: x = head.<span class="hljs-built_in">xcor</span>() y = head.<span class="hljs-built_in">ycor</span>() segments[<span class="hljs-number">0</span>].<span class="hljs-built_in">goto</span>(x, y)</pre></div><figure id="38f4"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*hEdJxrfZjWkAEt7Gy5FYnQ.png"><figcaption></figcaption></figure><h2 id="5f5c">Add Border Collisions</h2><p id="6333">We need to make sure that the snake dies when it collides with the border. We already have the coordinates of the border, we just need to reset the snakehead position when it touches those coordinates. Also, the snake needs to stop moving and hence change the direction to stop.</p><div id="bc20"><pre><span class="hljs-comment"># Check for collision</span> <span class="hljs-attribute">if</span> head.xcor() > <span class="hljs-number">290</span> or head.xcor() < -<span class="hljs-number">290</span> or head.ycor() > <span class="hljs-number">290</span> or head.ycor() < -<span class="hljs-number">290</span>: <span class="hljs-attribute">time</span>.sleep(<span class="hljs-number">1</span>) <span class="hljs-attribute">head</span>.goto(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>) <span class="hljs-attribute">head</span>.direction = <span class="hljs-string">"stop"</span></pre></div><p id="8075">Also, the segments need to disappear when the snake dies. For this, all we need to do is, set the segment’s position outside the window coordinates. Now when the game restarts we need fresh new segment and hence clear the segment list.</p><div id="71cb"><pre><span class="hljs-comment"># Hide the segments</span> <span class="hljs-keyword">for</span> <span class="hljs-keyword">segment</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">segments</span>: <span class="hljs-keyword">segment</span>.goto(<span class="hljs-number">1000</span>, <span class="hljs-number">1000</span>)

    <span class="hljs-comment"># clear segment list</span>
    <span class="hljs-keyword">segments</span> = []</pre></div><figure id="d8c5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lox9JGZ19_l_M5SUAdnhJw.png"><figcaption></figcaption></figure><h2 id="7eda">Add Body Collisions</h2><p id="b116">The snake needs to die when it touches itself. So we’re going to go through the entire segments list and check if the distance between the segment and head is less than 20. If it is, reset the head position and head direction.</p><div id="3d90"><pre><span class="hljs-comment"># Check for head collision</span>
<span class="hljs-keyword">for</span> <span class="hljs-keyword">segment</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">segments</span>:
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">segment</span>.distance(head) &lt; <span class="hljs-number">20</span>:
        <span class="hljs-built_in">time</span>.sleep(<span class="hljs-number">1</span>)
        head.goto(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
        head.direction = <span class="hljs-string">"stop"</span>

<span class="hljs-comment"># Hide the segments</span> <span class="hljs-keyword"

Options

for</span> <span class="hljs-keyword">segment</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">segments</span>: <span class="hljs-keyword">segment</span>.goto(<span class="hljs-number">1000</span>, <span class="hljs-number">1000</span>)

<span class="hljs-comment"># clear segment list</span> <span class="hljs-keyword">segment</span>.<span class="hljs-built_in">clear</span>()</pre></div><figure id="d21b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*f69JIxA7lW6Nuk9IS53_XA.png"><figcaption></figcaption></figure><h2 id="a4c9">Add Scores</h2><p id="d3f6">Turtle module has an amazing feature that allows you to write on the screen. I am going to start by creating a turtle to use it as a pen.</p><div id="089a"><pre>pen = turtle<span class="hljs-selector-class">.Turtle</span>() pen<span class="hljs-selector-class">.speed</span>(<span class="hljs-number">0</span>) pen<span class="hljs-selector-class">.shape</span>(<span class="hljs-string">"square"</span>) pen<span class="hljs-selector-class">.color</span>(<span class="hljs-string">"white"</span>) pen<span class="hljs-selector-class">.penup</span>() pen<span class="hljs-selector-class">.hideturtle</span>() pen<span class="hljs-selector-class">.goto</span>(<span class="hljs-number">0</span>, <span class="hljs-number">260</span>) pen<span class="hljs-selector-class">.write</span>(<span class="hljs-string">"Score: 0 High Score: {}"</span><span class="hljs-selector-class">.format</span>(high_score), align=<span class="hljs-string">"center"</span>, <span class="hljs-attribute">font</span>=(<span class="hljs-string">"Courier"</span>, <span class="hljs-number">24</span>, <span class="hljs-string">"normal"</span>))</pre></div><p id="e1cd">Let’s initialize a variable called <i>score </i>to 0 and <i>high_score </i>also to 0.</p><div id="2427"><pre><span class="hljs-comment"># score </span> <span class="hljs-attr">score</span> = <span class="hljs-number">0</span> <span class="hljs-attr">high_score</span> = <span class="hljs-number">0</span></pre></div><p id="3809">We need to analyze the situations when the score increases. First one is when the head collides with the food. Increase the <i>score</i> and update the <i>high_score</i>. We use the <b>pen.write()</b> to write the score on the screen.</p><div id="8c1c"><pre># Increase the <span class="hljs-variable language_">score</span> <span class="hljs-variable language_">score</span> = <span class="hljs-variable language_">score</span>+<span class="hljs-number">10</span>

    <span class="hljs-keyword">if</span> <span class="hljs-variable language_">score</span> &gt; high_score:
        high_score = <span class="hljs-variable language_">score</span></pre></div><p id="e343">We need to reset the score when the snakehead collides with the border and with its own segment. Add the following lines in those two places</p><div id="dfe1"><pre># reset <span class="hljs-keyword">score</span>
        <span class="hljs-keyword">score</span> = 0

# <span class="hljs-keyword">update</span> <span class="hljs-keyword">score</span>
        pen.<span class="hljs-keyword">clear</span>()
        pen.write(<span class="hljs-string">"score: {} High Score: {}"</span>.<span class="hljs-keyword">format</span>(<span class="hljs-keyword">score</span>, high_score), align=<span class="hljs-string">"center"</span>, font=(<span class="hljs-string">"Courier"</span>, 24, <span class="hljs-string">"normal"</span>))</pre></div><p id="a60d">And Tadaaaaa!! Your game is ready. Python is a widely-used programming language with 8.2 million developers working with it. You’ll be surprised to see what wonders it can do. Another cool module that allows you to develop games is Pygame.</p><p id="665f">I hope this Python’s turtle module has helped you get an idea of how games can be built with it. Please do use it to build more such games and let me know in the comments section below. I’d love to play them. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=python-turtle-module">Edureka’s official site.</a></p><p id="257f">Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.</p><blockquote id="273d"><p>1. <a href="https://readmedium.com/machine-learning-classifier-c02fbd8400c9">Machine Learning Classifier in Python</a></p></blockquote><blockquote id="a2f2"><p>2. <a href="https://readmedium.com/python-scikit-learn-cheat-sheet-9786382be9f5">Python Scikit-Learn Cheat Sheet</a></p></blockquote><blockquote id="a141"><p>3. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Machine Learning Tools</a></p></blockquote><blockquote id="9c7e"><p>4. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Python Libraries For Data Science And Machine Learning</a></p></blockquote><blockquote id="3d14"><p>5. <a href="https://readmedium.com/how-to-make-a-chatbot-in-python-b68fd390b219">Chatbot In Python</a></p></blockquote><blockquote id="5420"><p>6. <a href="https://readmedium.com/collections-in-python-d0bc0ed8d938">Python Collections</a></p></blockquote><blockquote id="7f97"><p>7. <a href="https://readmedium.com/python-modules-abb0145a5963">Python Modules</a></p></blockquote><blockquote id="a7a9"><p>8. <a href="https://readmedium.com/python-developer-skills-371583a69be1">Python developer Skills</a></p></blockquote><blockquote id="7133"><p>9. <a href="https://readmedium.com/oops-interview-questions-621fc922cdf4">OOPs Interview Questions and Answers</a></p></blockquote><blockquote id="cfdb"><p>10. <a href="https://readmedium.com/python-developer-resume-ded7799b4389">Resume For A Python Developer</a></p></blockquote><blockquote id="c954"><p>11. <a href="https://readmedium.com/exploratory-data-analysis-in-python-3ee69362a46e">Exploratory Data Analysis In Python</a></p></blockquote><blockquote id="772d"><p>12. <a href="https://readmedium.com/python-turtle-module-361816449390">Snake Game With Python’s Turtle Module</a></p></blockquote><blockquote id="6640"><p>13. <a href="https://readmedium.com/python-developer-salary-ba2eff6a502e">Python Developer Salary</a></p></blockquote><blockquote id="f84f"><p>14.<a href="https://readmedium.com/principal-component-analysis-69d7a4babc96"> Principal Component Analysis</a></p></blockquote><blockquote id="d6b7"><p>15. <a href="https://readmedium.com/python-vs-cpp-c3ffbea01eec">Python vs C++</a></p></blockquote><blockquote id="39c4"><p>16. <a href="https://readmedium.com/scrapy-tutorial-5584517658fb">Scrapy Tutorial</a></p></blockquote><blockquote id="2f43"><p>17. <a href="https://readmedium.com/scipy-tutorial-38723361ba4b">Python SciPy</a></p></blockquote><blockquote id="9ae2"><p>18. <a href="https://readmedium.com/least-square-regression-40b59cca8ea7">Least Squares Regression Method</a></p></blockquote><blockquote id="c9d3"><p>19. <a href="https://readmedium.com/jupyter-notebook-cheat-sheet-88f60d1aca7">Jupyter Notebook Cheat Sheet</a></p></blockquote><blockquote id="31e8"><p>20. <a href="https://readmedium.com/python-basics-f371d7fc0054">Python Basics</a></p></blockquote><blockquote id="48f6"><p>21. <a href="https://readmedium.com/python-pattern-programs-75e1e764a42f">Python Pattern Programs</a></p></blockquote><blockquote id="20eb"><p>22. <a href="https://readmedium.com/generators-in-python-258f21e3d3ff">Generators in Python</a></p></blockquote><blockquote id="fec7"><p>23. <a href="https://readmedium.com/python-decorator-tutorial-bf7b21278564">Python Decorator</a></p></blockquote><blockquote id="5acc"><p>24.<a href="https://readmedium.com/spyder-ide-2a91caac4e46"> Python Spyder IDE</a></p></blockquote><blockquote id="2e08"><p>25. <a href="https://readmedium.com/kivy-tutorial-9a0f02fe53f5">Mobile Applications Using Kivy In Python</a></p></blockquote><blockquote id="8166"><p>26. <a href="https://readmedium.com/best-books-for-python-11137561beb7">Top 10 Best Books To Learn &amp; Practice Python</a></p></blockquote><blockquote id="e647"><p>27. <a href="https://readmedium.com/robot-framework-tutorial-f8a75ab23cfd">Robot Framework With Python</a></p></blockquote><blockquote id="dfd1"><p>28. <a href="https://readmedium.com/web-scraping-with-python-d9e6506007bf">Web Scraping With Python</a></p></blockquote><blockquote id="baf9"><p>29. <a href="https://readmedium.com/django-interview-questions-a4df7bfeb7e8">Django Interview Questions and Answers</a></p></blockquote><blockquote id="85b9"><p>30. <a href="https://readmedium.com/python-applications-18b780d64f3b">Top 10 Python Applications</a></p></blockquote><blockquote id="9fb6"><p>31. <a href="https://readmedium.com/hash-tables-and-hashmaps-in-python-3bd7fc1b00b4">Hash Tables and Hashmaps in Python</a></p></blockquote><blockquote id="aaa1"><p>32. <a href="https://readmedium.com/whats-new-python-3-8-7d52cda747b">Python 3.8</a></p></blockquote><blockquote id="4b91"><p>33. <a href="https://readmedium.com/support-vector-machine-in-python-539dca55c26a">Support Vector Machine</a></p></blockquote><blockquote id="312d"><p>34. <a href="https://readmedium.com/python-tutorial-be1b3d015745">Python Tutorial</a></p></blockquote><p id="a413"><i>Originally published at <a href="https://www.edureka.co/blog/python-turtle-module/">https://www.edureka.co</a> on August 23, 2019.</i></p></article></body>

Build The Famous Snake Game With Python’s Turtle Module

Python Turtle Module — Edureka

As a kid, I am sure everybody has played the famous snake game. As a matter of fact, it was one of the first mobile games that came into the market. Wouldn’t it be cool to build it by yourself? Hell Yeah! In this article, I am going to use Python’s Turtle Module to build it from scratch.

Agenda:

  • What Is Python’s Turtle Module?
  • Start Building The Game
  1. Set Up The Screen
  2. Create Snake’s Head
  3. Functions To Move The Snake
  4. Add Some Food
  5. Build Snake’s Body
  6. Add Border Collisions
  7. Add Body Collisions
  8. Add Scores

What Is Python’s Turtle Module?

I’m sure everybody has used a drawing board as a kid. Now, imagine, instead of manually drawing on the board, you could command the system to draw for you. Isn’t that cool? Python’s turtle module lets you do that. It basically lets you create a drawing board and command a turtle to draw for you.

Let’s move ahead and start building the game. I have used PyCharm with Python version 2.7 for this article.

Start Building The Game

Let’s understand this game before we start building. There are two elements in this game — snake and food. The player has to move the snake such that it touches(eats) the food and grows in size. The snake dies if it touches its own body or the boundaries of the window. On an obvious note, the player needs to win and hence avoid dying.

Set Up The Screen

To start using the module, you need to import it like any other module in python.

import turtle

The function turtle.Screen() is used to create a window. In this case, our window is win for the game. Give this window a name with the function window.title(“Kalgi’s Snake Game”). Set the background color for the window with the function window.bgcolor(“Color”). Set the window height and width with the function window.setup(width=X, height=Y). The function window.tracer() turns off the screen updates. We do not need any screen updates other than the scoreboard and hence set to 0.

#set up the screen
win = turtle.Screen()
win.title("Kalgi's snake game")
win.bgcolor("blue")
win.setup(width=600,height=600)
win.tracer(0)

Create Snake’s Head

Once you’ve created the window, the next thing we need is a snakehead. Snake is basically a turtle(in python language) that moves around. Create a turtle with the function turtle.Turtle() and assign it the name head. We set the head speed to 0 as we’re just initializing in this section and the head does not need to move. We use the function turtle_name.speed() for this. Next, we need to initialize the head shape and color. We use the functions turtle_name.shape() and turtle_name.color().

Do we need to draw the paths taken by the snake? No! The function turtle_name.penup() makes sure that the path taken by the snake is not drawn. I want my snakehead’s position to be the center of the window and the direction to be “stop”. We use the functions turtle_name.goto() and turtle_name.direction() for it.

#Snake Head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 100)
head.direction = "stop"

Once the head is created, I need the main game loop which is always set to true. I am going to update my window using the function window.update(). This function basically updates my screen continuously with the loop.

# Main game loop
while True:
    win.update()

Functions To Move the Snake

Now that we have created a snake lets go ahead and make the snake move. We define a function called move(). If the head goes up, the ‘y’ coordinate is increased, if the head goes down, the ‘y’ coordinate decreases, if the head moves right, the ‘x’ coordinate increases and if the head moves left, the ‘x’ coordinate decreases.

def move():
    if head.direction == "up":
        y = head.ycor() #y coordinate of the turtle
        head.sety(y + 20)
 
    if head.direction == "down":
        y = head.ycor() #y coordinate of the turtle
        head.sety(y - 20)
 
    if head.direction == "right":
        x = head.xcor() #y coordinate of the turtle
        head.setx(x + 20)
 
    if head.direction == "left":
        x = head.xcor() #y coordinate of the turtle
        head.setx(x - 20)

The function does nothing until it’s called. So we need to call the function every time we update the screen or the window. Update the main game loop as follows:

#Main Game Loop
while: True
    win.update()
    move()

You can try executing the code so far and you’ll notice that the snake moves but very fast. That’s the default behavior for the move function. To slow this down, we need to use the time module. Go to the import section of your code and import the time module. We initialize a variable called delay to 0.1. And then call the function time.sleep(delay) to reduce turtle speed.

import turtle
import time
delay=0.1
# Main game loop
while True:
    wn.update()
    move()
    time.sleep(delay)

We’ve made the functions for moving the turtle up, down, left and right. But how does the computer know what up, down, left and right is? We need to define a function for each of these directions and set the head.direction to up, down, right and left.

Note: The snake cannot go right from left, left from right, top from down and down from the top.

def go_up():
    if head.direction != "down":
        head.direction = "up"
 
def go_down():
    if head.direction != "up":
        head.direction = "down"
 
def go_right():
    if head.direction != "left":
        head.direction = "right"
 
def go_left():
    if head.direction != "right":
        head.direction = "left"

We need the system to listen to our control key presses. We add a function called win.listen() that listens to the key presses. Every keypress needs to be bound to a function that carries out an action. We use the function win.onkeypress(function, “key”) for the same.

# keyboard bindings
win.listen()
win.onkey(go_up, "w")
win.onkey(go_down, "s")
win.onkey(go_right, "d")
win.onkey(go_left, "a")

Add Some Food

Food again is a turtle that remains stationary until it’s been touched(eaten). Once the snake eats the food, it takes up another random position and the game continuous. Let’s go ahead and create a turtle for food in a similar way. We are going to use the same functions as we used for creating the snakehead.

# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.shapesize(0.50, 0.50)
food.goto(0, 0)

Now that we’ve created the snakehead and the food and given functionalities to move, the snake is supposed to eat the food when it touches it and the food needs to take up a new position. I am going to calculate the distance between the two objects with the function head.distance(food). If the distance is less than 15(food and head come in contact), the food is re-positioned to a random position anywhere within the window. Let’s go ahead and add this feature in the main game loop.

if head.distance(food) <15:
# move the food to a random position on screen
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)

Build Snake’s Body

Now we need a functionality that increases the snake body every time it touches food. We use arrays for this purpose. We create an array called segments, which is initialized to empty.

segments = []

We need to add a segment to the snake’s body every time it touches the food. We already have a condition that checks for the head’s collision with food. Create a new turtle and name it new_segment, define its speed, shape, and color and append it to the segments array.

# add a segment
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment)

Adding the segment to the snakehead is not enough. Those segments need to move when the snakehead moves. The logic I’ve used moves the last segment which is in the position x to x-1 and x-1 to x-2 and so on.

# move the end segment in reverse order
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)

But the segment which is right above the head is a special case. Where does that go? It goes in the place of the head.

# Move segment 0 to where the head is
    if len(segments) &amp;gt; 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)

Add Border Collisions

We need to make sure that the snake dies when it collides with the border. We already have the coordinates of the border, we just need to reset the snakehead position when it touches those coordinates. Also, the snake needs to stop moving and hence change the direction to stop.

# Check for collision
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"

Also, the segments need to disappear when the snake dies. For this, all we need to do is, set the segment’s position outside the window coordinates. Now when the game restarts we need fresh new segment and hence clear the segment list.

# Hide the segments
        for segment in segments:
           segment.goto(1000, 1000)
 
        # clear segment list
        segments = []

Add Body Collisions

The snake needs to die when it touches itself. So we’re going to go through the entire segments list and check if the distance between the segment and head is less than 20. If it is, reset the head position and head direction.

# Check for head collision
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = "stop"
 
# Hide the segments
            for segment in segments:
                segment.goto(1000, 1000)
 
# clear segment list
            segment.clear()

Add Scores

Turtle module has an amazing feature that allows you to write on the screen. I am going to start by creating a turtle to use it as a pen.

pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: {}".format(high_score), align="center", font=("Courier", 24, "normal"))

Let’s initialize a variable called score to 0 and high_score also to 0.

# score 
score = 0 
high_score = 0

We need to analyze the situations when the score increases. First one is when the head collides with the food. Increase the score and update the high_score. We use the pen.write() to write the score on the screen.

# Increase the score
        score = score+10
 
        if score > high_score:
            high_score = score

We need to reset the score when the snakehead collides with the border and with its own segment. Add the following lines in those two places

# reset score
            score = 0
 
    # update score
            pen.clear()
            pen.write("score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))

And Tadaaaaa!! Your game is ready. Python is a widely-used programming language with 8.2 million developers working with it. You’ll be surprised to see what wonders it can do. Another cool module that allows you to develop games is Pygame.

I hope this Python’s turtle module has helped you get an idea of how games can be built with it. Please do use it to build more such games and let me know in the comments section below. I’d love to play them. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Machine Learning Classifier in Python

2. Python Scikit-Learn Cheat Sheet

3. Machine Learning Tools

4. Python Libraries For Data Science And Machine Learning

5. Chatbot In Python

6. Python Collections

7. Python Modules

8. Python developer Skills

9. OOPs Interview Questions and Answers

10. Resume For A Python Developer

11. Exploratory Data Analysis In Python

12. Snake Game With Python’s Turtle Module

13. Python Developer Salary

14. Principal Component Analysis

15. Python vs C++

16. Scrapy Tutorial

17. Python SciPy

18. Least Squares Regression Method

19. Jupyter Notebook Cheat Sheet

20. Python Basics

21. Python Pattern Programs

22. Generators in Python

23. Python Decorator

24. Python Spyder IDE

25. Mobile Applications Using Kivy In Python

26. Top 10 Best Books To Learn & Practice Python

27. Robot Framework With Python

28. Web Scraping With Python

29. Django Interview Questions and Answers

30. Top 10 Python Applications

31. Hash Tables and Hashmaps in Python

32. Python 3.8

33. Support Vector Machine

34. Python Tutorial

Originally published at https://www.edureka.co on August 23, 2019.

Programming
Python
Python Turtle Module
Python Module
Python Snake Game
Recommended from ReadMedium