I’m trying to do collision detection over the members of a list of turtles, so that a variable returns a Boolean to break a while true loop. It works with ONE of the turtles, but not the others. It also only prints the distance (for debug) for the one that collision works with. What’s confusing is the exact same syntax used in the collision function works just fine in the ball/wall collision detection loops.
import turtle
from turtle import Screen
import random
from random import randrange
screen = turtle.Screen()
screen.setup(500, 500)
screen.title('Balls Bounce')
friend = turtle.Turtle()
friend.shape('turtle')
friend.color('green')
friend.turtlesize(3)
def friendUp():
friend.setheading(90)
friend.forward(45)
def friendDown():
friend.setheading(270)
friend.forward(45)
def friendRight():
friend.setheading(0)
friend.forward(45)
def friendLeft():
friend.setheading(180)
friend.forward(45)
screen.onkey(friendUp, "Up")
screen.onkey(friendLeft, "Left")
screen.onkey(friendRight, "Right")
screen.onkey(friendDown, "Down")
screen.listen()
def createBall():
ball = turtle.Turtle(shape="circle")
ball.penup()
ball.color("Red")
ball.turtlesize(3)
ball.setheading(randrange(361))
ball.forward(5)
return ball
balls = []
for i in range(5):
b = createBall()
balls.append(b)
bodySize = 80
halfBodySize = bodySize / 2
collisionDistance = 5
isCollision = False
def collision(balls, friend):
distance = 0
for b in balls:
distance = b.distance(friend)
print(distance // 1)
if distance < halfBodySize:
print('Collision!')
global isCollision
isCollision = True
break
return isCollision
while True:
collision(balls, friend)
if isCollision == True:
break
for b in balls:
b.forward(5)
xPos = b.position()[0]
yPos = b.position()[1]
if xPos > 250 or xPos < -250:
b.forward(-5)
b.setheading(randrange(361))
if yPos > 250 or yPos < -250:
b.forward(-5)
b.setheading(randrange(361))
screen.mainloop()
I’ve tried using map and enumerate, but they keep returning issues that I can’t seem to figure out. For instance, using enumerate returns tuple issues, and I’m not sure I set up the syntax for it correctly. Map has similar issues.
daniels688 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.