cookertron

Python Pygame - Basic Jump

Mar 1st, 2020
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import pygame
  2.  
  3. WHITE = [255, 255, 255]
  4. BLACK = [0, 0, 0]
  5.  
  6.  
  7. SIZE = 600
  8. HALF = 300
  9.  
  10. pygame.init()
  11. DS = pygame.display.set_mode((SIZE, SIZE))
  12.  
  13.  
  14. blockSize =  30 # size of the block
  15. blockX = int(HALF - blockSize / 2)
  16. blockY = SIZE - blockSize # starting position of the block
  17. jumpCounter = 0 # keep track of block's jump height
  18. velocityY = 0 # The velocity of the block -1 (jump up), 0 (still), 1 (falling)
  19.  
  20. while True:
  21.     e = pygame.event.get()
  22.  
  23.     k = pygame.key.get_pressed()
  24.     if k[pygame.K_ESCAPE]: break # press escape to exit. Window controls don't work
  25.  
  26.     DS.fill(BLACK)
  27.     pygame.draw.rect(DS, WHITE, (blockX, blockY, blockSize, blockSize))
  28.     pygame.display.update()
  29.     pygame.time.Clock().tick(60) # 60 FPS
  30.    
  31.     # block can only jump if the space bar is pressed and the jumpCounter is zero and the velocity is zero
  32.     if k[pygame.K_SPACE] and not jumpCounter and not velocityY:
  33.         jumpCounter = 100 # the height block will jump
  34.         velocityY = -1 # jump up
  35.  
  36.     blockY += velocityY # add the velocity to the block's y position
  37.     if jumpCounter: # if jumpCounter is greater than 0
  38.         jumpCounter -= 1 # decrement the counter by 1
  39.         if not jumpCounter and velocityY == -1: # if the jump counter is zero and the block is jumping up
  40.             velocityY = 1 # change the velocity of the block so that it's falling
  41.             jumpCounter = 100 # change the value of the jump counter back to 100 so the block falls the same distance as it did jumping up
  42.         elif not jumpCounter and velocityY == 1: # if the jump counter is zero and the block is falling
  43.             velocityY = 0 # set the velocity of the block to zero so that it's motionless. The block should now be able to jump again!
Advertisement
Add Comment
Please, Sign In to add comment