0

My Code:

import Tkinter
from decimal import Decimal
import numpy
import time

__author__ = 'Sayakiss'

class Ball:

    def __init__(self, position, velocity, radius, name):
        self.position = position
        self.velocity = velocity
        self.radius = radius
        self.name = name


class BallSimulator:

    def __init__(self, balls):
        self.balls = balls

    def sim(self, delta):
        for ball in self.balls:
            ball.position[0] += ball.velocity[0] * delta
            ball.position[1] += ball.velocity[1] * delta


class BallCanvas(Tkinter.Canvas):

    def draw(self):
        for ball in self.simulator.balls:
            self.create_oval(ball.position[0] - ball.radius,
                             ball.position[1] - ball.radius,
                             ball.position[0] + ball.radius,
                             ball.position[1] + ball.radius)

    def sim(self):
        # while True: it should be sim again and again, but I couldn't add a while True here, what should I do?
        self.delete("all")
        self.draw()
        time.sleep(0.01)
        self.simulator.sim(Decimal('0.01'))

    def __init__(self, ball_simulator, master=None):
        Tkinter.Canvas.__init__(self, master)
        self.simulator = ball_simulator
        self.sim()


position = numpy.array([Decimal('10'), Decimal('10')])
velocity = numpy.array([Decimal('1'), Decimal('2')])
radius = 5
name = 'b1'
ball = Ball(position, velocity, radius, name)
simulator = BallSimulator([ball])

root = Tkinter.Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
canvas = BallCanvas(simulator, master=root)
canvas.grid(column=0, row=0, sticky=(Tkinter.N, Tkinter.W, Tkinter.E, Tkinter.S))
root.mainloop()
root.destroy()

My idea is:

Initialize Canvas =>
    clean Canvas => draw ball => calculate the next position of the ball +
         ^                                                               |
         |                                                               |
         +---------------------------------------------------------------+

When I dive into the Canvas, I find the only way to execute the BallCanvas.sim() in the root.mainloop() is bind it to an event. I read the canvas doc through, but I couldn't find an event which always triggered.

So, what should I do now to implement such a Ball Moving Simulator?

martineau
  • 119,623
  • 25
  • 170
  • 301
Sayakiss
  • 6,878
  • 8
  • 61
  • 107

0 Answers0