Leo Gortz
Leo Gortz

Reputation: 75

Pygame not responding to keys

I've recently started Python and I'm learning from a book but I think the book either uses an old version or it's not made very well. Using some code I tried to create a simple moving character.

#!/usr/bin/python3
import pygame
from pygame.locals import *
pygame.init()

running = True
gamewindow=pygame.display.set_mode((800, 600))
pygame.display.set_caption("Game")
black=(0, 0, 0)
white=(255, 255, 255)
img=pygame.image.load("/home/leo/Downloads/pixel.png")
def sprite(x,y):
        gamewindow.blit(img, (x,y))

x=(800*0.2)
y=(600*0.735)

xchange=0
imgspeed=0

while running:
    for event in pygame.event.get():
        if event.type==QUIT:
            running = False

    if event.type == pygame.KEYDOWN:
        if event.type == pygame.K_LEFT:
            xchange=-5
        elif event.type == pygame.K_RIGHT:
            xchange=5
    if event.type==pygame.KEYUP:
        if event.type==pygame.K_LEFT or event.key==pygame.K_RIGHT:
            xchange=0
    x= x + xchange

    gamewindow.fill(white)
    sprite(x,y)
    pygame.display.update()


pygame.quit()

Using this code, the character doesn't move and I think it may be due to the wrong functions in this section:

while running:
    for event in pygame.event.get():
        if event.type==QUIT:
            running = False

    if event.type == pygame.KEYDOWN:
        if event.type == pygame.K_LEFT:
            xchange=-5
        elif event.type == pygame.K_RIGHT:
            xchange=5
    if event.type==pygame.KEYUP:
        if event.type==pygame.K_LEFT or event.key==pygame.K_RIGHT:
            xchange=0
    x= x + xchange

Is the book completely wrong or is there just a few small things I have to change. Thank you!

Upvotes: 2

Views: 92

Answers (1)

Serge
Serge

Reputation: 3765

You check type of event instead of the event key. For example you should use event.key == pygame.K_LEFT instead of event.type == pygame.K_LEFT etc.

How do you think event.type can be equal pygame.K_LEFT and pygame.KEYDOWN in the same time?

See How to use pygame.KEYDOWN for the correct example.

Upvotes: 1

Related Questions