Creating a simple Minesweeper game in JavaScript with HTML and CSS involves a bit more complexity than the Snake game. Below is a basic implementation of Minesweeper. You can follow the same approach as before and create three files: index.html, styles.css, and script.js.
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minesweeper</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Minesweeper</h1>
<div id="gameContainer"></div>
<button id="restartButton" style="display: none;">Restart</button>
<script src="script.js"></script>
</body>
</html>
2. styles.css
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
}
h1 {
margin: 20px;
}
#gameContainer {
display: grid;
gap: 1px;
}
.cell {
width: 30px;
height: 30px;
background-color: #ccc;
text-align: center;
line-height: 30px;
cursor: pointer;
font-size: 18px;
}
.cell.revealed {
background-color: #fff;
cursor: default;
}
.cell.mine {
background-color: red;
}
.hidden {
visibility: hidden;
}
3. script.js
const rows = 10;
const cols = 10;
const minesCount = 15;
let board = [];
let revealedCount = 0;
let isGameOver = false;
// Initialize the game board
function initGame() {
board = Array.from({ length: rows }, () => Array(cols).fill({ mine: false, revealed: false, adjacent: 0 }));
// Place mines
for (let i = 0; i < minesCount; i++) {
placeMine();
}
// Calculate adjacent mines for each cell
calculateAdjacents();
// Render the board
renderBoard();
}
// Place a mine randomly
function placeMine() {
let placed = false;
while (!placed) {
const row = Math.floor(Math.random() * rows);
const col = Math.floor(Math.random() * cols);
if (!board[row][col].mine) {
board[row][col].mine = true;
placed = true;
}
}
}
// Calculate adjacent mines for each cell
function calculateAdjacents() {
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (board[r][c].mine) {
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
if (x === 0 && y === 0) continue;
const newRow = r + x;
const newCol = c + y;
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {
board[newRow][newCol].adjacent += 1;
}
}
}
}
}
}
}
// Render the board
function renderBoard() {
const container = document.getElementById('gameContainer');
container.innerHTML = ''; // Clear the container
container.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.row = r;
cell.dataset.col = c;
cell.addEventListener('click', handleClick);
// If the cell is revealed, show mine or adjacent count
if (board[r][c].revealed) {
revealCell(cell, r, c);
}
container.appendChild(cell);
}
}
}
// Handle cell click
function handleClick(event) {
if (isGameOver) return;
const row = event.target.dataset.row;
const col = event.target.dataset.col;
if (board[row][col].mine) {
isGameOver = true;
revealMines();
alert('Game Over! You hit a mine!');
} else {
revealCell(event.target, row, col);
}
}
// Reveal a cell and adjacent cells if there are no adjacent mines
function revealCell(cell, row, col) {
board[row][col].revealed = true;
revealedCount++;
cell.classList.add('revealed');
if (board[row][col].adjacent > 0) {
cell.textContent = board[row][col].adjacent;
} else {
// If the cell has no adjacent mines, reveal adjacent cells
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
if (x === 0 && y === 0) continue;
const newRow = row + x;
const newCol = col + y;
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !board[newRow][newCol].revealed) {
const adjCell = document.querySelector(`.cell[data-row="${newRow}"][data-col="${newCol}"]`);
revealCell(adjCell, newRow, newCol);
}
}
}
}
// Check for win condition
if (revealedCount === (rows * cols - minesCount)) {
isGameOver = true;
alert('Congratulations! You cleared the minefield!');
document.getElementById('restartButton').style.display = 'block';
}
}
// Reveal all mines when game is over
function revealMines() {
board.forEach((row, r) => {
row.forEach((cell, c) => {
if (cell.mine) {
const mineCell = document.querySelector(`.cell[data-row="${r}"][data-col="${c}"]`);
mineCell.classList.add('mine');
}
});
});
}
// Restart the game
document.getElementById('restartButton').addEventListener('click', () => {
initGame();
document.getElementById('restartButton').style.display = 'none';
});
// Initialize the game for the first time
initGame();
How to Run:
- Create a new folder on your computer and create the three files above within that folder.
- Open the
index.html file in your web browser.
Game Instructions:
- Click on the cells to reveal them. If you reveal a mine, the game is over, and mines will be revealed.
- If you reveal a cell with no adjacent mines, it will automatically reveal surrounding cells.
- The game is won when all non-mine cells are revealed.
- After the game ends, you can click the "Restart" button to play again.
This simple implementation can be expanded upon and improved with additional features like flags, timer, advanced styles, and better user interface elements. Feel free to enhance it further!