Press ESC to close · Ctrl+K to open

Minesweeper Programmed with Artificial Intelligence

A first experiment generating a classic HTML and JavaScript game from instructions given to an AI.

Update: this was the first experiment in the series. To see how the project evolved, read the remastered version and Minesweeper III: A Quality Leap.

Digital illustration of mines exploding in the sea for the AI Minesweeper article

Introduction

We continue looking for practical uses for new artificial intelligence engines. Today it is the turn of one of the classics: Minesweeper.

The idea is to generate a Minesweeper game programmed with AI, using HTML and JavaScript so it can be executed directly in any browser.

This article belongs to the AI generated code section, where we test what these tools can contribute in simple programming exercises.

Minesweeper generated by artificial intelligence

Minesweeper generated by Artificial Intelligence.

Minesweeper is a logic and strategy game in which the player must find and mark all hidden mines on a board. The objective is to locate all the mines without detonating any of them. The board contains empty cells, mined cells and numbered cells that indicate how many mines are around them.

With the context in place, we can move to the experiment.

Important note: an AI does not always generate the same output for the same prompt. Therefore, the development shown here will not necessarily be replicated 100%, although with such a simple game it is easy to get a similar base using comparable instructions.

Tools

Step 1: ask the AI for the code

We ask OpenAI for the code through Playground. There are many ways to request it; the more detail we provide, the better the response usually becomes.

In this first test, the instruction was intentionally simple: generate a Minesweeper game with a specific 3x3 board.

Prompt used in Playground to generate a 3x3 Minesweeper

Instruction in Playground to generate a 3x3 Minesweeper.

Depending on the quality of the prompt, the response will be better or worse and we will need more or fewer iterations. In this case, several tests were needed before getting a useful base.

Step 2: analyze the first generated code

The generated code was enough to start, but it needed to be reviewed. This is the normal workflow: ask, test, detect the issue and ask again with a more precise instruction.

Tip: insist with clearer instructions until one of the iterations provides a good base to work from.

First generated base
<html>
<head>
<title>Minesweeper</title>
<style type="text/css">
.casilla {
    width: 30px;
    height: 30px;
    text-align: center;
    border: 1px solid #999;
    font-size: 18px;
    float: left;
    background-color: #eee;
}
</style>
</head>
<body>
<div>
    <h1>Minesweeper</h1>
    <button onclick="generarTablero()">Restart</button>
    <div id="tablero"></div>
</div>
<script>
    var tablero = [];
    var ancho = 3;
    var alto = 3;
    var minas = 1;
    generarTablero();
</script>
</body>
</html>
First Minesweeper generated code in Playground

First generated code base.

Step 3: correct the board size

The first visual result worked as a basic proof, but the board was too small. The next instruction asked the AI to improve the result and increase the board to 15x15.

Minesweeper with a 3x3 board

Minesweeper with a 3x3 board.

Minesweeper corrected to a 15x15 board

Corrected 15x15 board.

Possible improvements

The result is simple but functional. From here, the game could be improved with several additions:

  • Timer.
  • Score and number of mines found.
  • Difficulty levels.
  • Control of repeated mine positions.
  • A more polished visual design.

Even so, this first version already shows the value of AI as an assistant for generating a first programming base quickly.

Final code

HTML + JavaScript
<html>
<head>
<title>Minesweeper</title>
<style type="text/css">
.casilla {
    width: 30px;
    height: 30px;
    text-align: center;
    border: 1px solid #999;
    font-size: 18px;
    background-color: #eee;
}
.casilla.vacia {
    background-color: #fff;
}
.casilla.mina {
    background-color: #f00;
    color: #fff;
    font-weight: bold;
}
</style>
</head>
<body>
<div>
    <h1>Minesweeper</h1>
    <button onclick="generarTablero()">Restart</button>
    <div id="tablero"></div>
</div>
<script>
var tablero = [];
var ancho = 15;
var alto = 15;
var minas = 5;

function generarTablero() {
    tablero = [];
    let tableroHTML = '';

    for (let y = 0; y < alto; y++) {
        let fila = [];
        for (let x = 0; x < ancho; x++) {
            fila.push({
                mina: false,
                marcada: false,
                descubierta: false
            });
            tableroHTML += `<div class="casilla" data-x="${x}" data-y="${y}" onclick="descubrirCasilla(${x},${y})" oncontextmenu="marcarCasilla(${x},${y});return false;"></div>`;
        }
        tablero.push(fila);
    }

    document.getElementById('tablero').innerHTML = tableroHTML;
    document.getElementById('tablero').style.display = 'grid';
    document.getElementById('tablero').style.gridTemplateColumns = 'repeat(15, 30px)';
    generarMinas(minas);
}

function generarMinas(cantidadMinas) {
    for (let i = 0; i < cantidadMinas; i++) {
        let x = Math.floor(Math.random() * ancho);
        let y = Math.floor(Math.random() * alto);
        tablero[y][x].mina = true;
    }
}

function descubrirCasilla(x, y) {
    if (tablero[y][x].marcada || tablero[y][x].descubierta) return;

    if (tablero[y][x].mina) {
        descubrirTodasLasMinas();
        alert('Game Over');
    } else {
        tablero[y][x].descubierta = true;
        renderizarTablero();
        if (comprobarVictoria()) {
            alert('You won');
        }
    }
}

function marcarCasilla(x, y) {
    tablero[y][x].marcada = !tablero[y][x].marcada;
    renderizarTablero();
}

function descubrirTodasLasMinas() {
    tablero.forEach(function(fila, y) {
        fila.forEach(function(casilla, x) {
            if (casilla.mina) {
                tablero[y][x].descubierta = true;
            }
        });
    });
    renderizarTablero();
}

function comprobarVictoria() {
    return tablero.every(function(fila) {
        return fila.every(function(casilla) {
            return casilla.mina || casilla.descubierta;
        });
    });
}

function renderizarTablero() {
    tablero.forEach(function(fila, y) {
        fila.forEach(function(casilla, x) {
            let celda = document.querySelector(`div[data-x="${x}"][data-y="${y}"]`);
            if (casilla.descubierta) {
                celda.classList.add('vacia');
                if (casilla.mina) {
                    celda.innerText = 'X';
                } else {
                    let cantidadMinasAlrededor = contarMinasAlrededor(x, y);
                    celda.innerText = cantidadMinasAlrededor > 0 ? cantidadMinasAlrededor : '';
                }
            } else if (casilla.marcada) {
                celda.innerText = 'M';
            } else {
                celda.innerText = '';
            }
        });
    });
}

function contarMinasAlrededor(x, y) {
    let minasAlrededor = 0;

    for (let dy = -1; dy <= 1; dy++) {
        for (let dx = -1; dx <= 1; dx++) {
            if (dx === 0 && dy === 0) continue;

            let xAlrededor = x + dx;
            let yAlrededor = y + dy;

            if (xAlrededor >= 0 && xAlrededor < ancho && yAlrededor >= 0 && yAlrededor < alto) {
                if (tablero[yAlrededor][xAlrededor].mina) {
                    minasAlrededor++;
                }
            }
        }
    }

    return minasAlrededor;
}

generarTablero();
</script>
</body>
</html>


Was this article useful?

Share on LinkedIn