Python function (viztask.waitdraw)

115 Views Asked by At

We have this two codes. The first one works and the second one doesn't. We have commented all the lines and we have verified that, in the second one, the code works until we introduce the line:

d = yield viztask.waitDraw()

In the second one, it doesn't even print "collision", which is the first line, even if the viztask.waitDraw() is declared below.

Working version:

ball.enable(viz.COLLIDE_NOTIFY)
def onCollide(e):
        print('collision')
        global count 
        count = count+1
        print(count)

viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

def testReactionTime(threadName):
    print 'boolTime: '
    print(boolTime)
    while boolTime:
        #Wait for next frame to be drawn to screen
        d = yield viztask.waitDraw()
        #Save display time
        displayTime = d.time
        #Wait for keyboard reaction
        d = yield viztask.waitMouseUp(viz.MOUSEBUTTON_LEFT)
        #Calculate reaction time
        reactionTime = d.time - displayTime
        print(reactionTime)

Non-working version:

ball.enable(viz.COLLIDE_NOTIFY)
def onCollide(e):
        print('collision')
        global count
        if e.obj2 == beginning:
            #Wait for next frame to be drawn to screen
            d = yield viztask.waitDraw()
            #Save display time
            displayTime = d.time
            #viztask.schedule( testReactionTime("h"))
            print('start time')
        elif e.obj2 == end:
            global reactionTime
            d = yield viztask.waitDraw()
            reactionTime = d.time - displayTime
            print("count = ")
            print(count)
            print("time = ")
            print(reactionTime)
        else:
            count = count+1
            print(count)
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )
1

There are 1 best solutions below

0
jonrsharpe On

When you yield from within it, you turn onCollide into a generator, not a standard function. Here's a minimal example to demonstrate the difference:

>>> def func():
    s = "foo"
    print(s)
    return s

>>> f = func()
foo # print
>>> f
'foo' # returned value
>>> def gen():
    """Identical to the above, but with 'yield' instead of 'return'."""
    s = "foo"
    print(s)
    yield s


>>> g = gen()
# nothing happens here
>>> g
<generator object gen at 0x02F1C648> # nothing yielded yet
>>> h = next(g)
foo # print
>>> h
'foo' # yielded value

Calling a generator sets it up, but nothing actually runs until you call next (or otherwise try to iterate over it). You will have to refactor your code to avoid using a generator as a callback function.