Let’s Gobble! Create a Simple Pac-Man Game with Python (Beginner-Friendly)

Have you ever wanted to build your own video game? It might sound complicated, but with Python, one of the most popular and beginner-friendly programming languages, it’s totally achievable! Today, we’re going to dive into creating a very simple version of the classic arcade game, Pac-Man. Don’t worry if you’re new to programming; we’ll break down every step using clear, simple language.

This project is a fantastic way to learn some fundamental game development concepts like creating game objects, handling user input, detecting collisions, and keeping score. We’ll use a special Python module called turtle for our graphics, which is perfect for getting started with visual programming.

Why Python and the Turtle Module?

Python is a fantastic language for beginners because its syntax (the rules for writing code) is very readable, almost like plain English. This makes it easier to understand what your code is doing.

The turtle module is a built-in Python library that lets you create simple graphics and animations. Think of it like drawing with a robot turtle on a canvas. You tell the turtle to move forward, turn, lift its pen, or put its pen down, and it draws on the screen. It’s an excellent tool for visualizing how programming commands translate into actions on a screen, making it ideal for our simple Pac-Man game.

  • Python: A versatile (meaning it can do many different things) and easy-to-read programming language.
  • Turtle Module: A Python library for creating graphics by issuing commands to a virtual “turtle” that draws on a screen.

What Will Our Simple Pac-Man Game Do?

Our version of Pac-Man will be quite basic, focusing on the core elements:
* A player-controlled Pac-Man.
* Multiple food pellets (dots) for Pac-Man to eat.
* Pac-Man moving around the screen using keyboard controls.
* A scoring system that increases when Pac-Man eats food.
* Food pellets disappearing when eaten.

We won’t be adding ghosts or complex mazes in this beginner-friendly version, as that would add too much complexity for our first game. But once you understand these basics, you’ll be well-equipped to add more features!

Setting Up Your Development Environment

Before we start coding, you’ll need Python installed on your computer. If you don’t have it, you can download it from the official Python website (python.org). Most operating systems come with a basic text editor, but a more advanced one like Visual Studio Code (VS Code) or PyCharm can make coding easier. For running our simple game, a basic text editor and command prompt will work perfectly.

Step-by-Step Game Creation

Let’s build our game piece by piece.

1. Initialize the Game Window

First, we need to set up the game window where everything will appear.

import turtle
import math # We'll use this later for distance calculations

wn = turtle.Screen() # This creates our game window
wn.setup(width=600, height=600) # Sets the size of the window
wn.bgcolor("black") # Sets the background color to black
wn.title("Simple Pac-Man") # Gives our window a title
wn.tracer(0) # This turns off screen updates, we'll update manually for smoother animation
  • import turtle: This line brings in the turtle module so we can use its functions.
  • wn = turtle.Screen(): We create an object called wn (short for window) which represents our game screen.
  • wn.setup(width=600, height=600): This makes our game window 600 pixels wide and 600 pixels tall. A pixel is a tiny dot on your screen.
  • wn.bgcolor("black"): Sets the background color of our game window.
  • wn.title("Simple Pac-Man"): Puts “Simple Pac-Man” in the title bar of the window.
  • wn.tracer(0): This is a very important line for game animation. By default, turtle updates the screen every time something moves. This can make animations look choppy. wn.tracer(0) tells turtle to not update automatically. We’ll manually update the screen later using wn.update() to make movements smoother.

2. Create the Player (Pac-Man)

Now, let’s create our Pac-Man character. We’ll use another turtle object for this.

player = turtle.Turtle() # Creates a new turtle object for our player
player.shape("circle") # Makes the player look like a circle
player.color("yellow") # Sets Pac-Man's color
player.penup() # Lifts the "pen" so it doesn't draw lines when moving
player.goto(0, 0) # Sets Pac-Man's starting position at the center of the screen
player.direction = "stop" # A variable to keep track of Pac-Man's current movement direction
  • player = turtle.Turtle(): We create an object named player that is a turtle.
  • player.shape("circle"): We change the default arrow shape of the turtle to a circle.
  • player.color("yellow"): Our Pac-Man will be yellow!
  • player.penup(): When a turtle moves, it usually draws a line. penup() lifts its “pen” so it moves without drawing. pendown() would put the pen back down.
  • player.goto(0, 0): In turtle graphics, the center of the screen is (0, 0). X-coordinates go left-right, Y-coordinates go up-down.
  • player.direction = "stop": We create a custom variable direction for our player turtle to store which way it’s supposed to move. Initially, it’s “stop”.

