How to simulate Jumping in Pygame for this particular code

See How to make a character jump in Pygame?. Add a variable jump and initialize it by 0, before the main loop:

jump = 0  
while run:
    # [...]

Only react on pygame.K_SPACE, if player is allowed to jump and stays on the ground. If this is fulfilled then set jump to the desired “jump” height:

if keys[pygame.K_SPACE] and Ycord == ScreenLenY - height:
    jump = 300

As long as jump is greater than 0, move the player upwards and decease jump by the same amount, in the main loop.
If the player is not jumping that let him fall dawn, till he reaches the ground:

 if jump > 0:
    Ycord -= vel
    jump -= vel
elif Ycord < ScreenLenY - height:
    Ycord += 1

See the demo, where I applied the suggestions to your code:

import pygame
pygame.init()

ScreenLenX, ScreenLenY = (1000, 500)
win = pygame.display.set_mode((ScreenLenX, ScreenLenY))
pygame.display.set_caption("aman")
Xcord, Ycord = (100, 100)
length, height = (10, 10)
xmove, ymove = (1, 1)
vel = 2
jump = 0

run = True
clock = pygame.time.Clock()
while run:
    #clock.tick(60)
    for event in pygame.event.get():
        print(event)
        if event.type ==pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT] and Xcord <= ScreenLenX-length:
        Xcord += vel
    if keys[pygame.K_LEFT] and Xcord >= 0:
        Xcord -= vel

    if keys[pygame.K_SPACE] and Ycord == ScreenLenY - height:
        jump = 300

    if jump > 0:
        Ycord -= vel
        jump -= vel
    elif Ycord < ScreenLenY - height:
        Ycord += 1

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), (Xcord, Ycord, length, height))

    pygame.display.update()

Leave a Comment