jumping_square.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from pygame import QUIT, K_UP
  4. import pygame
  5. # Colors
  6. BLUE = (0, 0, 255)
  7. GREEN = (0, 255, 0)
  8. WHITE = (255, 255, 255)
  9. WIDTH = 320
  10. HEIGHT = 240
  11. GRAVITY = .9
  12. FLOOR_Y_POS = 230
  13. FPS = 60
  14. SQUARE_SIZE = 40
  15. square_surf = pygame.Surface((SQUARE_SIZE, SQUARE_SIZE))
  16. square_surf.fill(GREEN)
  17. square_rect = square_surf.get_rect()
  18. y_speed = 0
  19. x_pos = WIDTH / 2
  20. y_pos = FLOOR_Y_POS
  21. screen = pygame.display.set_mode((WIDTH, HEIGHT))
  22. pygame.display.set_caption('Jumping square')
  23. fps_clock = pygame.time.Clock()
  24. # Define the x coordinate (center) of the square. there is no need to update it
  25. # because the purpose of this program is to only make a square jump, there
  26. # are no horizontal movements.
  27. square_rect.centerx = int(x_pos)
  28. running = True
  29. while running:
  30. key_pressed = pygame.key.get_pressed()
  31. if y_speed == 0:
  32. if key_pressed[K_UP]:
  33. y_speed -= 12
  34. else:
  35. y_pos += y_speed
  36. y_speed += GRAVITY
  37. if y_pos > FLOOR_Y_POS: # Stops falling when it hits the floor
  38. y_speed = 0
  39. y_pos = FLOOR_Y_POS
  40. # Update square y coordinate
  41. square_rect.bottom = int(y_pos)
  42. screen.fill(WHITE)
  43. pygame.draw.rect(screen, BLUE, (0, 230, WIDTH, HEIGHT - 230)) # Floor
  44. screen.blit(square_surf, square_rect)
  45. fps_clock.tick(FPS)
  46. pygame.display.update()
  47. for event in pygame.event.get():
  48. if event.type == QUIT:
  49. running = False