3. Create the Food Pellets

We need some food for Pac-Man to eat! We’ll create a list of turtle objects for our food.

foods = []

food_positions = [
    (-200, 200), (-150, 200), (-100, 200), (-50, 200), (0, 200), (50, 200), (100, 200), (150, 200), (200, 200),
    (-200, 150), (-100, 150), (0, 150), (100, 150), (200, 150),
    (-200, 100), (-150, 100), (-50, 100), (50, 100), (150, 100), (200, 100),
    (-200, 0), (-100, 0), (0, 0), (100, 0), (200, 0), # Note: (0,0) is player start, we'll remove it later
    (-200, -100), (-150, -100), (-50, -100), (50, -100), (150, -100), (200, -100),
    (-200, -150), (-100, -150), (0, -150), (100, -150), (200, -150),
    (-200, -200), (-150, -200), (-100, -200), (-50, -200), (0, -200), (50, -200), (100, -200), (150, -200), (200, -200)
]

for pos in food_positions:
    food = turtle.Turtle()
    food.shape("circle")
    food.color("white")
    food.shapesize(0.5) # Makes the food circles smaller
    food.penup()
    food.goto(pos)
    foods.append(food) # Add each food pellet to our 'foods' list

for food in foods:
    if food.distance(player) < 1: # If food is very close to the player
        food.hideturtle() # Make it invisible
        foods.remove(food) # Remove it from our list
        break # Exit the loop once found and removed
  • foods = []: This creates an empty list. A list is like a container that can hold multiple items. We’ll store all our food turtle objects here.
  • food_positions = [...]: We define a list of (x, y) coordinates where our food pellets will appear.
  • for pos in food_positions:: This is a for loop, which means it will repeat the code inside it for each item in food_positions. For each pos (position):
    • We create a new food turtle.
    • Set its shape to “circle”, color to “white”, and make it smaller with shapesize(0.5).
    • Move it to the current pos.
    • foods.append(food): We add this newly created food turtle to our foods list.
  • food.distance(player) < 1: The distance() method calculates the distance between two turtles. If it’s less than 1, they are essentially at the same spot.
  • food.hideturtle(): Makes the food turtle invisible.
  • foods.remove(food): Deletes the food turtle from our foods list.

4. Implement Player Movement

We need functions to tell Pac-Man which way to go when the user presses a key.

def go_up():
    player.direction = "up"

def go_down():
    player.direction = "down"

def go_left():
    player.direction = "left"

def go_right():
    player.direction = "right"

wn.listen() # Tells the window to listen for keyboard input
wn.onkeypress(go_up, "w") # When 'w' is pressed, call go_up()
wn.onkeypress(go_down, "s") # When 's' is pressed, call go_down()
wn.onkeypress(go_left, "a") # When 'a' is pressed, call go_left()
wn.onkeypress(go_right, "d") # When 'd' is pressed, call go_right()

wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
  • go_up(), go_down(), etc.: These are simple functions that just update our player.direction variable. Pac-Man won’t move immediately when a key is pressed; instead, we’ll check this direction variable inside our main game loop to move him consistently.
  • wn.listen(): This line is crucial; it tells the game window to start listening for keyboard presses.
  • wn.onkeypress(function, key): This connects a key press to a function. For example, when the ‘w’ key is pressed, the go_up() function will be called.

5. Display the Score

We need a way to show the player’s score. We’ll use another turtle for this, but this turtle will only write text.

score = 0

score_display = turtle.Turtle()
score_display.speed(0) # Fastest animation speed
score_display.color("white")
score_display.penup()
score_display.hideturtle() # We don't want to see the turtle itself, just its writing
score_display.goto(0, 260) # Position it near the top of the screen
score_display.write("Score: 0", align="center", font=("Courier", 24, "normal")) # Display initial score
  • score = 0: Initializes our score variable.
  • score_display = turtle.Turtle(): Creates a turtle for displaying text.
  • score_display.hideturtle(): We don’t want to see the turtle drawing the score, just the score text itself.
  • score_display.goto(0, 260): Moves the turtle to the top of the screen.
  • score_display.write(...): This command makes the turtle write text.
    • "Score: 0": The actual text to display.
    • align="center": Centers the text.
    • font=("Courier", 24, "normal"): Sets the font style, size, and weight.

