Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

code in html for minesweaper game in darkmode

  1. User

    code in html for minesweaper game in darkmode

  2. Assistant

    Here's an HTML code for a simple Minesweeper game in dark mode. This implementation uses HTML, CSS, and JavaScript to create an interactive game that you can play directly in your browser.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Minesweeper in Dark Mode</title>
        <style>
            /* CSS Styles for Dark Mode */
            body {
                background-color: #121212;
                color: #ffffff;
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 20px;
                user-select: none;
            }
            h1 {
                text-align: center;
                margin-bottom: 10px;
            }
            #game-board {
                display: grid;
                grid-template-columns: repeat(10, 40px);
                grid-template-rows: repeat(10, 40px);
                gap: 2px;
                width: fit-content;
                margin: 20px auto;
            }
            .cell {
                width: 40px;
                height: 40px;
                background-color: #1e1e1e;
                border: 1px solid #3c3c3c;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                color: #ffffff;
                font-size: 18px;
                font-weight: bold;
            }
            .cell.open {
                background-color: #2b2b2b;
                cursor: default;
            }
            .cell.mine {
                background-color: #b71c1c;
            }
            .cell.flagged {
                background-color: #3c3c3c;
            }
            .controls {
                text-align: center;
                margin-bottom: 20px;
            }
            .controls button {
                background-color: #1e1e1e;
                color: #ffffff;
                border: 1px solid #3c3c3c;
                padding: 10px 20px;
                cursor: pointer;
                font-size: 16px;
            }
            .controls button:hover {
                background-color: #2b2b2b;
            }
        </style>
    </head>
    <body>
    
        <h1>Minesweeper - Dark Mode</h1>
        <div class="controls">
            <button onclick="initGame()">Restart Game</button>
        </div>
        <div id="game-board"></div>
    
        <script>
            // Game Settings
            const BOARD_SIZE = 10;
            const MINE_COUNT = 15;
    
            let board = [];
            let gameBoardElement = document.getElementById('game-board');
    
            // Initialize the game
            function initGame() {
                board = [];
                gameBoardElement.innerHTML = '';
                createBoard();
                placeMines();
                calculateMineCounts();
            }
    
            // Create the game board
            function createBoard() {
                for (let row = 0; row < BOARD_SIZE; row++) {
                    board[row] = [];
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        let cellElement = document.createElement('div');
                        cellElement.classList.add('cell');
                        cellElement.dataset.row = row;
                        cellElement.dataset.col = col;
                        cellElement.addEventListener('click', cellClicked);
                        cellElement.addEventListener('contextmenu', cellRightClicked);
                        gameBoardElement.appendChild(cellElement);
    
                        board[row][col] = {
                            element: cellElement,
                            hasMine: false,
                            isOpen: false,
                            isFlagged: false,
                            mineCount: 0
                        };
                    }
                }
            }
    
            // Place mines randomly on the board
            function placeMines() {
                let minesPlaced = 0;
                while (minesPlaced < MINE_COUNT) {
                    let row = Math.floor(Math.random() * BOARD_SIZE);
                    let col = Math.floor(Math.random() * BOARD_SIZE);
                    if (!board[row][col].hasMine) {
                        board[row][col].hasMine = true;
                        minesPlaced++;
                    }
                }
            }
    
            // Calculate the number of adjacent mines for each cell
            function calculateMineCounts() {
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        if (!board[row][col].hasMine) {
                            let mineCount = 0;
                            for (let i = -1; i <= 1; i++) {
                                for (let j = -1; j <= 1; j++) {
                                    let newRow = row + i;
                                    let newCol = col + j;
                                    if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE) {
                                        if (board[newRow][newCol].hasMine) {
                                            mineCount++;
                                        }
                                    }
                                }
                            }
                            board[row][col].mineCount = mineCount;
                        }
                    }
                }
            }
    
            // Handle left-click on a cell
            function cellClicked(e) {
                let row = parseInt(this.dataset.row);
                let col = parseInt(this.dataset.col);
                openCell(row, col);
            }
    
            // Handle right-click on a cell
            function cellRightClicked(e) {
                e.preventDefault();
                let row = parseInt(this.dataset.row);
                let col = parseInt(this.dataset.col);
                toggleFlag(row, col);
            }
    
            // Open a cell
            function openCell(row, col) {
                let cell = board[row][col];
                if (cell.isOpen || cell.isFlagged) return;
    
                cell.isOpen = true;
                cell.element.classList.add('open');
    
                if (cell.hasMine) {
                    cell.element.classList.add('mine');
                    cell.element.textContent = '💣';
                    gameOver(false);
                } else {
                    if (cell.mineCount > 0) {
                        cell.element.textContent = cell.mineCount;
                    } else {
                        // Recurse to open adjacent cells
                        for (let i = -1; i <= 1; i++) {
                            for (let j = -1; j <= 1; j++) {
                                let newRow = row + i;
                                let newCol = col + j;
                                if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE) {
                                    if (!board[newRow][newCol].isOpen) {
                                        openCell(newRow, newCol);
                                    }
                                }
                            }
                        }
                    }
                    checkWin();
                }
            }
    
            // Toggle flag on a cell
            function toggleFlag(row, col) {
                let cell = board[row][col];
                if (cell.isOpen) return;
    
                cell.isFlagged = !cell.isFlagged;
                if (cell.isFlagged) {
                    cell.element.classList.add('flagged');
                    cell.element.textContent = '🚩';
                } else {
                    cell.element.classList.remove('flagged');
                    cell.element.textContent = '';
                }
            }
    
            // Check if the player has won the game
            function checkWin() {
                let openedCells = 0;
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        if (board[row][col].isOpen) {
                            openedCells++;
                        }
                    }
                }
                if (openedCells === BOARD_SIZE * BOARD_SIZE - MINE_COUNT) {
                    gameOver(true);
                }
            }
    
            // Reveal all mines and end the game
            function gameOver(won) {
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        let cell = board[row][col];
                        if (cell.hasMine) {
                            cell.element.classList.add('open');
                            cell.element.classList.add('mine');
                            cell.element.textContent = '💣';
                        }
                        cell.element.removeEventListener('click', cellClicked);
                        cell.element.removeEventListener('contextmenu', cellRightClicked);
                    }
                }
                setTimeout(() => {
                    alert(won ? 'Congratulations! You won!' : 'Game Over! You hit a mine.');
                }, 100);
            }
    
            // Start the game on page load
            window.onload = initGame;
        </script>
    </body>
    </html>
    

    Explanation:

    • HTML Structure:

      • The game consists of a <div> with the ID game-board where the grid is dynamically generated.
      • A "Restart Game" button is added to allow restarting the game without refreshing the page.
    • CSS Styling:

      • The body has a dark background color (#121212) and white text to create a dark mode theme.
      • Cells (.cell) have dark backgrounds, borders, and change appearance when opened, flagged, or when they contain a mine.
      • A grid display is used to arrange the cells in a 10x10 layout.
    • JavaScript Logic:

      • The game uses a 2D array board to represent the game state.
      • initGame() Function:
        • Initializes or resets the game by creating the board, placing mines, and calculating adjacent mine counts.
      • createBoard() Function:
        • Generates the grid of cells and attaches event listeners for left and right clicks.
      • placeMines() Function:
        • Randomly places a specified number of mines (MINE_COUNT) on the board.
      • calculateMineCounts() Function:
        • Calculates how many mines are adjacent to each cell.
      • Event Handlers:
        • Left-click (cellClicked) opens a cell.
        • Right-click (cellRightClicked) toggles a flag on a cell.
      • openCell() Function:
        • Opens a cell and recursively opens adjacent cells if there are no adjacent mines.
        • Checks for game over conditions.
      • toggleFlag() Function:
        • Flags or unflags a cell to indicate suspected mines.
      • checkWin() Function:
        • Checks if all non-mine cells are opened to declare a win.
      • gameOver() Function:
        • Reveals all mines and displays a message indicating if the player has won or lost.

    Instructions to Run the Game:

    1. Save the Code:

      • Copy the entire code above and paste it into a new text file.
      • Save the file with an .html extension, for example, minesweeper_darkmode.html.
    2. Open in a Browser:

      • Open the saved HTML file in a modern web browser like Chrome, Firefox, or Edge.
    3. Play the Game:

      • Left-click on cells to reveal them.
      • Right-click on cells to place or remove flags.
      • The goal is to open all non-mine cells without clicking on a mine.
      • Click the "Restart Game" button to start a new game at any time.

    Enjoy playing Minesweeper in dark mode!