How do I assign values to a variable with a schedule function in pyglet?

耗尽温柔 提交于 2019-12-13 05:10:01

问题


With the following code

x=1.0
def update(dt):
    space.step(dt)
def xprinter(self, x):
    print (x)
    return x+1

if __name__ == "__main__":


    x=pyglet.clock.schedule(xprinter,x)
    pyglet.clock.schedule_interval(update, 1.0/60)
    pyglet.app.run()

My return is simply 1.0 over and over. I would like for the value to be updated with each call. What am I missing?


回答1:


The design here is based on that your function rely on returning a result.
Which causes a problem because Pyglet's internal functions are in charge of executing that function at a interval, meaning you're not the one executing the call - and there for you're not the one getting that return value, Pyglet is.

And since there's no meaningful way for Pyglet to relay that returned value (there are ways, but they involve hooking in and overriding certain internal functions), you will never see that return value.

The quick and easy workaround would be to do:

x=1.0
def update(dt):
    space.step(dt)

def xprinter(self):
    global x
    print(x)
    x += 1

if __name__ == "__main__":
    pyglet.clock.schedule(xprinter)
    pyglet.clock.schedule_interval(update, 1.0/60)
    pyglet.app.run()

This way, the schedule call will update the global variable x rather than returning the result of the math equation.

A more neat approach would be to define a class with the x attribute and pass a class instance to the pyglet.clock.schedule():

class player():
    def __init__(self):
        self.x = 0

def update(dt):
    space.step(dt)

def xprinter(self, p):
    print(p)
    p.x += 1

if __name__ == "__main__":
    p = player()
    x = pyglet.clock.schedule(xprinter, p)
    pyglet.clock.schedule_interval(update, 1.0/60)
    pyglet.app.run()

And if I'm not completely out of the ball park, this would remember the value across clock ticks, because of the instance.

This is also usually what you'll be using the schedule for, doing player / game / animation updates.



来源:https://stackoverflow.com/questions/52935271/how-do-i-assign-values-to-a-variable-with-a-schedule-function-in-pyglet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!