[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] newbie



On 3/25/2010 6:03 PM, snet-1@xxxxxxx wrote:
Ah, yes I see what's happening, the last time I was doing it I was using:
...........KEYDOWN:
if event.key == K_LEFT:
foreward = True
...........KEYUP:
if event.key == K_LEFT:
foreward = False
meaning it was staying true, until key up but now it's not keeping the
output next time round & waiting for it again.
could you elaborate on this bit 'You could make the character move every
frame (eg. setting a speed and
moving by that speed per frame) until a KEYUP event happens', or is that
pretty much what I 'was' doing?

If you said, "On a KEYDOWN event, set speed to N and set direction to whatever; and on a KEYUP event, stop," then the result should be that the character keeps moving until you let go of the key. If you said, "On a KEYDOWN event, move," then you should get one frame of movement each time you press (not hold) the key.

My advice is to figure out what the player's trying to do first, like "move right", and then actually execute the movement in a separate bit of code ("if moving right..."). That's useful for things like replacing what keys do what, or having some non-interactive event steer the character.

Could I use "keys_down = pygame.key.get_pressed" then
"if keys_down[K_RIGHT] ## move right",

in this way:
class character():
................
def update(self, d, sp):
if d == 6:
self.x += sp
elif d == 4:
self.x -= sp
elif d == 8:
self.y -= sp
elif d == 2:
self.y += sp

Why use this odd numeric-keypad code for the direction? Other than the variable names and that code, this looks usable. But think about what'd happen if I pressed RIGHT and UP at the same time: the code would see the RIGHT, set the direction to right, then probably see the UP (depending on which was mentioned last in the code) and change the direction to up.

A different way to handle the movement would be something like:
player.coords = [42,100] ## some starting value
## In a loop:
movement = [0,0]
if keys_down[K_RIGHT]:
  movement[0] = speed
...
if keys_down[K_UP]:
  movement[1] = speed
...
player.move(movement)

def Move(movement):
  self.coords[0] += movement[0]
  self.coords[1] += movement[1]

You'd then get diagonal movement, and not have to specify the direction, and could apply effects like muddy ground multiplying the X and Y movement by .5 or something. The actual diagonal speed would be sqrt(2) * speed though, which might matter.

def controls():

output = 0
keysDown = pygame.key.get_pressed():

Why is there a colon after the function call? That's only for defining it.

Are you familiar with the "Model/View/Controller" style of organizing a game, by the way? It's similar to what you're doing, and pretty useful.