How to find a turtle collision

Question:

I’m trying to make a snake game with turtle in python.
What I am trying to do is when the snake goes in the circle the snake gets longer.

I’m also trying to make the circle go in a different place every time using the random module and I don’t want the snake to get out of the screen.

from turtle import Turtle, Screen
import random

wn = Screen()
wn.bgcolor('lightblue')

snake = Turtle()
snake.shape("square")
snake.shapesize(1, 1, 1)

snake.color('red')
snake.penup()

speed = 3


circle = Turtle()
circle.shape("circle")
circle.shapesize(0.8, 0.8, 0.8)
circle.color('blue')

def travel():
    snake.forward(speed)
    wn.ontimer(travel, 10)
#controls for using arrows with keyboard
wn.onkey(lambda: snake.setheading(90), 'Up')
wn.onkey(lambda: snake.setheading(180), 'Left')
wn.onkey(lambda: snake.setheading(0), 'Right')
wn.onkey(lambda: snake.setheading(270), 'Down')

wn.listen()

travel()

wn.mainloop()
Asked By: Abdullah

||

Answers:

Turtle doesn’t contain any built in way to detect collisions between two Turtle objects. What you can do is define a collision function based on the difference between the position of snake and circle. Using Turtles built in distance function, this is a easy enough task. The radius, 20 in the case, can be tweaked for precision

import turtle

def isCollision(t1, t2):
    return t1.distance(t2) < 20

To send the circle Turtle to a random position, you can make use of the goto and randit functions to have it move to a random x and y coordinate

import turtle
from random import randint

circle.goto(randint(0,100),randint(0,100))

References:

Detecting collision in Python turtle game

How to send turtle to random position?

Answered By: Patrick Custer