I have a bunch of turtle objects on the screen. They don't do anything yet but I am trying to detect collision of turtle objects the simplest way. I know I am supposed to compare all turtle elements turtle.pos
with the turtle.pos
of all the other elements, but I am not sure how to do it.
Also, I am concerned with not comparing any one item with its own position.
from turtle import *
import random
screen = Screen()
screen.bgcolor("grey")
screen.setup(width=800, height=600)
my_turtles = []
for i in range(10):
turtle = Turtle()
turtle.penup()
turtle.setx(random.randrange(-50, 50))
turtle.sety(random.randrange(-50, 50))
my_turtles.append(turtle)
#for t in turtles:
# if t.pos == anyother t.pos_except_itself
# do something
screen.listen()
screen.exitonclick()
The last thing you want to do is directly compare one turtle.position()
with another turtle.position()
. The reason is that turtles wander a floating point plane, and directly comparing coordinate values rarely works the way you want. Instead, you need to decide on the minimal distance between (the centers of) two turtles that will be considered a collision . Once you know that distance, then a loop like:
for a in turtles:
if any(a != b and a.distance(b) < SAFE_MARGIN for b in turtles):
# collision, do something here
Here's a rework of your code that does this, causing any turtles that have overly invaded each other's personal space to blink:
from turtle import Screen, Turtle
from random import randrange
RADIUS = 10
def blink_turtles():
for a in turtles:
if any(a != b and a.distance(b) < RADIUS for b in turtles):
a.color(*reversed(a.color()))
screen.ontimer(blink_turtles, 1000)
screen = Screen()
screen.setup(width=800, height=600)
turtles = []
for _ in range(15):
turtle = Turtle()
turtle.hideturtle()
turtle.shape('turtle')
turtle.color('red', 'green')
turtle.penup()
turtle.goto(randrange(-50, 50), randrange(-50, 50))
turtle.showturtle()
turtles.append(turtle)
blink_turtles()
screen.exitonclick()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.