Вопрос : Как мне поменять эти два шара на многие из них?
Создать class object
для каждого шара или пары шаров.
В результате все шары используют одни и те же правила.
Примечание : я показываю только один шар на class object
, не пара шаров и без обнаружения столкновений !
![enter image description here](https://i.stack.imgur.com/1CvcK.gif)
class Ball:
R = 15
def __init__(self, parent=None, color=None):
self.parent = parent
# Define shortcuts
radius = self.R
# Random bbox Ellipse coordinates of the ball.
x = random.randrange(50 + radius, 550 - radius)
y = random.randrange(50 + radius, 350 - radius)
coord1 = (x - radius, y - radius, x + radius, y + radius)
# Random direction
x = random.randrange(1, 10)
y = random.randrange(1, 10)
self.direction = (x, y)
# Save the bbox coordinate of the ball
self.coord1 = self.bbox(coord1, self.direction)
def bbox(self, coord1=None, direction=None):
# Return if NO move
if coord1 is None:
return self.coord1
return (coord1[0] + direction[0],
coord1[1] + direction[1],
coord1[2] + direction[0],
coord1[3] + direction[1]
)
def vector_rule(self):
# Get the estimated new bbox coordinate of the Ball
coord1 = self.bbox(self.coord1, self.direction)
# Define shortcuts
R = self.R
x1 = coord1[0]
y1 = coord1[1]
vx1 = self.direction[0]
vy1 = self.direction[1]
# Boundary check
if (x1 > 530 - R):
vx1 = -vx1
if (x1 < 35 + R):
vx1 = -vx1
if (y1 > 330 - R) or (y1 < 35 + R):
vy1 = -vy1
# Save the new direction - could be the same as before
self.direction = (vx1, vy1)
# Save the new bbox coordinate of the Ball
self.coord1 = self.bbox(self.coord1, self.direction)
# Return the move offsets
return self.direction
Использование :
Создание цикла class BallCanvas
в .create_balls(...
для создания class Ball
объектов и Canvas create_oval(...
объектов.
Накопление обоих в list
, цикл этотlist
для перемещения шаров с помощью canvas.move(...
, в результате Ball.vector_rules(...
.
class BallCanvas(tk.Canvas):
def __init__(self, parent, width, height):
self.parent = parent
super().__init__(parent, width=width, height=height)
self.create_rectangle(50, 50, 550, 350)
self.grid(row=1)
self.balls = []
self.create_balls()
def create_balls(self):
for n in range(5):
for color in ['red', 'blue']:
ball = Ball()
self.balls.append((self.create_oval(ball.bbox(), fill=color, tags='ball'), ball))
def move_balls(self):
for id, ball in self.balls:
new_x, new_y = ball.vector_rule()
self.move(id, new_x, new_y)
Основное применение :
Переместите Ball objects
с помощью Tkinter .after(150, ...
.
Это означает.все Ball objects
перемещаются каждые 150 мс.
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("610x430+650+280")
self.canvas = BallCanvas(self, width=600, height=400)
self.count = 200
self.after(500, self.move)
def move(self):
self.count -= 1
self.canvas.move_balls()
if self.count > 0:
self.after(150, self.move)
if __name__ == "__main__":
App().mainloop()
Проверено на Python: 3,5