1

In This program I want to have it register Pressed Keys But only once instead of multiple times. If you've played 2048, I am trying to make something like that. I want to do this without slowing the Frame rate.

import pygame, sys
pygame.init()

WIDTH, HEIGHT = 450,450
win = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
class Tile:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def Move(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            print("Left")
        elif keys[pygame.K_RIGHT]:
                print("Right")
        elif keys[pygame.K_UP]:
                print("Up")
        elif keys[pygame.K_DOWN]:
                print("Down")
            
keys = pygame.key.get_pressed()
        
running = run = True
a = Tile(200, 500)
while run:
    a.Move()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            sys.exit()
            
    

    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
JITTU VARGHESE
  • 435
  • 1
  • 4
  • 6

1 Answers1

1

You have to use the key events, rather then pygame.key.get_pressed().

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or movement.

Get the list of events (event_list) in the main application loop and pass the list to the method Move of the class Tile. Handel the events in the method:

import pygame, sys
pygame.init()

WIDTH, HEIGHT = 450,450
win = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

class Tile:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def Move(self, event_list):
        for event in event_list:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    print("Left")
                elif event.key == pygame.K_RIGHT:
                    print("Right")
                elif event.key == pygame.K_UP:
                    print("Up")
                elif event.key == pygame.K_DOWN:
                    print("Down")
            
running = run = True
a = Tile(200, 500)
while run:

    event_list = pygame.event.get()
    a.Move(event_list)

    clock.tick(60)
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False
            sys.exit()

    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174