PDA

View Full Version : setting player controll keys in python/pygame. NEED HELP PLZ




Sparky445
Aug 26, 2013, 04:24 AM
I created this game in pygame but i can't figure out how to set controll keys such as WASD. This is the code

import pygame, sys, time, math
from pygame.locals import *

pygame.init()
width = 640
height = 480

FPS = 30
FPSCLOCK = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100, 100]

player = pygame.image.load('/Users/Sparky/Desktop/squirrel.png')

while 1:
screen.fill(0)
screen.blit(player, playerpos)
pygame.display.flip()


for event in pygame.event.get():
if event.type == QUIT:
terminate()

elif event.type == KEYDOWN:
if event.key==K_w:
key[0]=True
elif event.key==K_a:
key[1]=True
elif event.key==K_s:
key[2]=True
elif event.key==K_d:
key[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
key[0]=False
elif event.key==pygame.K_a:
key[1]=False
elif event.key==pygame.K_s:
key[2]=False
elif event.key==pygame.K_d:
key[3]=False

if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5




I keep getting a error message 'key' is not defined.

PLZ HELP ME PLZ.



Ursadorable
Aug 26, 2013, 10:18 PM
Don't know if this is relevant as I don't specifically know pygame, but noticing your keydown code is missing the pygame object on the following marked lines but are present on the keyup code:

elif event.type == KEYDOWN: <<
if event.key==K_w: <<
key[0]=True
elif event.key==K_a: <<
key[1]=True
elif event.key==K_s: <<
key[2]=True
elif event.key==K_d: <<
key[3]=True

tswett
Aug 27, 2013, 09:02 PM
I believe the problem here is that you are trying to set "key[0]" and the whatnot. Since your array is called "keys", not "key", you need to write "keys[0]" instead of "key[0]".

What Ursadorable mentioned may also be relevant after you've fixed this error.

chrono1081
Aug 28, 2013, 12:22 PM
Please don't take what I'm about to say as being rude this is genuinely meant to help for future cases but you may want to avoid writing "HELP PLZ" in all caps. Most people will pass right by the thread if you write that way.

Again I'm not trying to be rude by any means but in pretty much every forum its seen in a negative light.