Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Whack-a-Mole Game using HTML CSS and JavaScript
Next article icon

Create a Minesweeper Game using HTML CSS & JavaScript

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

Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.

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

Screenshot-2023-09-25-173603

Prerequisites

Before we dive into coding, make sure you have the following tools and knowledge:

  • Basic understanding of HTML, CSS, and JavaScript.
  • A code editor like Visual Studio Code or Sublime Text.
  • A modern web browser (e.g., Chrome, Firefox).

Approach

  • Use <h1> for the game title.
  • Create a grid of <div> elements to represent the cells of the Minesweeper board.
  • Define styles for the game board, cells, buttons, and other UI components.
  • Apply colors, fonts, and layout rules to make the game visually appealing.
  • Generate a grid of cells based on the desired number of rows and columns.
  • Randomly place mines within the grid while ensuring that mines are not placed adjacent to each other.
  • Handle user interactions, such as clicking on cells.
  • Keep track of the game state, including whether the player has won or lost.
  • Implement win and lose conditions.

Example: The code below explains the approach.

JavaScript
// Script.js const numRows = 8; const numCols = 8; const numMines = 10;  const gameBoard =     document.getElementById(         "gameBoard"     ); let board = [];  function initializeBoard() {     for (let i = 0; i < numRows; i++) {         board[i] = [];         for (             let j = 0;             j < numCols;             j++         ) {             board[i][j] = {                 isMine: false,                 revealed: false,                 count: 0,             };         }     }      // Place mines randomly     let minesPlaced = 0;     while (minesPlaced < numMines) {         const row = Math.floor(             Math.random() * numRows         );         const col = Math.floor(             Math.random() * numCols         );         if (!board[row][col].isMine) {             board[row][                 col             ].isMine = true;             minesPlaced++;         }     }      // Calculate counts     for (let i = 0; i < numRows; i++) {         for (             let j = 0;             j < numCols;             j++         ) {             if (!board[i][j].isMine) {                 let count = 0;                 for (                     let dx = -1;                     dx <= 1;                     dx++                 ) {                     for (                         let dy = -1;                         dy <= 1;                         dy++                     ) {                         const ni =                             i + dx;                         const nj =                             j + dy;                         if (                             ni >= 0 &&                             ni <                                 numRows &&                             nj >= 0 &&                             nj <                                 numCols &&                             board[ni][                                 nj                             ].isMine                         ) {                             count++;                         }                     }                 }                 board[i][j].count =                     count;             }         }     } }  function revealCell(row, col) {     if (         row < 0 ||         row >= numRows ||         col < 0 ||         col >= numCols ||         board[row][col].revealed     ) {         return;     }      board[row][col].revealed = true;      if (board[row][col].isMine) {         // Handle game over         alert(             "Game Over! You stepped on a mine."         );     } else if (         board[row][col].count === 0     ) {         // If cell has no mines nearby,         // Reveal adjacent cells         for (             let dx = -1;             dx <= 1;             dx++         ) {             for (                 let dy = -1;                 dy <= 1;                 dy++             ) {                 revealCell(                     row + dx,                     col + dy                 );             }         }     }      renderBoard(); }  function renderBoard() {     gameBoard.innerHTML = "";      for (let i = 0; i < numRows; i++) {         for (             let j = 0;             j < numCols;             j++         ) {             const cell =                 document.createElement(                     "div"                 );             cell.className = "cell";             if (board[i][j].revealed) {                 cell.classList.add(                     "revealed"                 );                 if (                     board[i][j].isMine                 ) {                     cell.classList.add(                         "mine"                     );                     cell.textContent =                         "????";                 } else if (                     board[i][j].count >                     0                 ) {                     cell.textContent =                         board[i][                             j                         ].count;                 }             }             cell.addEventListener(                 "click",                 () => revealCell(i, j)             );             gameBoard.appendChild(cell);         }         gameBoard.appendChild(             document.createElement("br")         );     } }  initializeBoard(); renderBoard(); 
HTML
<!-- Index.html --> <!DOCTYPE html> <html>  <head>     <title>Minesweeper Game</title> </head> <link rel="stylesheet" href="./style.css">  <body>     <h1>Minesweeper</h1>     <div id="gameBoard"></div> </body> <script src="./script.js"></script>  </html> 
CSS
/* Styles.css */ body {     font-family: Arial, sans-serif;     text-align: center; } .board {     display: inline-block;     margin: 20px; } .cell {     width: 30px;     height: 30px;     border: 1px solid #ccc;     display: inline-block;     text-align: center;     vertical-align: middle;     font-size: 20px;     cursor: pointer;      /* Default color for unrevealed tiles */     background-color: #eee;      /* Default color for unrevealed tile text */     color: #333; } .revealed {     /* Color for revealed tiles */     background-color: #ccc;      /* Color for revealed tile text */     color: #000; } .mine {     /* Color for mines */     background-color: #ff3333; } 

Output:

mine-sweeper
minesweeper game

Next Article
Whack-a-Mole Game using HTML CSS and JavaScript

L

lunatic1
Improve
Article Tags :
  • HTML
  • JavaScript-Projects
  • Geeks Premier League 2023

Similar Reads

    Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over.Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequ
    4 min read
    Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.  The project will contain HTML, CSS and JavaScript files. The H
    6 min read
    Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
    Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
    Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over.Prerequisite
    5 min read
    Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
    Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image
    3 min read
    Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
    Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to
    5 min read
    Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 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