import pygame import sys import math import random # Initialize Pygame pygame.init() # Set up the screen WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Movement System in Pygame") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) DARK_BLUE = (0, 18, 46) # Player attributes player_width = 20 player_height = 20 player_x = WIDTH // 2 - player_width // 2 player_y = HEIGHT // 2 - player_height // 2 player_speed = 3 clock = pygame.time.Clock() # Variables to track spacebar state space_pressed = False space_released = True # Main game loop running = True while running: screen.fill(DARK_BLUE) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Track spacebar state if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: space_pressed = True space_released = False elif event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: space_pressed = False space_released = True # Get the state of the keyboard keys = pygame.key.get_pressed() # Move the player if keys[pygame.K_a]: player_x -= player_speed if keys[pygame.K_d]: player_x += player_speed if keys[pygame.K_w]: player_y -= player_speed if keys[pygame.K_s]: player_y += player_speed # Boundaries player_x = max(0, min(player_x, WIDTH - player_width)) player_y = max(0, min(player_y, HEIGHT - player_height)) # Draw the player pygame.draw.rect(screen, WHITE, (player_x, player_y, player_width, player_height)) # Update the display pygame.display.flip() # Cap the frame rate clock.tick(60) # Quit Pygame pygame.quit() sys.exit()