I’m trying to record the amount of times my space bar is pressed so that I can limit the amount of times it can be pressed within a certain amount of time to avoid spamming which eliminates the point of the game. I tried this by adding one (+1) to the keypress_count variable every time I press the space bar, however, once I release the space bar, the value goes back to 0.
class Player():
def __init__(self, x, y):
self.image = aru
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
def update(self):
δx = 0
δy = 0
keypress_count = 0
# Player controls
kei = pygame.key.get_pressed()
if kei[pygame.K_SPACE] and self.jumped == False:
self.vel_y = -15
self.jumped = True
keypress_count += 1
print(keypress_count)
if kei[pygame.K_SPACE] == False:
self.jumped = False
print(keypress_count)
if kei[pygame.K_a]:
δx -= 10
if kei[pygame.K_d]:
δx += 10
How do I make it so that the value remains the same even after I release the space bar?
1
Your code just resets the count each time through the update method. You should make another instance variable:
class Player():
def __init__(self, x, y):
self.image = aru
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
self.keypress_count = 0
def update(self):
δx = 0
δy = 0
# Player controls
kei = pygame.key.get_pressed()
if kei[pygame.K_SPACE] and self.jumped == False:
self.vel_y = -15
self.jumped = True
self.keypress_count += 1
print(self.keypress_count)
if kei[pygame.K_SPACE] == False:
self.jumped = False
print(self.keypress_count)
if kei[pygame.K_a]:
δx -= 10
if kei[pygame.K_d]:
δx += 10