Skip to content

Instantly share code, notes, and snippets.

@EncodeTheCode
Created April 18, 2023 22:24
Show Gist options
  • Save EncodeTheCode/1999bb9e5e319eb4e1b4b6944d7c8298 to your computer and use it in GitHub Desktop.
Save EncodeTheCode/1999bb9e5e319eb4e1b4b6944d7c8298 to your computer and use it in GitHub Desktop.
import pygame
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Define constants
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 540
WALL_THICKNESS = 10
PLAYER_SPEED = 0.15
# Initialize Pygame
pygame.init()
# Set up the display
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My Game")
# Create the player circle
player_radius = 20
player_x = SCREEN_WIDTH // 2
player_y = SCREEN_HEIGHT // 2
player_color = WHITE
# Game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle player movement
keys = pygame.key.get_pressed()
dx = dy = 0
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
dx = -PLAYER_SPEED
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
dx = PLAYER_SPEED
if keys[pygame.K_UP] or keys[pygame.K_w]:
dy = -PLAYER_SPEED
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
dy = PLAYER_SPEED
# Check for collisions in the x direction
if dx != 0:
new_x = player_x + dx
if new_x - player_radius < WALL_THICKNESS or new_x + player_radius > SCREEN_WIDTH - WALL_THICKNESS:
dx = 0
else:
player_x = new_x
# Check for collisions in the y direction
if dy != 0:
new_y = player_y + dy
if new_y - player_radius < WALL_THICKNESS or new_y + player_radius > SCREEN_HEIGHT - WALL_THICKNESS:
dy = 0
else:
player_y = new_y
# Draw the background
screen.fill(BLACK)
# Draw the walls
pygame.draw.rect(screen, RED, (0, 0, SCREEN_WIDTH, WALL_THICKNESS)) # Top wall
pygame.draw.rect(screen, RED, (0, SCREEN_HEIGHT - WALL_THICKNESS, SCREEN_WIDTH, WALL_THICKNESS)) # Bottom wall
pygame.draw.rect(screen, RED, (0, WALL_THICKNESS, WALL_THICKNESS, SCREEN_HEIGHT - 2 * WALL_THICKNESS)) # Left wall
pygame.draw.rect(screen, RED, (SCREEN_WIDTH - WALL_THICKNESS, WALL_THICKNESS, WALL_THICKNESS, SCREEN_HEIGHT - 2 * WALL_THICKNESS)) # Right wall
# Draw the player
pygame.draw.circle(screen, player_color, (int(player_x), int(player_y)), player_radius)
# Update the display
pygame.display.update()
# Quit Pygame
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment