Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Hangman game using React
Next article icon

PacMan game using React

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Let's make a Pacman game using React for a fun and nostalgic web experience. We'll include classic features like the maze, pellets, and ghosts, and learn some cool React stuff along the way. The game will be easy to play with arrow keys, and we'll add extras like keeping score and power pellets. It's like bringing the old Pacman joy into today's browsers with a modern twist! Just click "Start" and enjoy.

Preview of final output: Let us have a look at how the final output will look like.

Screenshot-(1414)
The output of the pacman game using react.js

Prerequisites:

  • HTML
  • CSS
  • JavaScript
  • React

Approach to create PacMan Game:

  • Create a 2D maze with React components and a CSS grid layout.
  • Use animation elements of the Pacman and different types of ghosts with their own dynamic motion patterns.
  • To drive Pacman through a maze and out of bad ghosts, you need keyboard controls.
  • Track dot collection, updating the score with each chomp and displaying it on the screen.
  • Design algorithms for ghost movement, level progression, and game-over conditions.
  • Enhance game play with classic audio effects for munching and ghostly encounters

Steps to Create the Game application:

  • You need to install the React and any other libraries that are required. You can organize your project files by component, asset, and style directories.
  • To create a familiar maze structure, create a React component for the maze grid using CSS or other layout techniques.
  • Create separate components for Pac ReactMan and each type of ghost. To make them come alive, use animation libraries or CSS animations.
  • To capture keyboard inputs and update PacMan's position according to the chosen direction, use event listeners.
  • In order to prevent him from crossing the walls, think about introducing an obstacle detection system. The rest of the dots will be tracked, their score updated with every chomp and displayed on the screen.
  • Develop algorithms for the movement pattern of all ghosts to ensure that they are following Pacman and avoiding collisions. In order to address this additional challenge, the level progression and gameover conditions shall be implemented.
  • Add sound effects to doteating, ghost encounters, and game events. In order to increase the experience, add visuals and animations of PacMan and ghosts.
  • In order to assure a smooth game play and uninterrupted operation, check thoroughly for bugs in your game. Consider creating a game on the internet, sharing your creation with the world!

Project Structure:

Screenshot-(1413)
project structure of the game

Steps to Create a React Project:

Step 1: Create your react project and navigate to your project folder ( commands in your terminal)

npx create-react-app Pacman-game
cd Pacman-game


Step 2: Create the 'components' folder to create the file 'Maze.js', 'Ghost.js', 'Pacman.js', 'GameLogic.js'.

Step 3: Images that are used in the application. Download it from google drive link (https://drive.google.com/drive/folders/1HDKSE-ypleoTSHXTr4LwM2r7cbfdRlTR?usp=sharing). Save all the images in the 'images' folder as mentioned in project structure.

Example:

  • The project folder includes components, styles, assets and helpful functions, for your React application.
  • App.js is the React component for managing the overall interface of the game.
  • The Maze.js program takes care of creating and displaying the grid and dots for the maze.
  • Pacman.js handles Pac Mans movement, animation and collision detection.
  • Ghost.js serves as a foundation component with its AI logic that allows for different types of ghosts to be created.
  • GameLogic.js manages the games state, including keeping track of scores advancing levels and determining game over conditions.
  • App.css defines the styles for all elements in the game such, as the maze, Pac Man, ghosts and text elements.
JavaScript
import React, { useState, useEffect } from "react"; import wall from "./assets/wall.png"; import coin from "./assets/coin.png"; import pacmann from "./assets/pacman.png"; import bg from "./assets/bg.png"; import ghost from "./assets/ghost2.png"; import "./App.css"; // Import your CSS file  const PacManGame = () => {     // State for PacMan position and game map     const [pacman, setPacman] = useState({ x: 6, y: 4 });     const [map, setMap] = useState([         [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],         [1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1],         [1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1],         [1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1],         [1, 2, 2, 2, 1, 1, 5, 1, 1, 2, 2, 2, 1],         [1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1],         [1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1],         [1, 2, 2, 2, 2, 2, 1, 4, 2, 2, 2, 2, 1],         [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],     ]);     const [gameOver, setGameOver] = useState(false);     // Function to handle PacMan movement     const handleKeyDown = (event) => {         if (gameOver) {             return; // If the game is over, don't handle key events         }         if (             event.keyCode === 37 &&             pacman.x > 0 &&             map[pacman.y][pacman.x - 1] !== 1         ) {             setMap((prevMap) => {                 const newMap = [...prevMap];                 newMap[pacman.y][pacman.x] = 3;                 setPacman(                     (prevPacman) =>                     (                         {                             ...prevPacman,                             x: prevPacman.x - 1                         }));                 newMap[pacman.y][pacman.x - 1] = 5;                 return newMap;             });         } else if (             event.keyCode === 38 &&             pacman.y > 0 &&             map[pacman.y - 1][pacman.x] !== 1         ) {             setMap((prevMap) => {                 const newMap = [...prevMap];                 newMap[pacman.y][pacman.x] = 3;                 setPacman(                     (prevPacman) =>                     (                         {                             ...prevPacman,                             y: prevPacman.y - 1                         }));                 newMap[pacman.y - 1][pacman.x] = 5;                 return newMap;             });         } else if (             event.keyCode === 39 &&             pacman.x < map[0].length - 1 &&             map[pacman.y][pacman.x + 1] !== 1         ) {             setMap((prevMap) => {                 const newMap = [...prevMap];                 newMap[pacman.y][pacman.x] = 3;                 setPacman(                     (prevPacman) =>                     (                         {                             ...prevPacman,                             x: prevPacman.x + 1                         }));                 newMap[pacman.y][pacman.x + 1] = 5;                 return newMap;             });         } else if (             event.keyCode === 40 &&             pacman.y < map.length - 1 &&             map[pacman.y + 1][pacman.x] !== 1         ) {             setMap((prevMap) => {                 const newMap = [...prevMap];                 newMap[pacman.y][pacman.x] = 3;                 setPacman((prevPacman) =>                 (                     {                         ...prevPacman,                         y: prevPacman.y + 1                     }));                 newMap[pacman.y + 1][pacman.x] = 5;                 return newMap;             });         }          // Check for winning condition after each movement         checkWinningCondition();     };     // Function to check for winning condition and collision detection     const checkWinningCondition = () => {         if (!map.some((row) => row.includes(2))) {             setGameOver(true);             alert("Congratulations! You collected all the coins. You win!");             // Additional logic for restarting the game or other actions         } else if (!map.some((row) => row.includes(4))) {             setGameOver(true);             alert("Game over !! You collided with the ghost");             // Additional logic for restarting the game or other actions         }     };      // Initial rendering     useEffect(() => {         const handleKeyDownEvent =              (event) => handleKeyDown(event);          document.addEventListener("keydown", handleKeyDownEvent);          // Cleanup event listener on component unmount         return () => {             document.removeEventListener("keydown", handleKeyDownEvent);         };     }, [handleKeyDown]);      return (         <div id="world" style={{ backgroundColor: "white" }}>             {/* Render the game map */}             {map.map((row, rowIndex) => (                 <div key={rowIndex}>                     {row.map((cell, colIndex) => (                         <div                             key={colIndex}                             className={                                 cell === 1                                 ? "wall"                                 : cell === 2                                 ? "coin"                                 : cell === 3                                 ? "ground"                                 : cell === 4                                 ? "ghost"                                 : cell === 5                                 ? "pacman"                                 : null                             }                             style={                                 cell === 1                                     ? { backgroundImage: `url(${wall})` }                                     : cell === 2                                     ? { backgroundImage: `url(${coin})` }                                     : cell === 3                                     ? { backgroundImage: `url(${bg})` }                                     : cell === 4                                     ? { backgroundImage: `url(${ghost})` }                                     : cell === 5                                     ? { backgroundImage: `url(${pacmann})` }                                     : null                             }                         ></div>                     ))}                 </div>             ))}         </div>     ); };  export default PacManGame; 
CSS
/* Write CSS Here */ * {     color: white; }  .wall {     width: 50px;     height: 50px;     background-color: #5e318c;     display: inline-block; }  .coin {     width: 50px;     height: 50px;     display: inline-block; }  .ground {     width: 50px;     height: 50px;      display: inline-block; }  .ghost {     width: 50px;     height: 50px;     display: inline-block; }  .pacman {     width: 50px;     height: 50px;     display: inline-block; }  div {     line-height: 0px; } 

Steps to the application:

Step 1: Type the following command in terminal.

npm start


Step 2: Open your default web-browser and type the following URL.

http://localhost:3000/


Output:

ezgifcom-video-to-gif-converted
Output

Next Article
Hangman game using React

D

dikshashu9v51
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Web Development Projects
  • ReactJS-Projects
  • Geeks Premier League 2023

Similar Reads

  • Hangman game using React
    React provides an excellent platform for creating interactive and engaging web applications. In this tutorial, you will be guided to build a classic Hangman game using React. Hangman is a word-guessing game that is not only entertaining but also a great way to practice your React skills. Preview of
    5 min read
  • Ping Pong Game using React
    Ping Pong is one of the earliest video games. It's a two-player game in which each player controls the paddle by dragging it from one side of the screen to the other to strike the ball back and forth. In this article, you will see how you can create a simple but exciting game of ping pong using Reac
    4 min read
  • Math Sprint Game using React
    In this article, we will create a Math Sprint Game Using ReactJS. Math Sprint is a fun and challenging game where players have to solve math problems within a time limit to earn points. This game presents random math questions with four options. Players click the correct answer, and if correct, it’s
    5 min read
  • Paint App using ReactJS
    In this article, we will be building a simple paint application that lets you draw just like in MS-Paint. Through this article, we will learn how to implement and work with canvas in React.js. Our app contains two sections, one for drawing and the other is a menu where the user can customize the bru
    4 min read
  • 15 Puzzle Game using ReactJS
    In this article, we will create the 15 Puzzle Game using ReactJS. 15 puzzle game is basically a tile-based game in which there are 16 tiles out of which 1 tile is left empty and the remaining tiles are filled with numbers from 1 to 15 in random order. The user has to arrange all the tiles in numeric
    6 min read
  • Typing Game using React
    React Typing Game is a fun and interactive web application built using React. It tests and improves the user's typing speed and accuracy by presenting sentences for the user to type within a specified time limit. The game provides real-time feedback by highlighting any mistakes made by the user, mak
    4 min read
  • Word Guess Game using React
    In this article, we will create an Interactive Word Guess Game using ReactJS. Word Guess game is basically a guessing game, where a hint will be given based on the hint you have to guess the word. This project basically implements functional components and manages the state accordingly. This Game al
    6 min read
  • Whack a Mole Game using ReactJS
    In this article, we explore the creation of a digital Whac-A-Mole game using React. This beloved classic challenges players to "whack" moles as they pop up from their holes. Prerequisites:Basic Knowledge of HTML, CSS, and JavaScript:React.jsNode.js and npmApproachProject Setup: Set up a new React pr
    3 min read
  • Tenzies Game using ReactJS
    In this article, we are going to implement Tenzied Games using React JS. Tenzies is a fast-paced and fun game where players have to race to roll a specific combination with a set of ten dice. As we are building this game with ReactJS, we are using the functional components to build the application,
    7 min read
  • GPA Calculator using React
    GPA Calculator is an application that provides a user interface for calculating and displaying a student's GPA(Grade Point Average). Using functional components and state management, this program enables users to input course information, including course name, credit hours and earned grades and add
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences