0

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
    That's because you're returning `x+1` but aren't storing it anywhere. A simpler approach would be to do `global x; x += 1; print(x)` in your `xprinter()` function. To my knowledge, since you're working with a timer, it's a internally called function within pyglet, meaning it's not called by you - there for the return value is (if nothing else) extremely hard to relay back to you in a meaningful way. Instead of trying to catch the return value, you should use global variables or pass a instance of a class that the function modifies. – Torxed Oct 23 '18 at 07:05
  • You responded just in the nick of time. Thank you so much, this solved my problem and saved my project. – physicsisphun Oct 25 '18 at 02:54

1 Answers1

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.

Torxed
  • 22,866
  • 14
  • 82
  • 131