Skip to content

Instantly share code, notes, and snippets.

@matthewdeanmartin
Created December 4, 2022 15:07
Show Gist options
  • Select an option

  • Save matthewdeanmartin/2ac9a2d222b803c6ad40dc0c9a94fc6c to your computer and use it in GitHub Desktop.

Select an option

Save matthewdeanmartin/2ac9a2d222b803c6ad40dc0c9a94fc6c to your computer and use it in GitHub Desktop.
# Import the pygame module
import pygame
# Initialize the game
pygame.init()
# Set the screen size and caption
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pac-Man")
# Load the images
pacman_image = pygame.image.load("pacman.png")
dot_image = pygame.image.load("dot.png")
# Create the pacman sprite
pacman = pygame.sprite.Sprite()
pacman.image = pacman_image
pacman.rect = pacman.image.get_rect()
# Create the dot sprite
dot = pygame.sprite.Sprite()
dot.image = dot_image
dot.rect = dot.image.get_rect()
# Game loop
while True:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Update the pacman sprite
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
pacman.rect.x -= 5
if keys[pygame.K_RIGHT]:
pacman.rect.x += 5
if keys[pygame.K_UP]:
pacman.rect.y -= 5
if keys[pygame.K_DOWN]:
pacman.rect.y += 5
# Keep the pacman sprite inside the screen
if pacman.rect.x < 0:
pacman.rect.x = 0
if pacman.rect.x > screen.get_width() - pacman.rect.width:
pacman.rect.x = screen.get_width() - pacman.rect.width
if pacman.rect.y < 0:
pacman.rect.y = 0
if pacman.rect.y > screen.get_height() - pacman.rect.height:
pacman.rect.y = screen.get_height() - pacman.rect.height
# Check if the pacman sprite is colliding with the dot sprite
if pacman.rect.colliderect(dot.rect):
# Move the dot to a random location
dot.rect.x = random.randint(0, screen.get_width() - dot.rect.width)
dot.rect.y = random.randint(0, screen.get_height() - dot.rect.height)
# Draw the sprites on the screen
screen.fill((0, 0, 0))
screen.blit(pacman.image, pacman.rect)
screen.blit(dot.image, dot.rect)
pygame.display.flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment