Advertisement
AtEchoOff

Pygame Example

Apr 18th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | Source Code | 0 0
  1. import pygame
  2. import sys
  3.  
  4. pygame.init()
  5.  
  6. # Set up the screen
  7. WIDTH, HEIGHT = 500, 400
  8. screen = pygame.display.set_mode((WIDTH, HEIGHT))
  9. pygame.display.set_caption("Move the Square")
  10.  
  11. # Set up the clock
  12. clock = pygame.time.Clock()
  13.  
  14. # Square settings
  15. square_color = (0, 200, 255)
  16. square_size = 50
  17. x = WIDTH // 2
  18. y = HEIGHT // 2
  19. speed = 5
  20.  
  21. running = True
  22. while running:
  23.     # Handle quitting the game
  24.     for event in pygame.event.get():
  25.         if event.type == pygame.QUIT:
  26.             running = False
  27.  
  28.     # Get key state
  29.     keys = pygame.key.get_pressed()
  30.  
  31.     # Move the square
  32.     if keys[pygame.K_LEFT]:
  33.         x -= speed
  34.     if keys[pygame.K_RIGHT]:
  35.         x += speed
  36.     if keys[pygame.K_UP]:
  37.         y -= speed
  38.     if keys[pygame.K_DOWN]:
  39.         y += speed
  40.  
  41.     # Clear the screen and draw the square
  42.     screen.fill((30, 30, 30))
  43.     pygame.draw.rect(screen, square_color, (x, y, square_size, square_size))
  44.  
  45.     pygame.display.flip()
  46.     clock.tick(60)
  47.  
  48. pygame.quit()
  49. sys.exit()
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement