1

I am trying to move only one sprite in a game loop including two sprites. I have included spr1 in the Bit.update() method so if w is pressed spr1.y -= 60. In other words the sprite is assigned to self in the hope that only spr1 will be moved when w is pressed. However, in the current code, pressing w moves both spr1 and spr2. How can I refer to and update only spr1 in the update method?

class Bit(games.Sprite):
    def update(self):
        if games.keyboard.is_pressed(games.K_w):
            self = spr1
            self.y -= 60

def main():
    spr1_image = games.load_image("spr1.png")
    spr1 = Bit(image = spr1_image,
                x = games.screen.width / 10,
                y = games.screen.height / 10)

    spr2_image = games.load_image("spr2.png")
    spr2 = Bit(image = spr2_image,
                x = games.screen.width * 9 / 10,
                y = games.screen.height * 9 / 10)

    games.screen.add(spr1)
    games.screen.add(spr2)

    games.screen.mainloop()

main()
cxw
  • 16,685
  • 2
  • 45
  • 81
Astrophe
  • 568
  • 1
  • 7
  • 25
  • It's not clear what you are trying to do. Each instance only refers to itself anyway; calling `self.y` only acts on the instance that `update` is called on. – Daniel Roseman May 10 '16 at 12:34
  • When I press w it moves both sprites. I'm trying to write the program so that pressing w moves spr1 alone. – Astrophe May 10 '16 at 12:41

1 Answers1

0

Edited The two sprites have different behavior, so you need different classes for them.

  1. In Bit, take out the self=spr1 line and you should be OK. In update(), self is whatever the current sprite is - spr1 or spr2.
  2. In main, change spr2 to

    spr2 = games.Sprite(image = spr2_image,    # <---- changed class
            x = games.screen.width * 9 / 10,
            y = games.screen.height * 9 / 10)
    

    Since spr2 doesn't need to respond to the keyboard, it doesn't need any behaviour that games.Sprite doesn't already provide. Therefore, you don't need to use Bit for it.

(Caveat: I haven't used livewires, so I may be missing something obvious :) )

cxw
  • 16,685
  • 2
  • 45
  • 81
  • I understand what you have done. My code has been simplified for clarity. There are tens of sprites in the actual program and I'm hoping to avoid writing a class for each one. I want some way (like self=spr1) to move single sprites. – Astrophe May 10 '16 at 13:18
  • Whether there's a better way depends on how you have structured your code. Rather than totally changing this question, would you please add a separate question, linking to this one, with more details about your many-sprite use case? Please include how you decide which sprite you want to move. For example, do you have some notion of a single sprite being the "active sprite" at any given time? Thanks! – cxw May 10 '16 at 14:05