| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 
 | import Tkinter as tk
import time
 
DEBUG = True
def debug(s):
    if DEBUG: print(s)
 
COUNT = 4
Y_MAX = X_MAX = 400 
RADIUS = 20
DELAY = 20
 
centers = [ (50, 50), (300, 50), (50, 300), (300, 300), ]
deltas = [ (10, 10) ] * COUNT
colors = ['red','blue','green','yellow' ]
idents = [ 0 ] * COUNT
timer = None
 
def check_wall_collision(v, du, MIN, MAX):
    dv = du
    if not (MIN <= v <= MAX):
        if v < MIN:
            b = MIN
        else:
            b = MAX
        v = 2 * b - v
        dv = -du
    return v, dv
 
 
last_move = time.clock()
 
def move():
    global timer, last_move
    for i in range(COUNT):
        x0, y0 = centers[i]
        dx, dy = deltas[i]
        x1, dx = check_wall_collision(x0 + dx, dx, RADIUS, X_MAX - RADIUS) 
        y1, dy = check_wall_collision(y0 + dy, dy, RADIUS, Y_MAX - RADIUS) 
        assert RADIUS <= x1 <= X_MAX - RADIUS, 'fatal: x1 out of range: (%d, %d)' % (x0, x1)
        assert RADIUS <= y1 <= Y_MAX - RADIUS, 'fatal: y1 out of range: (%d, %d)' % (y0, y1)
        iid = idents[i]
        canvas.move(iid, x1-x0, y1-y0)
        centers[i] = x1, y1
        deltas[i] = dx, dy
    now = time.clock()
    debug('delta: %.3f' % (now - last_move))
    last_move = now    
    timer = app.after(DELAY, move)
 
def do_start():
    if timer is None:
        move()
 
def do_stop():
    global timer
    if timer is not None:
        app.after_cancel(timer)
        timer = None
 
if __name__ == '__main__':
 
    app = tk.Tk()
 
    canvas = tk.Canvas(width=X_MAX,height=Y_MAX,bg='dark grey')
    canvas.grid(row=1,column=1,rowspan=3)
 
    for i in range(COUNT):
        cx, cy = centers[i]
        color = colors[i]
        coords = (cx - RADIUS, cy - RADIUS,
            cx + RADIUS, cy + RADIUS,)
 
        idents[i] = canvas.create_oval(coords, fill=color)
 
    tk.Button(text='Go!',command=do_start).grid(row=1,column=2)
    tk.Button(text='Stop!',command=do_stop).grid(row=2,column=2)
    tk.Button(text='Quitter',command=app.quit).grid(row=3,column=2)
 
    tk.mainloop() | 
Partager