Skip to content

Instantly share code, notes, and snippets.

@EncodeTheCode
Created April 18, 2023 22:28
Show Gist options
  • Save EncodeTheCode/611f710187fe2cb00a9fec1a177f832a to your computer and use it in GitHub Desktop.
Save EncodeTheCode/611f710187fe2cb00a9fec1a177f832a to your computer and use it in GitHub Desktop.
import pygame
import math
# Initialize pygame
pygame.init()
# Set up the display
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pac-Man")
# Set up the clock
clock = pygame.time.Clock()
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# Set up the player
player_x = 50
player_y = 50
player_radius = 25
player_speed = 5
player_angle = 0
# Set up the walls
wall_thickness = 10
walls = [pygame.Rect(200, 150, wall_thickness, 300),
pygame.Rect(400, 150, wall_thickness, 300),
pygame.Rect(200, 150, 200, wall_thickness),
pygame.Rect(200, 450, 200, wall_thickness)]
# 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()
if keys[pygame.K_UP] or keys[pygame.K_w]:
player_x += player_speed * math.cos(player_angle)
player_y -= player_speed * math.sin(player_angle)
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
player_x -= player_speed * math.cos(player_angle)
player_y += player_speed * math.sin(player_angle)
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
player_angle += math.pi / 24
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
player_angle -= math.pi / 24
# Handle wall collision detection
for wall in walls:
if wall.colliderect(pygame.Rect(player_x - player_radius, player_y - player_radius,
player_radius * 2, player_radius * 2)):
# If the player collides with a wall, move the player back to their previous position
player_x, player_y = prev_player_x, prev_player_y
# Save the previous player position before updating it
prev_player_x, prev_player_y = player_x, player_y
# Clear the screen
screen.fill(BLACK)
# Draw the walls
for wall in walls:
pygame.draw.rect(screen, RED, wall)
# Draw the player Pac-Man
pac_man = pygame.transform.rotate(pygame.image.load('pac_man.png'), player_angle * 180 / math.pi)
screen.blit(pac_man, (player_x - player_radius, player_y - player_radius))
# Update the screen
pygame.display.flip()
# Limit the framerate
clock.tick(60)
# Quit the game
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment