Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 04 Feb 2013
Offline Last Active Feb 06 2013 12:40 AM

Topics I've Started

Need help with movement controls using OOP

04 February 2013 - 10:52 PM

So I have googled for hours and played with this for hours.
I have managed to make a game that works without using classes or other files but I want to make something more substantial and hence I have learned how to utilize these tools. One problem. The old method I used for movement controls doesn't port well to the way I am forced to do things via classes so I have coded a new way of handling it but for the life of me I can't seem to make it all work.
The problems hang around the self.position in __init__. I want it to give the default position of (WINDOWWIDTH // 2, WINDOWHEIGHT // 2) so it will start us in the middle of the screen but if I give it any value thats where I start and stop. I don't think it's being updated from the movement function.
I have managed to make movement sort of work with the use of a for loop before the movement ifs that looks like this:


for k in key_states:
     if k.key == pygame.K_UP:
          dy = -1 * MOVESPEEDY * dt
      #etc for all the movement keys



But it only works in such a way that you have to repeatedly tap the movement key to make it work not able to hold it down.
Here is my code.


# Lets get to savin peeps
import pygame, sys
import constants
import os.path
from pygame.locals import *


class Player(object):

    def __init__(self):
        self.color = constants.WHITE
        self.position = None
    #Can't remember why I put this here.
    def place(self, position):
        self.position = position

    def draw(self, surface):
        (ix, iy) = (int(self.position[0]), int(self.position[1]))
        pygame.draw.circle(surface, self.color, (ix, iy,), 15)

    def movementPlayer(self, dt, key_states, key_pressed):
        #Heres our controls
        dx = 0
        dy = 0
                # key_states is a variable in main.py that reads
                # key_states = pygame.event.get(pygame.KEYDOWN)
        if key_states[pygame.K_DOWN]: 
                     dy = 1 * constants.MOVESPEEDY * dt
        if key_states[pygame.K_UP]:
                     dy = -1 * constants.MOVESPEEDY * dt
        if key_states[pygame.K_LEFT]:
                     dx = -1 * constants.MOVESPEEDY * dt
        if key_states[pygame.K_RIGHT]:
                     dx = 1 * constants.MOVESPEEDY * dt
        (x, y) = self.position
        self.position = (x + dx, y + dy)
Now as the code stands it gives me 
IndexError: Index is out of key range.
for the [pygame.K_WHATEVERS] in the if statements.
Thanks a lot for any help.
and I can post additional information if needed.