Я пытался порождать шары, используя onkey (spawn, "space"), и все было в порядке. Но как породить их, используя цикл? Кажется, что цикл «while True» внутри метода класса не позволяет делать итерации цикла «for» снаружи.
from turtle import *
from random import randint
w = 100
h = 100
BallList = []
sc = Screen()
sc.tracer(0)
class Ball(Turtle):
def __init__(self, x, y, s, c):
Turtle.__init__(self)
self.x = x
self.y = y
self.s = s
self.c = c
self.color(self.c)
self.shape("circle")
self.penup()
self.speed(0)
self.setheading(self.towards(randint(-100, 100), randint(-100, 100)))
def move(self):
self.forward(self.s)
def bounce(self):
if self.xcor() > w:
self.setheading(self.towards(-w, randint(-100, 100)))
if self.xcor() < -w:
self.setheading(self.towards(w, randint(-100, 100)))
if self.ycor() > h:
self.setheading(self.towards(randint(-100, 100), -h))
if self.ycor() < -h:
self.setheading(self.towards(randint(-100, 100), h))
def loop(self):
while True:
self.move()
self.bounce()
sc.update()
for i in range(10):
BallList.append(Ball(0, 0, 10, (0, 100, 0)))
BallList[i].loop()