2

I am messing around with pygame, and trying to create a simple jumping function (no physics yet).

For some reason my "jumps" are not visible in the display, even though the values I am using print out and seem to be working as intended. What could I be doing wrong?

isJump = False
jumpCount = 10
fallCount = 10
if keys[pygame.K_SPACE]:
    isJump = True
if isJump:
    while jumpCount > 0:
        y -= (jumpCount**1.5) / 3
        jumpCount -= 1
        print(jumpCount)
    while fallCount > 0:
        y += (fallCount**1.5) / 3
        fallCount -= 1
        print(fallCount)
    else:
        isJump = False
        jumpCount = 10
        fallCount = 10
        print(jumpCount, fallCount)

win.fill((53, 81, 92))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()

I shortened the amount of code, but I think this is all that is related to the problem.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Astudent
  • 186
  • 1
  • 2
  • 16
  • 1
    The indentation is wrong, please correct it so that it matches your real code. – Thierry Lathuille Oct 20 '19 at 15:03
  • 2
    you can't use `while` because it may display correct values but it never run `pygame.display.update()` ((and other code) to display it. You should use only one loop - main loop - and isnide this loop change value in every loop. – furas Oct 20 '19 at 15:03

1 Answers1

6

You've to turn the while loops to if conditions. You don't want to do the complete jump in a single frame.
You've to do a single "step" of the jump per frame. Use the main application loop to perform the jump.

See the example:

import pygame

pygame.init()
win = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

isJump = False
jumpCount, fallCount = 10, 10
x, y, width, height = 200, 300, 20, 20

run = True
while run:
    clock.tick(20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        isJump = True
    if isJump:
        if jumpCount > 0:
            y -= (jumpCount**1.5) / 3
            jumpCount -= 1
            print(jumpCount)
        elif fallCount > 0:
            y += (fallCount**1.5) / 3
            fallCount -= 1
            print(fallCount)
        else:
            isJump = False
            jumpCount, fallCount = 10, 10
            print(jumpCount, fallCount)

    win.fill((53, 81, 92))
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height)) 
    pygame.display.flip()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174