sudchau
sudchau

Reputation: 13

How to use event.type?

The program doesn't work when I press the left cursor key. But when I do the conventional way of pygame.keys.get_pressed(), It works. The character moves right, but it doesn't go to the left.

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("BALANCE")

def updatedis(x):

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), (x, 480, 40, 20))
    pygame.draw.line(win, (0, 255, 0), (x+20, 480), (x+20, 380), 2)
    pygame.display.update()

def main():

    x = 230
    k = True

    while k:

        keys = pygame.key.get_pressed()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                k = False
            if event.type == pygame.K_LEFT:
                x = x-5

        pygame.time.delay(10)

        if keys[pygame.K_RIGHT] and x <= 460:
            x = x + 5

        updatedis(x)

    pygame.quit()

main()

Upvotes: 1

Views: 999

Answers (1)

Rabbid76
Rabbid76

Reputation: 210889

When a key is pressed then a single pygame.KEYDOWN event occurs. When the key is release then a single KEYUP occurs. If you want detect, if the pygame.K_LEFT is pressed or released, the you've to check the .key attribute of the pygame.event. Set a state (left) when the pygame.K_LEFT is pressed and reset the state when it is released.
Change the x coordinate in the main loop, when left is stated:

left = False
while k:

    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            k = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                left = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                left = False

    pygame.time.delay(10)

    if keys[pygame.K_RIGHT] and x <= 460:
        x = x + 5
    if left:
        x = x-5

Note, this is very similar to that, what pygame does for you, when stating the values which are returned by pygame.key.get_pressed().

Upvotes: 1

Related Questions