VOOZH about

URL: https://www.geeksforgeeks.org/c/pacman-game-in-c-1/

⇱ Pacman Game in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pacman Game in C

Last Updated : 25 Mar, 2026

The Pacman game is a classic arcade-style game where the player controls a character that moves inside a maze, collects food pellets, and avoids enemies. The objective is to maximize the score by eating all the food while avoiding the ghost. The game ends when Pacman collides with the ghost.

Approach

  • The game maze is represented using a 2D character array.
  • Pacman (C) moves inside the maze using keyboard inputs.
  • Food pellets (.) are placed across the maze and increase the score when eaten.
  • A ghost (G) moves automatically and tries to chase Pacman.
  • Collision with walls is restricted, and collision with the ghost ends the game.
  • The screen is continuously updated to simulate motion.

Libraries Used

  • <stdio.h>: Used for input/output operations like printf.
  • <stdlib.h>: Used for functions like system().
  • <windows.h>: Used for cursor control, keyboard input, and delay functions.

Functions

  • setup(): Initializes game variables such as positions and score.
  • clearScreen(): Clears the console buffer efficiently to prevent flickering.
  • draw(): Displays the maze, Pacman, ghost, and score on the console.
  • input(): Handles real-time keyboard input using GetAsyncKeyState.
  • logic(): Updates food consumption, ghost movement, and collision detection.

Implementation

Output:

👁 pacmanc
Game output

Explanation:

The maze is stored as a 2D array, where:

  • # represents walls
  • . represents food
  • Space represents empty paths

Pacman Movement:

  • Controlled using W (Move Up), S (Move Down), A (Move Left), D (Move Right), X (Exit Game).
  • Movement is restricted when hitting walls

Real-Time Input: GetAsyncKeyState() allows smooth continuous movement without pressing Enter

Ghost Logic:

  • The ghost moves towards Pacman using a simple chasing algorithm
  • It prioritizes horizontal movement first, then vertical

Collision Detection:

  • Eating food increases score
  • If Pacman and ghost positions match → Game Over

Rendering Optimization:

  • Cursor repositioning avoids full screen flicker
  • clearScreen() ensures a clean end screen
Comment
Article Tags:
Article Tags: