How do I assign values to a variable with a schedu

2019-08-19 08:29发布

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条回答
不美不萌又怎样
2楼-- · 2019-08-19 08:57

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.

查看更多
登录 后发表回答