Jake Huston
Jake Huston

Reputation: 71

Only 1 event key is working

So I'm developing a game in python. Here is my code:

bif="main_background.jpg"
pif="player_head.png"

import pygame, sys
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((900,600),0,32)

background=pygame.image.load(bif).convert()
player_sprite=pygame.image.load(pif).convert_alpha()

x,y=0,0
movex, movey=0,0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_RIGHT:
                movex=+1
            if event.type==K_LEFT:
                movex=-1
            if event.type==K_UP:
                movey=-1
            if event.type==K_DOWN:
                movey=+1
        if event.type==KEYUP:
            if event.key==K_RIGHT:
                movex=0
            if event.type==K_LEFT:
                movex=0
            if event.type==K_UP:
                movey=0
            if event.type==K_DOWN:
                movey=0

    x+=movex
    y+=movey

    screen.blit(background, (0,0))
    screen.blit(player_sprite, (x,y))

    pygame.display.update()

But the problem is that only the first event.key is working (K_RIGHT)

The sprite only moves when I press the right arrow key.

I've also tried replacing 2nd, 3rd and 4th event.key with elif but It didn't work either.

Upvotes: 1

Views: 206

Answers (2)

Elmar Peise
Elmar Peise

Reputation: 15493

You check event.key==K_RIGHT but for the other directions, you do event.type==K_LEFT etc.

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122536

You are using event.type instead of event.key for all other keys, except for K_RIGHT (which works). That explains why the other keys are not working. Also, you should write:

movex += 1

or

movey -=1

and so on to make the sprite change position. This will increment and decrement the sprite's position. Writing movex += 1 is shorthand for movex = movex + 1.

Upvotes: 4

Related Questions