6. The Main Game Loop

This is the heart of our game. The game loop runs continuously, updating everything on the screen and checking for actions.

while True: # This loop will run forever until the program is closed
    wn.update() # Manually update the screen (because we used wn.tracer(0))

    # Move the player
    if player.direction == "up":
        y = player.ycor() # Get current Y coordinate
        player.sety(y + 2) # Move up by 2 pixels
    if player.direction == "down":
        y = player.ycor()
        player.sety(y - 2)
    if player.direction == "left":
        x = player.xcor() # Get current X coordinate
        player.setx(x - 2) # Move left by 2 pixels
    if player.direction == "right":
        x = player.xcor()
        player.setx(x + 2)

    # Wrap around the edges (simple boundary)
    if player.xcor() > 290: # If Pac-Man goes too far right
        player.setx(-290) # Warp to the left side
    if player.xcor() < -290: # If Pac-Man goes too far left
        player.setx(290) # Warp to the right side
    if player.ycor() > 290: # If Pac-Man goes too far up
        player.sety(-290) # Warp to the bottom side
    if player.ycor() < -290: # If Pac-Man goes too far down
        player.sety(290) # Warp to the top side

    # Check for collision with food
    # We iterate backwards through the list to safely remove items
    for i in range(len(foods) - 1, -1, -1):
        food = foods[i]
        if player.distance(food) < 15: # If Pac-Man is close enough to the food (adjust 15 as needed)
            food.hideturtle() # Make the food disappear
            foods.pop(i) # Remove the food from the list
            score += 10 # Increase the score
            score_display.clear() # Clear the old score text
            score_display.write(f"Score: {score}", align="center", font=("Courier", 24, "normal")) # Write the new score

    # Check for game over (all food eaten)
    if not foods: # If the 'foods' list is empty
        score_display.clear()
        score_display.goto(0, 0) # Move score display to center
        score_display.write(f"GAME OVER! Your Score: {score}", align="center", font=("Courier", 30, "bold"))
        player.hideturtle() # Hide Pac-Man
        wn.update() # Update one last time
        break # Exit the game loop
  • while True:: This creates an infinite loop. The code inside will run again and again until the program is closed or a break statement is encountered.
  • wn.update(): This is where we manually refresh the screen. Because wn.tracer(0) is on, all movements and changes only become visible after wn.update() is called.
  • player.ycor() / player.xcor(): These functions get the current Y (vertical) or X (horizontal) coordinate of the player turtle.
  • player.sety(y + 2) / player.setx(x - 2): These functions set the new Y or X coordinate. We add or subtract 2 to move Pac-Man in the desired direction. This ‘2’ represents his speed.
  • Wrap around edges: These if statements check if Pac-Man has gone off one side of the screen and, if so, goto() the opposite side. This creates a classic Pac-Man “wrap-around” effect.
  • for i in range(len(foods) - 1, -1, -1):: This loop goes through the foods list backwards. This is a common and safe practice when you might be removing items from a list while you’re looping through it. If you iterate forwards and remove an item, the list shortens and the indices (positions of items) shift, which can lead to errors.
  • player.distance(food) < 15: This checks if Pac-Man is close enough to a food pellet to “eat” it. The number 15 is a radius; you can adjust it if you want Pac-Man to have to be closer or further away to eat food.
  • foods.pop(i): This removes the food item at index i from the foods list.
  • score_display.clear(): Before writing a new score, we clear the old one so it doesn’t overlap.
  • if not foods:: This checks if the foods list is empty. If it is, it means Pac-Man has eaten all the food, and the game ends!

Putting It All Together (Complete Code)

Here’s the complete code for your simple Pac-Man game. You can copy and paste this into a Python file (e.g., pacman_simple.py) and run it.

import turtle
import math

wn = turtle.Screen()
wn.setup(width=600, height=600)
wn.bgcolor("black")
wn.title("Simple Pac-Man")
wn.tracer(0) # Turn off screen updates for smoother animation

player = turtle.Turtle()
player.shape("circle")
player.color("yellow")
player.penup()
player.goto(0, 0)
player.direction = "stop" # Initial direction

