Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # turtle_threading.py
- from threading import Thread, active_count
- from turtle import Turtle
- import Queue as queue
- import random
- def test1():
- for _ in range(360):
- graphics.put(turtle1.forward)
- graphics.put(turtle1.left)
- def test2():
- while not color in turtle:
- 0
- ACTIONS = [turtle[color].forward, turtle[color].right, turtle[color].left]
- _color = color
- for z in range(100):
- move = random.choice(ACTIONS)
- for i in 'x'*random.randint(0,9):
- graphics.put(move)
- graphics.put(turtle[_color].forward)
- def process_queue():
- while not graphics.empty():
- (graphics.get())(1)
- if active_count() > 1:
- turtle.ontimer(process_queue, 1)
- graphics = queue.Queue(16) # size = number of hardware threads you have - 1
- QUEUE_SIZE = 1 # set higher the more hardware threads you have
- COLORS = ['red', 'orange', 'blue', 'green', 'magenta', 'gray', 'pink']
- turtle1 = Turtle('turtle')
- turtle1.speed('fastest')
- thread1 = Thread(target=test1)
- thread1.daemon = True # thread dies when main thread (only non-daemon thread) exits.
- thread1.start()
- turtle = {}
- for color in COLORS:
- turtle[color] = Turtle('turtle')
- turtle[color].color(color)
- turtle[color].setheading(random.randint(0, 360))
- turtle[color].speed('fastest')
- thread2 = Thread(target=test2)
- thread2.daemon = True
- thread2.start()
- process_queue()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement