Minesweeper in Javascript and Canvas

Updating game logic

Our updateGame method will serve to process click events. How it does so depends on the current screen.

function updateGame()
{

If the current screen is the menu screen and the mouseState.click event is not null, we loop through the difficulties to see if the event fell on the menuBox area of an entry. If it did, we start a new game at that difficulty and clear the click event.

	if(gameState.screen=='menu')
	{
		if(mouseState.click!=null)
		{
			for(var i in difficulties)
			{
				if(mouseState.y >= difficulties[i].menuBox[0] &&
					mouseState.y <= difficulties[i].menuBox[1])
				{
					startLevel(i);
					break;
				}
			}
			mouseState.click = null;
		}
	}

If the current screen is won or lost however, we just return to the menu screen and clear the click event.

	else if(gameState.screen=='won' || gameState.screen=='lost')
	{
		if(mouseState.click!=null)
		{
			gameState.screen = 'menu';
			mouseState.click = null;
		}
	}

Otherwise, we are on the playing screen and a game is in progress. If a click event has occured, we begin by creating a temporary reference to the current difficulty (cDiff):

	else
	{
		if(mouseState.click!=null)
		{
			var cDiff = difficulties[gameState.difficulty];

Next, we test to see if the event fell on the grid. It must be greater than or equal to the offsetX, offsetY values, and less than these values plus the width or height of the current difficulty grid multiplied by the gameState tileW or tileH.

			if(mouseState.click[0]>=offsetX &&
				mouseState.click[1]>=offsetY &&
				mouseState.click[0]<(offsetX + (cDiff.width * gameState.tileW)) &&
				mouseState.click[1]<(offsetY + (cDiff.height * gameState.tileH)))
			{

If the click fell on the grid, we convert the pixel position of the click to the tile x, y position on the grid:

				var tile = [
					Math.floor((mouseState.click[0]-offsetX)/gameState.tileW),
					Math.floor((mouseState.click[1]-offsetY)/gameState.tileH)
				];

If the click button was the left mouse button, we call the click method for the target tile. Otherwise, we call the flag method:

				if(mouseState.click[2]==1)
				{
					grid[((tile[1] * cDiff.width) + tile[0])].click();
				}
				else
				{
					grid[((tile[1] * cDiff.width) + tile[0])].flag();
				}

If the click event did not fall on the grid, we see if the y value is greater than 380, in which case we'll leave the current game and go back to the menu screen.

			}
			else if(mouseState.click[1]>=380)
			{
				gameState.screen = 'menu';
			}

The click event is then cleared, and the if statements and current method is closed.

			mouseState.click = null;
		}
	}
}
Page loaded in 0.014 second(s).