1
votes

I am making a shooting game containing a "player" who can shoot "bullets". Press "WASD" can control the movement of the player and press "Space" can make the "player" shoot. Now I hope that Pygame can respond the long-pressed keys with different speeds. For example, respond "WASD" for every 10 ms and respond "Space" for every 1000ms. What should I do?

I have tried pygame.key.set_repeat() and every key will be responded with the same speed.

1

1 Answers

0
votes

pygame.key.set_repeat() sets the delay for the whole keyboard, it cannot discriminate between keys. You need to do it in your program.

A possible solution is to set the delay between repeated events with set_repeat to the shortest interval you want to have in your game. For keys which require a longer interval, you need to check by yourself if enough time is passed to "accept" the event and allow the corresponding action to be performed.

This sample code should give you an idea of what I mean.

import sys
import pygame

#the action you want to perform when the key is pressed. Here simply print the event key
#in a real game situation, this action would differ according to the key value
def onkeypress(event):
    print(event.key)

#dict of key constants for which you want a longer delay and their tracking time
#in ms, initialized to 0. Here only the spacebar
repeat1000 = {pygame.K_SPACE : 0}

pygame.init()
screen = pygame.display.set_mode((500, 500))

#sets repeat interval to 10 milliseconds for all keys
pygame.key.set_repeat(10)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            current_time = pygame.time.get_ticks()
            if event.key in repeat1000.keys():
                if current_time - repeat1000[event.key] > 1000:
                    repeat1000[event.key] = current_time
                    onkeypress(event)
            elif event.key in [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]:
                onkeypress(event)

If you try the above code, you'll see that the key of the spacebar (32 on my system) is printed each second if you keep pressed the spacebar. Buf if you press one of W A S D the corresponding keys (119, 97, 115, 100 on my system) are printed each 0.01 seconds.