-1

No matter how hard I try, the sprite does not move, the code is correct, I would not ask, but I have a hopeless situation, help !! I have already used KeyStateHandler but it doesn't work either.

import pyglet
from pyglet.window import keys

x = 300
y = 300                                           

w=pyglet.window.Window(600,600)
i = 
pyglet.resource.image("pl.png")
sprite = pyglet.sprite.Spite(i)

@w.event
def on_draw():
    w.clear()
    sprite.draw(x,y)
@w.event
def key(symbol, modifiers):
    if symbol == K.UP:
       x+=10
Adilet Usonov
  • 139
  • 1
  • 6
  • 1
    Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results differ from what you expected. You state "the sprite does not move, the code is correct". I don't understand what you mean: if you expect the sprite to move, then how is the code "correct"? Where is that trace that shows the program flow reaching the expected statements? Where did you prove that the x values change as expected? – Prune Aug 10 '20 at 16:58

1 Answers1

0

If you want to modify a global variable inside of a function, then you need to specify that it is global.

@w.event
def key(symbol, modifiers):
    global x
    if symbol == K.UP:
       x += 10

If you don't, you're actually just creating a local variable. x += 10 is the same thing as x = x + 10. If you write this in a function and don't declare x as global, python will think that you want to create a local variable x that's equal to the global variable x plus 10. When the function exits, the local variable is destroyed and the global variable unchanged.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50