foods = []
food_positions = [
    (-200, 200), (-150, 200), (-100, 200), (-50, 200), (0, 200), (50, 200), (100, 200), (150, 200), (200, 200),
    (-200, 150), (-100, 150), (0, 150), (100, 150), (200, 150),
    (-200, 100), (-150, 100), (-50, 100), (50, 100), (150, 100), (200, 100),
    (-200, 0), (-100, 0), (100, 0), (200, 0), # (0,0) excluded here to avoid overlap with player start
    (-200, -100), (-150, -100), (-50, -100), (50, -100), (150, -100), (200, -100),
    (-200, -150), (-100, -150), (0, -150), (100, -150), (200, -150),
    (-200, -200), (-150, -200), (-100, -200), (-50, -200), (0, -200), (50, -200), (100, -200), (150, -200), (200, -200)
]

for pos in food_positions:
    food = turtle.Turtle()
    food.shape("circle")
    food.color("white")
    food.shapesize(0.5)
    food.penup()
    food.goto(pos)
    foods.append(food)

def go_up():
    player.direction = "up"
def go_down():
    player.direction = "down"
def go_left():
    player.direction = "left"
def go_right():
    player.direction = "right"

wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")

score = 0
score_display = turtle.Turtle()
score_display.speed(0)
score_display.color("white")
score_display.penup()
score_display.hideturtle()
score_display.goto(0, 260)
score_display.write("Score: 0", align="center", font=("Courier", 24, "normal"))

while True:
    wn.update() # Manually update the screen

    # Move the player
    if player.direction == "up":
        y = player.ycor()
        player.sety(y + 2)
    elif player.direction == "down": # Use elif to ensure only one direction is processed
        y = player.ycor()
        player.sety(y - 2)
    elif player.direction == "left":
        x = player.xcor()
        player.setx(x - 2)
    elif player.direction == "right":
        x = player.xcor()
        player.setx(x + 2)

    # Wrap around the edges
    if player.xcor() > 290:
        player.setx(-290)
    elif player.xcor() < -290:
        player.setx(290)
    elif player.ycor() > 290:
        player.sety(-290)
    elif player.ycor() < -290:
        player.sety(290)

    # Check for collision with food
    for i in range(len(foods) - 1, -1, -1): # Loop backwards
        food = foods[i]
        if player.distance(food) < 15: # Collision distance
            food.hideturtle()
            foods.pop(i)
            score += 10
            score_display.clear()
            score_display.write(f"Score: {score}", align="center", font=("Courier", 24, "normal"))

    # Check for game over (all food eaten)
    if not foods:
        score_display.clear()
        score_display.goto(0, 0)
        score_display.write(f"GAME OVER! Your Score: {score}", align="center", font=("Courier", 30, "bold"))
        player.hideturtle()
        wn.update()
        break # Exit the game loop

How to Run Your Game

  1. Save: Save the code above into a file named pacman_simple.py (or any name ending with .py).
  2. Open Terminal/Command Prompt: Navigate to the folder where you saved your file using your terminal or command prompt.
  3. Run: Type python pacman_simple.py and press Enter.

A new window should pop up, showing your black game screen, a yellow Pac-Man, and white food pellets. Use the ‘W’, ‘A’, ‘S’, ‘D’ keys or the arrow keys to move Pac-Man and start gobbling up those pellets!

Next Steps and Improvements

Congratulations! You’ve just created your very own simple game in Python. This is just the beginning. Here are some ideas to expand your game:

  • Add Walls/Maze: You could create simple “walls” using more turtle objects or by drawing lines and preventing Pac-Man from passing through them.
  • Introduce Ghosts: This is a big step, but you could create other turtle objects (ghosts) that move independently and end the game if they touch Pac-Man.
  • Different Food Types: Add larger pellets that give more points or special power-ups.
  • Levels: Once all food is eaten, reset the game with more food or a different layout.
  • Sounds: Python has modules (like winsound on Windows or pygame.mixer) to play sound effects when food is eaten or the game ends.

Conclusion

Building games is a fantastic way to learn programming. The turtle module in Python provides an intuitive and visual way to understand core programming concepts without getting bogged down in complex graphics libraries. You’ve taken your first steps into game development, and hopefully, you’ve seen how a few lines of code can bring an idea to life. Keep experimenting, keep coding, and most importantly, have fun!


Comments

Leave a Reply