# Minesweeper in Javascript and Canvas

## Minesweeper theory

Minesweeper! That wonderfully simple yet entertaining puzzle that provides a welcome distraction from real work! In this article we'll look at the theory, and then how to put the game together in Javascript, Canvas and HTML.

The premise is simple; clear a grid of hidden tiles to isolate the mines, but touch a mine and it's all over! As you clear, numbers on revealed tiles tell you how many adjacent tiles have mines on them, or if the tile has no dangerous neighbours it reveals all neighbouring tiles.

When developing this game, there are two key areas. The first is how the grid itself is built:

```[grid] = [array of tiles, width x height]

[placed mines] = 0

do until [placed mines] == [desired number of mines]:
[pos] = select random tile

if [pos] has mine then restart 'do' loop
else:
[grid][pos] has mine
[placed mines] + 1
(loop)

foreach [pos] in [grid]:
set [grid][pos] danger = (number of adjacent tiles that have mines)
(loop)
```

### User interaction

Once our grid has been built, we handle user input. This consists of the user clicking on a tile, as well as a function that handles revealing the tile to the player, and works as follows:

```function reveal tile ( [tile] ):
set [tile] revealed

if [tile][danger] == 0:
foreach [n] in [neighbours]:
reveal tile( [n] )
(loop)
end function

if [clicked tile] has mine: game over
else:
reveal tile( [clicked tile] )

if [all tiles without mines] are revealed:
game won
```

These are the key concepts behind the game minesweeper, so if you follow these carry on to see how the game can be put together!