Python Game Programming Tutorial: Snake Game Part 5 - playproduction.de

Python Game Programming Tutorial: Snake Game Part 5

TokyoEdtech
Views: 53245
Like: 825
NEED HELP?
🆘 Watch this first and then let me know in the comments below:

❤️❤️ SHOW SOME LOVE AND SUPPORT THE CHANNEL ❤️❤️

Click Join and Become a Channel Member Today!
Channel members can get preferential comment replies, early access to new content, members only live streams, and access to my private Discord.
❤️

Amazon Affiliate Links
💻 My Laptop (Asus Zenbook 13):
🎙My New Microphone (Blue Yeti Pro):
🎙My Old Microphone (Blue Snowball):
🎶My USB Interface (Focusrite Scarlett Solo):

Other Affiliate Links
⭐ Kite is a free AI-powered coding assistant that will help you code faster and smarter. The Kite plugin integrates with all the top editors and IDEs to give you smart completions and documentation while you’re typing.

LINKS
🗄️ GITHUB:
💬 Follow me on Twitter:
📜 Subscribe to my Newsletter:
📝 Check out my Blog:
⬇️ Download Geany Editor:

LEARN MORE PYTHON
➡️Space Invaders:
➡️Snake Game:
➡️Pong:
➡️Space War:
➡️Intro to Python (for Java Coders):
➡️Space Arena – The Ultimate Python Turtle Graphics Game Tutorial:

LEARN MORE JAVA
➡️Basic Java for Beginners:
➡️Intro to AP Computer Science A:

#Python #Tutorial #Beginner

