[pygame] Smooth movement and set_repeat()

21 views
Skip to first unread message

Jan Gregorczyk

unread,
May 13, 2021, 1:57:47 PM5/13/21
to pygame...@seul.org
Hi,
is it possible to set key_repeat only for some keys? I want move left and move right to repeat after pressing, but all other keys to work only once. How can I achieve that?

I was trying by doing something like this:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_F5:
self.reset()
if event.key == pygame.K_F1 or event.key == pygame.K_ESCAPE:
self.running = not self.running
if event.key == pygame.K_LEFT:
brick.move(
(brick.position[0] - 1, brick.position[1])
)
pygame.key.set_repeat(100)
if event.key == pygame.K_RIGHT:
brick.move(
(brick.position[0] + 1, brick.position[1])
)
pygame.key.set_repeat(100)
if event.key == pygame.K_x or event.key == pygame.K_UP:
brick.rotate("right")
pygame.key.set_repeat(0)
if event.key == pygame.K_RCTRL or event.key == pygame.K_z:
brick.rotate("left")
pygame.key.set_repeat(0)
if event.key == pygame.K_SPACE:
pygame.key.set_repeat(0)
self.game_state.hard_drop()

But that way if I click for example space and then try to move it won't repeat.

BW

unread,
May 13, 2021, 2:05:51 PM5/13/21
to pygame...@seul.org

In the event handler detect KEYDOWN and KEYUP for the keys you're interested in, and store the state in a variable. In the game logic handler, if the variable indicates that the key is in the pressed state, then do the action.

You can also poll the state of the keys with key.get_pressed(). But it is less efficient than using the event handler.

Reply all
Reply to author
Forward
0 new messages