Minesweeper in Javascript and Canvas

Global variables and objects

Now on to the main code of the game! To begin with, we'll need some global variables to keep track of various things throughout the game.

We'll start by creating a variable, ctx, that we'll use as a reference to our Canvas elements 2D drawing context later on. We'll also create gameTime, to keep track of the elapsed time for the current game in milliseconds, and lastFrameTime, the time the game update function last ran in milliseconds, as well as three variables (currentSecond, frameCount and framesLastSecond) for displaying the frame rate.

var ctx = null;

var gameTime = 0, lastFrameTime = 0;
var currentSecond = 0, frameCount = 0, framesLastSecond = 0;

We'll also need offsetX and offsetY when calculating the the position of the game grid on the Canvas, and the grid array which will store our game tiles when we start a play a level:

var offsetX = 0, offsetY = 0;
var grid = [];

Global objects

We also need some globally available objects for keeping track on events, states, and settings throughout the game. The first of these is mouseState, which stores the position of the cursor on the Canvas (x, y), and if a click event has occured and needs to be processed. The value of this will either be null if there is no unprocessed click event, or an array in the form [x, y, button], where x, y is the coordinates of the event, and button is the mouse button that was clicked there (1 for left button, otherwise 2).

var mouseState = {
	x	: 0,
	y	: 0,
	click	: null

We'll also store some information about the gameState. We need to know the current difficulty, the screen to display, whether or not the Player has achieved a newBest time for this difficulty once the grid is cleared, and the timeTaken, in milliseconds, for the player to clear the grid.

We'll also specify the tileW and tileH (width and height) at which we'll draw tiles on the grid, in pixels.

var gameState = {
	difficulty	: 'easy',
	screen		: 'menu',
	newBest		: false,
	timeTaken	: 0,
	tileW		: 20,
	tileH		: 20

We'll also have a map of available difficulty settings. For each setting we need to specify the name of the difficulty, the width and height of the grid, in tiles, the number of mines to place randomly on the grid, and bestTime (which we'll give the value 0) to keep track of the players best time for this difficulty, as well as menuBox, an array with the values [0, 0] that we'll use later:

var difficulties = {
	easy	: {
		name		: "Easy",
		width		: 10,
		height		: 10,
		mines		: 10,
		bestTime	: 0,
		menuBox		: [0,0]
	medium	: {
		name		: "Medium",
		width		: 12,
		height		: 12,
		mines		: 20,
		bestTime	: 0,
		menuBox		: [0,0]
	hard	: {
		name		: "Hard",
		width		: 15,
		height		: 15,
		mines		: 50,
		bestTime	: 0,
		menuBox		: [0,0]
Page loaded in 0.011 second(s).