134 Comments

  1. can' t we declare the segment list once more as an empty list in the if statement

  2. Sir there is everything fine in my game except the colllision with the borders. My snake is not resetting after colliding with the border inspite of that it gets beyond the borders.
    My code is given below please help me out :-
    import turtle

    import time

    import random

    delay = 0.1

    wn = turtle.Screen()

    wn.title("Snake Game by Ankit Chauhan")

    wn.bgcolor("light blue")

    wn.setup(width=600, height=600)

    wn.tracer(0) #to turn of the screen

    # Snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("circle")

    head.color("green")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    #Snake Food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("square")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    # Functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    # Keyboard Bindings

    wn.listen()

    wn.onkeypress(go_up, "w")

    wn.onkeypress(go_down, "s")

    wn.onkeypress(go_right, "d")

    wn.onkeypress(go_left, "a")

    # Main game loop

    while True:

    wn.update()

    # Check for collision with the border

    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"

    #hide the segments

    for segment in segments:

    segment.goto(1000, 1000)

    #CLEAR THE LIST

    segments.clear()

    # Check for a collision with the food

    if head.distance(food) < 20:

    # Move the food to a random spot on the screen

    x = random.randint(-290, 290)

    y = random.randint(-290, 290)

    food.goto(x, y)

    # Add a segment

    new_segment = turtle.Turtle()

    new_segment.speed(0)

    new_segment.shape("circle")

    new_segment.color("black")

    new_segment.penup()

    segments.append(new_segment)

    # move the end segments first in reversal

    for index in range(len(segments) -1, 0 , -1):

    x = segments[index-1].xcor()

    y = segments[index-1].ycor()

    segments[index].goto(x, y)

    # Move segment 0 to where the head is

    if len(segments) > 0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x, y)

    move()

    time.sleep(delay)

    wn.mainloop()

  3. Sir I am facing some problem in this game, when the snake collides with borders it comes back to origin but do not move after it, some len error is coming .
    Please can u help me

  4. Can you help when i die i spawn with one segment and cant get anymore

  5. Dear Sir, I followed what you have taught but the game doesn't run !!!
    CODE:
    import turtle

    import time

    import random

    delay = 0.1

    # set up screen

    screen = turtle.Screen()

    screen.title("SNAKE GAME by Nguyen Duc Hoang")

    screen.bgcolor("green")

    screen.setup(width=600, height=600)

    screen.tracer(0) # Turn off the screen

    # Snake head

    snake_head = turtle.Turtle()

    snake_head.speed(0)

    snake_head.shape("square")

    snake_head.color("black")

    snake_head.penup()

    snake_head.goto(0, 0)

    snake_head.direction = "stop"

    # Snake food

    snake_food = turtle.Turtle()

    snake_food.speed(0)

    snake_food.shape("circle")

    snake_food.color("red")

    snake_food.penup()

    snake_food.goto(0, 100)

    add_bodies = [0]

    # Functions

    def go_up():

    snake_head.direction == "up"

    def go_down():

    snake_head.direction == "down"

    def go_left():

    snake_head.direction == "left"

    def go_right():

    snake_head.direction == "right"

    def move():

    if snake_head.direction == "up":

    y = snake_head.ycor()

    snake_head.sety(y + 20)

    if snake_head.direction == "down":

    y = snake_head.ycor()

    snake_head.sety(y – 20)

    if snake_head.direction == "left":

    x = snake_head.xcor()

    snake_head.setx(x – 20)

    if snake_head.direction == "right":

    x = snake_head.xcor()

    snake_head.setx(x + 20)

    # Keyboard bindings

    screen.listen()

    screen.onkeypress(go_up, "w")

    screen.onkeypress(go_down, "s")

    screen.onkeypress(go_left, "a")

    screen.onkeypress(go_right, "d")

    # MAIN GAM LOOP

    while True:

    screen.update()

    # Check for a collision to the borders

    if snake_head.xcor()>290 or snake_head.xcor()<-290 or snake_head.ycor()>290 or snake_head.ycor()<-290:

    time.sleep(1)

    snake_head.goto(0, 0)

    snake_head.direction = "stop"

    # Hide the body

    for new_body in add_bodies:

    new_body.goto(1000, 1000)

    # Clear the body list

    add_bodies.clear()

    # Check for a collision with the food

    if snake_head.distance(snake_food) < 20:

    # Move the food to random spot

    x = random.randint(-290, 290)

    y = random.randint(-290, 290)

    snake_food.goto(x, y)

    # Add bodies to Snake

    new_body = turtle.Turtle()

    new_body.speed(0)

    new_body.shape("diamond")

    new_body.color("grey")

    new_body.penup()

    add_bodies.append(new_body)

    # Move the end to first in reverse order

    for index in range(add_bodies – 1, 0, -1):

    x = add_bodies[index – 1].xcor()

    y = add_bodies[index – 1].ycor()

    add_bodies[index].goto(x, y)

    # Move body = 0 to where the head is

    if len(add_bodies) > 0:

    x = snake_head.xcor()

    y = snake_head.ycor()

    add_bodies[0].goto(x, y)

    move()

    time.sleep(delay)

    screen.mainloop()

    ERROR:
    D:PythonSnakeGame.pyvenvScriptspython.exe D:PythonSnakeGame.pySnake.py

    Traceback (most recent call last):

    File "D:PythonSnakeGame.pySnake.py", line 91, in <module>

    new_body.goto(1000, 1000)

    AttributeError: 'int' object has no attribute 'goto'

    Process finished with exit code 1

    PLEASE HELP !

  6. To clear segments just do segments.clear() its a python list function

  7. for index in range(len(segment)-1, 0, -1):

    TypeError: object of type 'Turtle' has no len()

  8. Possibly even more counterintuitive but some how more beautiful would be to move the tail to where the head was, just one turtle moved. Sure the segments would not be in the obvious sequential order of the snake, but that does not seem to matter at this stage. Perhaps later on there may be issues but I don't see why. I like minimalist solutions.

  9. it says invalid syntax for the "if head.xcor()>450 or head.xcor()<-450 or head.ycor()>450 or head.ycor()<-450" (my game is 900×900)

  10. for part in body_parts:

    part.hideturtle()

    part.clear()
    body_parts.clear()
    gc.collect() # added just to be sure its gone from the memory
    worked for me for deleting the turtle… i don't think you need to do the gc.collect but if you do import gc first

  11. when my sake touches the borders the application does closes

  12. Hi TokyoEdTech. I found your channel last week, when I was searching for a Python code for the Snake game. I loved the tutorial you made and I followed it step by step. Well, after that I decided to use what I learned from you to improve a little bit of the game. I created new features and did small changes on your code:
    1. The food is created on a grid scale of 20 pixels, in a way that the snake and the food will be on the very same grid layout (to avoid just a part of snake's head touching the food);
    2. I added a clock counting the seconds of game play (I found another video where you explain how to create a timer);
    3. I added a new food called "Bonus Cereal" (yellow square), which is created every 30 seconds. When the cereal is consumed, the score's count is multiplied by 3 for the next 10 seconds;
    4. I added a new food called "Power Bar" (purple triangle), which has a 20% probability to spawn after the snake consume a normal food. When the power bar is consumed, the snake's speed is multiplied by 2 for the next 10 seconds;
    5. Other than that, I also made some visual changes, colors, key to quit the game, etc.
    I shared my code if anyone here wants to see how I built these features, even though my code may not be the most efficient one: https://pastebin.com/zqs4j8d9
    Thanks for your videos! I'm ready to create the Pong game now!

  13. hello am getting this i don't know how solve it File "C:/Users/ihirw/PycharmProjects/pythonProject4/main.py", line 92

    if head.distance(food) < 20:

    ^

    IndentationError: unindent does not match any outer indentation level

  14. hello
    my snake freeze (window open and the objects dont move) after i code this :
    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"

    the errors are:
    Traceback (most recent call last):
    File "/home/pi/Documents/pythonclass/snake game.py", line 87, in <module>
    head.goto(0, 0)
    File "/usr/lib/python3.7/turtle.py", line 1776, in goto
    self._goto(Vec2D(x, y))
    File "/usr/lib/python3.7/turtle.py", line 3158, in _goto
    screen._pointlist(self.currentLineItem),
    File "/usr/lib/python3.7/turtle.py", line 755, in _pointlist
    cl = self.cv.coords(item)
    File "<string>", line 1, in coords
    File "/usr/lib/python3.7/tkinter/__init__.py", line 2469, in coords
    self.tk.call((self._w, 'coords') + args))]
    _tkinter.TclError: invalid command name ".!canvas"

    the link for the code is:
    https://pastebin.com/gaC7UJ57

    great content!!! keep the good work!

  15. you can do 'segment.hideturtle()' to remove the segment.

  16. Sir to clear the segments
    "segments.clear()" it gives me one segment hide and not appears other segments before touch the wall

  17. how to use multiple audio at once using turtle module, pls make a video about that

  18. how we can write this program on ython 3.7?

  19. Could you help, my snake segment adds triangles instead of squares every time it eats food

    import turtle
    import time
    import random

    # turtle head
    delay = 0.1

    wn = turtle.Screen()
    wn.title("Snake Game")
    wn.bgcolor("black")
    wn.setup(width=600, height=600)
    wn.tracer(0)

    head = turtle.Turtle()
    head.speed(0)
    head.shape("square")
    head.color("white")
    head.penup()
    head.goto(0,0)
    head.direction = "stop"

    # snake food
    food = turtle.Turtle()
    food.speed(0)
    food.shape("circle")
    food.color("grey")
    food.penup()
    food.goto(0,100)

    segments = []

    # functions
    def go_up():
    head.direction = "up"

    def go_down():
    head.direction = "down"

    def go_left():
    head.direction = "left"

    def go_right():
    head.direction = "right"

    def move():
    if head.direction == "up":
    y = head.ycor()
    head.sety(y + 20)

    if head.direction == "down":
    y = head.ycor()
    head.sety(y – 20)

    if head.direction == "left":
    x = head.xcor()
    head.setx(x – 20)

    if head.direction == "right":
    x = head.xcor()
    head.setx(x + 20)

    # keyboard bindings
    wn.listen()
    wn.onkeypress(go_up, "Up")
    wn.onkeypress(go_down, "Down")
    wn.onkeypress(go_left, "Left")
    wn.onkeypress(go_right, "Right")

    # main game loop
    while True:
    wn.update()

    if head.distance(food) < 20:
    x = random.randint(-290, 290)
    y = random.randint(-290, 290)
    food.goto(x,y)

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

    for index in range(len(segments)-1, 0, -1):
    x = segments[index-1].xcor()
    y = segments[index-1].ycor()
    segments[index].goto(x, y)

    if len(segments) > 0:
    x = head.xcor()
    y = head.ycor()
    segments[0].goto(x, y)

    move()

    time.sleep(delay)

    wn.mainloop()

  20. Hey man this weird thing keeps happening to me, whenever I die then it resets, then I eat one food, there is a grey segment in the middle of my screen not following the head but after I eat another food it returns to the body like nothing has happened here is my code right now
    import turtle
    import time
    import random

    delay = 0.1

    # Set up the screen
    wn = turtle.Screen()
    wn.title("Snake Game by @Arman")
    wn.bgcolor("blue")
    wn.setup(width=600, height=600)
    wn.tracer(0)

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

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

    segments = []

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

    def move():
    if head.direction == "up":
    y = head.ycor()
    head.sety(y + 20)

    if head.direction == "down":
    y = head.ycor()
    head.sety(y – 20)

    if head.direction == "left":
    x = head.xcor()
    head.setx(x – 20)

    if head.direction == "right":
    x = head.xcor()
    head.setx(x + 20)

    # Keyboard bindings
    wn.listen()
    wn.onkeypress(go_up, "w")
    wn.onkeypress(go_down, "s")
    wn.onkeypress(go_left, "a")
    wn.onkeypress(go_right, "d")

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

    # Check for collision with order
    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"

    # Hide the segments
    for segment in segments:
    segment.goto(1000, 1000)

    # Clear the segments list
    segments.clear()

    # Check for a collision with the food

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

    # 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)

    # Move the end segments first 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)

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

    move()

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

    time.sleep(delay)

    wn.mainloop()

  21. Hey, man I like your vids!
    One question do you know how to remove one segment,
    let's say i want to make a virus instead of the food.
    Is it possible to delete one segment each time you come over the virus?

  22. I would like something, like spacer.
    So if someone picked op the spacer then the background color would change in (blue) but after 3 seconds the background needs to automaticly go back to the green color.
    Can you please help me?

  23. i did everything that you did in the video, but my snake wont move, and it does not come any "message" that something is wrong, it just wont move. (i saw the video in the description)

  24. Hello I have a question. In the part of #hide the segments the segments is difined as [ ] and the segment is difined how?

  25. This works to remove them instead of moving them.

    for segment in segments:

    carl=segment

    carl.reset()

    #Clear the segments list

    segments.clear()

  26. Excellent tutorial. I wonder if I can use part of your code, mainly the ideas and expand it to make a 3D snake game. I will give you credit in the video. Thanks.

  27. Hi #error? whenever i clear the segments, the segments is still appearing on the snake's body and whenever i have 2 segments and i eat another food, it doesn't work, please help me i'm using python 3.2.3 the link is here: https://pastebin.com/gCsK8vKA

  28. hi bro, thanks for the cool tutorials, i love them. Just a question, for this tutorial, why do we have to hide the segments?
    Is it possible to not hide the segments but just clear the segments list? Where does all the turtle instances go to in the list if i were to clear the segments? confused on this part

    # Hide the segments
    for segment in segments:
    segment.goto(1000, 1000)

    # Clear the segments list
    segments = []

  29. Hi i like ur vids, i have been having some problems with the code every time i exit the border with a segment it crashes the window and it says an error message like this Exception Thrown object of type 'Turtle' has no len() Here is the code: https://pastebin.com/GVfxEMJM

  30. Error:

    line 65, in <module>

    f head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor<-290:

    TypeError: '<' not supported between instances of 'method' and 'int'

    my code: import turtle

    import time

    import random

    delay = 0.1

    wn = turtle.Screen()

    wn.title("Snake game google assaignment")

    wn.bgcolor("green")

    wn.setup(width=600, height=600)

    wn.tracer(0)

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("black")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    food = turtle.Turtle()

    food.speed(0)

    food.shape("circle")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    wn.listen()

    wn.onkeypress(go_up, "w")

    wn.onkeypress(go_down, "s")

    wn.onkeypress(go_left, "a")

    wn.onkeypress(go_right, "d")

    while True:

    wn.update()

    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"

    if head.distance(food) < 20:

    x = random.randint(-290,290)

    y = random.randint(-290,290)

    food.goto(x,y)

    new_segment = turtle.Turtle()

    new_segment.speed(0)

    new_segment.shape("square")

    new_segment.color("grey")

    new_segment.penup()

    segments.append(new_segment)

    for index in range(len(segments)-1,0,-1):

    x = segments[index – 1].xcor()

    y = segments[index – 1].ycor()

    segments[index].goto(x, y)

    if len(segments) > 0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x,y)

    move()

    time.sleep(delay)

    wn.mainloop()

  31. @TokyoEdtech my segments disappear while playing, please check what I have wrong

    import turtle

    import time

    import random

    delay = 0.1

    #set up the screen

    wn = turtle.Screen()

    wn.title("snake game by malaz")

    wn.bgcolor("cyan")

    wn.setup(width=600, height=600)

    wn.tracer(0) #stops the screen updates

    #snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("green")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    # The food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("circle")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    # Functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x + 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x – 20)

    # keyboard bindings

    wn.listen()

    wn.onkeypress(go_up, "w")

    wn.onkeypress(go_down, "s")

    wn.onkeypress(go_left, "d")

    wn.onkeypress(go_right, "a")

    # Main gameloop

    while True:

    wn.update()

    # check for a collision with the border

    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"

    # hide the segments

    for segment in segments:

    segment.goto(1000, 1000)

    # clear the segments list

    segments.clear()

    # check for colision of the head with the food

    if head.distance(food) < 20:

    #move the food to a random spot

    x = random.randint(-290,290)

    y = random.randint(-290,290)

    food.goto(x, y)

    # Add a segment

    new_segment = turtle.Turtle()

    new_segment.speed(0)

    new_segment.shape("square")

    new_segment.color("yellow")

    new_segment.penup()

    segments.append(new_segment)

    # move the segments in reverse order first

    for index in range(len(segments)-1, 0, -1):

    x = segments[index-1].xcor()

    y = segments[index-1].ycor()

    segments[index].goto(x, y)

    # Move the segment 0 to where the head is

    if len(segments) > 0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x,y)

    move()

    time.sleep(delay)

    wn.mainloop()

  32. PLS HELP ME
    segment.goto(1000, 1000)

    NameError: name 'segment' is not defined

  33. mine wont work the error code is this:
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor < 290:

    TypeError: '<' not supported between instances of 'method' and 'int'

  34. When I hit the border is says TypeError: object of type 'Turtle' has no len()

    and here is my code:
    import turtle

    import time

    import random

    delay = 0.175

    #set up screen

    wn = turtle.Screen()

    wn.title("Snake Game by Hamza A.")

    wn.bgcolor("green")

    wn.setup(width= 600, height= 600)

    wn.tracer(0)

    #Snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("light green")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    #Snake food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("circle")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    #Functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    #Keyboard binding

    wn.listen()

    wn.onkeypress(go_up, "Up")

    wn.onkeypress(go_down, "Down")

    wn.onkeypress(go_left, "Left")

    wn.onkeypress(go_right, "Right")

    #Main game loop

    while True:

    wn.update()

    # Check for collision with border

    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"

    #Hide the segments

    for segments in segments:

    segments.goto(1000,1000)

    # Check for collision with food

    if head.distance(food)<20:

    # Move food to random spot

    x = random.randint(-290,290)

    y = random.randint(-290,290)

    food.goto(x,y)

    # 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)

    # mover the end segments first in reverse

    for index in range(len(segments)-1, 0, -1):

    x = segments[index – 1].xcor()

    y = segments[index – 1].ycor()

    segments[index].goto(x,y)

    # move segment 0 to where the head is

    if len(segments)>0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x, y)

    move()

    time.sleep(delay)

    wn.mainloop()import turtle

    import time

    import random

    delay = 0.175

    #set up screen

    wn = turtle.Screen()

    wn.title("Snake Game by Hamza A.")

    wn.bgcolor("green")

    wn.setup(width= 600, height= 600)

    wn.tracer(0)

    #Snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("light green")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    #Snake food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("circle")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    #Functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    #Keyboard binding

    wn.listen()

    wn.onkeypress(go_up, "Up")

    wn.onkeypress(go_down, "Down")

    wn.onkeypress(go_left, "Left")

    wn.onkeypress(go_right, "Right")

    #Main game loop

    while True:

    wn.update()

    # Check for collision with border

    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"

    #Hide the segments

    for segments in segments:

    segments.goto(1000,1000)

    # Check for collision with food

    if head.distance(food)<20:

    # Move food to random spot

    x = random.randint(-290,290)

    y = random.randint(-290,290)

    food.goto(x,y)

    # 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)

    # mover the end segments first in reverse

    for index in range(len(segments)-1, 0, -1):

    x = segments[index – 1].xcor()

    y = segments[index – 1].ycor()

    segments[index].goto(x,y)

    # move segment 0 to where the head is

    if len(segments)>0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x, y)

    move()

    time.sleep(delay)

    wn.mainloop()import turtle

    import time

    import random

    delay = 0.175

    #set up screen

    wn = turtle.Screen()

    wn.title("Snake Game by Hamza A.")

    wn.bgcolor("green")

    wn.setup(width= 600, height= 600)

    wn.tracer(0)

    #Snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("light green")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    #Snake food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("circle")

    food.color("red")

    food.penup()

    food.goto(0,100)

    segments = []

    #Functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    #Keyboard binding

    wn.listen()

    wn.onkeypress(go_up, "Up")

    wn.onkeypress(go_down, "Down")

    wn.onkeypress(go_left, "Left")

    wn.onkeypress(go_right, "Right")

    #Main game loop

    while True:

    wn.update()

    # Check for collision with border

    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"

    #Hide the segments

    for segments in segments:

    segments.goto(1000,1000)

    # Check for collision with food

    if head.distance(food)<20:

    # Move food to random spot

    x = random.randint(-290,290)

    y = random.randint(-290,290)

    food.goto(x,y)

    # 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)

    # mover the end segments first in reverse

    for index in range(len(segments)-1, 0, -1):

    x = segments[index – 1].xcor()

    y = segments[index – 1].ycor()

    segments[index].goto(x,y)

    # move segment 0 to where the head is

    if len(segments)>0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x, y)

    move()

    time.sleep(delay)

    wn.mainloop()

  35. If head.xcor( ) > 290 or head.xcor( ) <-290 or head.ycor( )>290 or head.ycor( )<-290:

    Error: indetationError: unindent does not match any outer inderation level

  36. Yo I hope im not too late. Soo my problem is that my turtle draws lines and i dont know why so could you please help me i need a solution for this pls

  37. Hello… when I put clear.segments() the segment instantly disappears when I eat a circle. if you need I can copy the code please

  38. I have a problem, it says when I put the segment.goto(1000, 1000) part in my code, terminal says there is a nameerror

  39. Hello, i have a problem. My snake won't stay together and glitches on my screen. I have checked the code but i can't find the problem. You have any ideas of how i can make it work again?

  40. Hello, I have a problem. When I hit the border only the first segment dissapears not all of them. This is my code:

    #snake game

    import turtle

    import time

    import random

    delay = 0.1

    # set up the screen

    wn = turtle.Screen()

    wn.title("Snake Game")

    wn.bgcolor("green")

    wn.setup(width=600, height=600)

    wn.tracer(0) # turns off the screen updates

    #snake head

    head = turtle.Turtle()

    head.speed(0)

    head.shape("square")

    head.color("black")

    head.penup()

    head.goto(0,0)

    head.direction = "stop"

    # Snake Food

    food = turtle.Turtle()

    food.speed(0)

    food.shape("square")

    food.color("red")

    food.penup()

    food.goto(0,100)

    food.direction = "stop"

    segments = []

    # functions

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move():

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20)

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20)

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20)

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20)

    # keyboard bindings

    wn.listen()

    wn.onkeypress(go_up, "w")

    wn.onkeypress(go_down, "s")

    wn.onkeypress(go_left, "a")

    wn.onkeypress(go_right, "d")

    # main game loop

    while True:

    wn.update()

    # Check for collision with the border

    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'

    # Hide the segments

    for segment in segments:

    segment.goto(100000, 100000)

    # Clear segments list

    segments.clear()

    #check for a collision with the food

    if head.distance(food) < 20:

    # move food to random position

    x = random.randint(-290, 290)

    y = random.randint(-290, 290)

    food.goto(x, y)

    #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)

    # move the end segments first 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)

    # Move segment 0 to where the head is

    if len(segments) > 0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x,y)

    move()

    time.sleep(delay)

    wn.mainloop()

  41. I Am facing a Problem here,
    1. My segments aren't visible whenever I apply the " segment.clear() " line but they do appear when I comment it out.
    2. When I apply the " for segment in segments: segment.goto(1000, 1000) " my segements don't increase when they collide with the food

    Kindly Help me out Please

    #Import Section

    import turtle

    import time

    import random

    #—————————————————————————————–

    #Setting Time Delay

    delay = 0.1

    #Screen Setup—————————————

    #wn – Window

    wn= turtle.Screen()

    wn.title("Snake Game @Pradyum S ( 216230307013 )")

    wn.bgcolor("light cyan") #Color of the Screen

    wn.setup(width=600, height=600) #Size

    wn.tracer(0) #turns off the screen updates which allows the module go fastest as possible

    #Snake Setup—————————————

    head = turtle.Turtle()

    head.speed(0) #animation speed of the turtle #'0 is the fastest'

    head.shape("square") #shape of the snake

    head.color("green") #color of the snake

    head.penup() #for not drawing anything

    head.goto(0,0) #keeping the snake in center at the start

    head.direction="stop" #direction of the head to move

    #Snake Body Setup—————————————

    segments = []

    #Snake Food Setup—————————————

    food = turtle.Turtle()

    food.speed(0) #animation speed of the turtle #'0 is the fastest'

    food.shape("circle") #shape of the snake

    food.color("dark khaki") #color of the snake

    food.penup() #for not drawing anything

    food.goto(0,0) #keeping the snake in center at the start

    food.direction="stop" #direction of the head to move

    #Controls—————————————

    def go_up():

    head.direction = "up"

    def go_down():

    head.direction = "down"

    def go_left():

    head.direction = "left"

    def go_right():

    head.direction = "right"

    def move(): #Direction we want to move our snake

    if head.direction == "up":

    y = head.ycor()

    head.sety(y + 20) #+20 blocks, snake will move up

    if head.direction == "down":

    y = head.ycor()

    head.sety(y – 20) #-20 blocks, snake will move down

    if head.direction == "left":

    x = head.xcor()

    head.setx(x – 20) #-20 blocks, snake will move left

    if head.direction == "right":

    x = head.xcor()

    head.setx(x + 20) #+20 blocks, snake will move right

    #Keyboard Aligning—————————————

    wn.listen()

    wn.onkeypress(go_up, "w")

    wn.onkeypress(go_down, "s")

    wn.onkeypress(go_left, "a")

    wn.onkeypress(go_right, "d")

    #Main Game Loop & Calling Functions—————————————

    while True: #This loop auto-updates the screen

    wn.update() #Updates the Screen

    #GameOverRules

    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"

    #Hiding Snake Body after GameOver

    for segment in segments:

    segment.goto(1000, 1000)

    #Clear Segments list

    segments.clear()

    #Collision of SNAKE & FOOD

    if head.distance(food) < 20:

    #Moving the Food Randomly

    x = random.randint(-290, 290) #Not letting the Food Spawn out of the box on "X" Coordinate

    y = random.randint(-290, 290) #Not letting the Food Spawn out of the box on "Y" Coordinate

    food.goto(x,y)

    #Snake Body "Segment"

    new_segment = turtle.Turtle()

    new_segment.speed(0) #food Animation Speed

    new_segment.shape("square")

    new_segment.color("light green")

    new_segment.penup()

    segments.append(new_segment)

    #Moving the end segments first ( 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)

    #Moving Segments from 0 towards the Snake

    if len(segments) > 0:

    x = head.xcor()

    y = head.ycor()

    segments[0].goto(x,y)

    move() #calling the move function

    time.sleep(delay) #delay loop

    wn.mainloop()#Let's the Screen not be closed by itself

    #—————————————————————————————–

  42. Hey Guys,
    if you want your snake to come out of the other side, after leaving your boundary of 300, you can use this code. (edit: no hiding of segments needed)

    if head.ycor()> 290:
    head.goto(head.xcor(), -280)

    head.direction = 'up'

    if head.ycor()<-290:

    head.goto(head.xcor(), 280)

    head.direction = 'down'

    if head.xcor()> 290:

    head.goto(-280, head.ycor())

    head.direction = 'right'

    if head.xcor()< -290:

    head.goto(280, head.ycor())

    head.direction = 'left'

    (its like the snake that i remember from my brick nokia back in the day)
    have fun 🙂

  43. I do not know if this is what you meant but @3:12 you can substitute the segment.goto(1000,1000) with segment.hideturtle()

Leave a Reply

Your email address will not be published.