Alright I have an issue with sprite movement on screen. I have a certain way I want things to happen as follows:
- When I press the left movement key, and while holding it, press the right movement key, I want the sprite to go RIGHT until i take my finger off the right key, then it will continue left until i also remove my finger from the left movement key.
- I also want this method for the up/down keys
- To add to this, when i press one of the up or down keys, and i then press, one of the left/right keys, i want to see the sprite move left or right until one of them are unpressed as well.
To summarize, I want the most recent directional key press to take movement priority, and when it is unpressed I want the next most recent key pressed to take movement priority. I also so not want diagonal movement, but that’s not an issue so far.
here is my code so far
m=pygame.key.get_pressed()
if m[K_d]:
movey=0
movex=speed
elif m[K_a]:
movey=0
movex=-speed
elif m[K_w]:
movex=0
movey=-speed
elif m[K_s]:
movex=0
movey=speed
This does 50% of what I want it to. The problem is, the code itself take priority in what is happening, so the result is when I just press the ‘A’ key, I move left, and then at the same time press the ‘D’ key, i move right. Then if i just press the ‘D’ key, I move right, but then when I also press the ‘A’ key I keep moving right when I want to be moving left at that point. I’ve tried if/not/and nested different ways but have failed so far.
How do i fix this?
Edit: Here is what I came up with with the help of Bartlomiej.
if e.type==KEYDOWN:
if e.key==pygame.K_a:
keylist.append(1)
#keylist.reverse()
print keylist[-1:]
if e.key==pygame.K_d:
keylist.append(2)
#keylist.reverse()
print keylist[-1:]
if e.type==pygame.KEYUP:
if e.key==pygame.K_a:
keylist.remove(1)
print keylist
if e.key==pygame.K_d:
keylist.remove(2)
print keylist
if keylist[-1:]==[1]:
walk=[-spd, 0]
print 'WTF MOVE LEFT'
elif keylist[-1:]==[2]:
walk=[spd, 0]
print 'WTF MOVE RIGHT'
else:
print 'WTFFFFFF'
walk=[0, 0]
This works how I want and all i need to do now is minimize it and make it more elegant as a function but i got the idea down now. Thanks again Bartlomiej for helping me understand python and coding in general a bit better. Really appreciate it.
I always solved the problem like this: (a partial solution):
This doesn’t stop movement when the previous key has been unpressed.
EDIT: It is not impossible, its just not that useful. You could for example have 2 lists that would imitate a stack. When the list is empty your character will not move. With each keydown, you append the key to the end of list. Every keyup, you remove the key from the list. That way, the most recent key pressed will be at the end of the list, and if you unpress the last recent will also be at the end of the list.
A small example:
the in the move method you try this:
You get the last element in the list if it exists, move the character in the right direction.