Monday, 24 September 2018

How to run the same method concurrently without waiting for loop to end?

As seen in my code below, I have a function that produces an animation of a circle when the user clicks on the window. My problem is, for me to have another circle appear and move after one is already spawned, I have to wait for the previous one to finish its loop of movement. After one circle has finished its "i in range" loop at the end of the snowfall function, then I can click and produce another circle. I want to be able to click at any time and have as many circles moving simultaneously as I want (I'm aware I've limited it to 10 times in the code under the function). It looks like I need away to run the same method multiple times concurrently.

from graphics import*
from random import*


win = GraphWin("Graphics Practice", 500, 500)

colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"]

def snowfall(randColour):
    point = win.getMouse()
    circle = Circle(point, 40)
    circle.draw(win)
    circle.setFill(colours[randColour])
    for i in range(1000):
        circle.move(0, 1)
        time.sleep(0.002)

randColour = randint(0, 8)
for i in range (10):
    repeatColour = randColour
    snowfall(randColour)
    randColour = randint(0, 8)
    while randColour == repeatColour:
        randColour = randint(0, 8)

win.getMouse()
win.close()

One of my failed attempts at multithreading this:

from graphics import*
from random import*


win = GraphWin("Graphics Practice", 500, 500)

colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"]

def snowfall(randColour):
    point = win.getMouse()
    circle = Circle(point, 40)
    circle.draw(win)
    circle.setFill(colours[randColour])
    for i in range(1000):
        circle.move(0, 1)
        time.sleep(0.002)

randColour = randint(0, 8)
t1 = threading.Thread(target = snowfall, args = randColour)
for i in range (10):
    repeatColour = randColour
    t1.start()
    t1.join()
    randColour = randint(0, 8)
    while randColour == repeatColour:
        randColour = randint(0, 8)

win.getMouse()
win.close()



from How to run the same method concurrently without waiting for loop to end?

No comments:

Post a Comment