Advertisement
here2share

# turtle_threading.py

Oct 30th, 2019
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. # turtle_threading.py
  2.  
  3. from threading import Thread, active_count
  4. from turtle import Turtle
  5. import Queue as queue
  6. import random
  7.  
  8. def test1():
  9.     for _ in range(360):
  10.         graphics.put(turtle1.forward)
  11.         graphics.put(turtle1.left)
  12.  
  13. def test2():
  14.     while not color in turtle:
  15.         0
  16.     ACTIONS = [turtle[color].forward, turtle[color].right, turtle[color].left]
  17.     _color = color
  18.     for z in range(100):
  19.         move = random.choice(ACTIONS)
  20.         for i in 'x'*random.randint(0,9):
  21.             graphics.put(move)
  22.         graphics.put(turtle[_color].forward)
  23.  
  24. def process_queue():
  25.     while not graphics.empty():
  26.         (graphics.get())(1)
  27.  
  28.     if active_count() > 1:
  29.         turtle.ontimer(process_queue, 1)
  30.  
  31. graphics = queue.Queue(16)  # size = number of hardware threads you have - 1
  32.  
  33. QUEUE_SIZE = 1  # set higher the more hardware threads you have
  34. COLORS = ['red', 'orange', 'blue', 'green', 'magenta', 'gray', 'pink']
  35.  
  36. turtle1 = Turtle('turtle')
  37. turtle1.speed('fastest')
  38. thread1 = Thread(target=test1)
  39. thread1.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
  40. thread1.start()
  41.  
  42. turtle = {}
  43. for color in COLORS:
  44.     turtle[color] = Turtle('turtle')
  45.     turtle[color].color(color)
  46.     turtle[color].setheading(random.randint(0, 360))
  47.     turtle[color].speed('fastest')
  48.     thread2 = Thread(target=test2)
  49.     thread2.daemon = True
  50.     thread2.start()
  51.  
  52. process_queue()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement