Want to make a ball to change trajectory when I click on it. But in my case when I click on some ball, movement not always happens on the ball that was clicked but on another one. Tried to change place for onclic method, but always the same. print shows that function is called for wrong object. Don't know how to make it right.
import random
import turtle
def my_function(x, y):
print(x, y)
xd[index] = -xd[index]
print (myballs)
window = turtle.Screen()
window.delay(5)
message = turtle.Turtle()
message.hideturtle()
MAXX, MAXY = window.screensize()
BALLSIZE = 1
border = turtle.Turtle()
border.hideturtle()
border.speed(0)
border.up()
border.goto(MAXX, MAXY)
border.down()
border.pensize(1)
border.color('red')
border.goto(MAXX, -MAXY)
border.goto(-MAXX, -MAXY)
border.goto(-MAXX, MAXY)
border.goto(MAXX, MAXY)
balls = []
balls.append(turtle.Turtle())
balls.append(turtle.Turtle())
x = [0] * len(balls)
y = [0] * len(balls)
xd = [0] * len(balls)
yd = [0] * len(balls)
for myballs in balls:
x, y = random.randint(-MAXX + 1, MAXX - 1), random.randint(-MAXY + 1, MAXY - 1)
myballs.hideturtle()
myballs.speed(0)
myballs.up()
myballs.shapesize(BALLSIZE)
myballs.shape('circle')
myballs.goto(x, y)
myballs.showturtle()
index = balls.index(myballs)
speed = 1
xd[index] = speed
yd[index] = speed
myballs.onclick(my_function)
while True:
for myballs in balls:
index = balls.index(myballs)
x, y = myballs.pos()
if x+BALLSIZE*10 >= MAXX or x-BALLSIZE*10 <= -MAXX:
xd[index] = -xd[index]
if y+BALLSIZE*10 >= MAXY or y-BALLSIZE*10 <= -MAXY:
yd[index] = -yd[index]
x = x + xd[index]
y = y + yd[index]
myballs.goto(x, y)