How can I do a double jump in pygame?

To what you want you need to change some the jump algorithm. Calculate the jump based on an acceleration and a velocity.

Define constants for the gravity and jump acceleration:

PLAYER_ACC = 15
PLAYER_GRAV = 1

Use the keyboard events for the jump, instead of pygame.key.get_pressed(). 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.
Set the jump acceleration when the space is pressed:

acc_y = PLAYER_GRAV
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            acc_y = -PLAYER_ACC
            vel_y = 0

Change the velocity depending on the acceleration and the y coordinate depending on the velocity in every frame:

vel_y += acc_y
y += vel_y

Limit the y-coordinate by the ground:

if y + height > ground_y:
    y = ground_y - height
    vel_y = 0
    acc_y = 0

Minimal example:

import pygame

pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()

ground_y = 400
x, y = 200, ground_y
width, height = 40, 60
vel_x, vel_y = 5, 0
acc_y = 0

PLAYER_ACC = 15
PLAYER_GRAV = 1

run = True
while run:
    acc_y = PLAYER_GRAV
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                acc_y = -PLAYER_ACC
                vel_y = 0

    keys = pygame.key.get_pressed()
    x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel_x
    x = max(0, min(500 - width, x))

    vel_y += acc_y
    y += vel_y

    if y + height > ground_y:
        y = ground_y - height
        vel_y = 0
        acc_y = 0

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
    pygame.display.update()
    clock.tick(60)

pygame.quit()

Leave a Comment