多线程碰到边缘就反弹弹球例子_multithread bounce on edge turtle example

"""
   多线程碰到边缘就反弹弹球例子_multithread bounce on edge turtle example 
"""
from time import sleep
from queue import Queue
from random import randint
from turtle import Screen, Turtle
from threading import Thread, active_count

QUEUE_SIZE = 1 

def bounce_on_edge(turtle):
    """
       碰到边缘就反弹的一个线程
    """
    dx = randint(-5,5)
    dy = randint(-5,5)
    x, y = turtle.position()
    screen = turtle.getscreen()
    width = screen.window_width()
    height = screen.window_height()
    while True:        
        if abs(x) > width//2: dx = -dx
        if abs(y) > height//2 : dy = -dy
        x = x + dx
        y = y + dy
        actions.put((turtle.goto,  (x,y)))        

def process_queue():
    """处理队列,动作列表不空就执行"""
    while not actions.empty():
        action, argument = actions.get()
        action(argument)
        screen.update()

    if active_count() > 1:
        screen.ontimer(process_queue, 100)

actions = Queue(QUEUE_SIZE)
 
for _ in range(4):         # 创建4只海龟
    t = Turtle("circle", visible=False)
    t.penup()
    t.speed(0)
    t.color('blue')        
    t.showturtle()
    Thread(target=bounce_on_edge, args=[t], daemon=True).start()

screen = Screen()
screen.tracer(0)
screen.delay(0)
process_queue()

screen.mainloop()