(Renkum, Monday 4th of June 2012)

The static screen

So, my first page is going to be an empty canvas. I will put my scripting in another file, so my first HTML5 webpage looks like this:

<!DOCTYPE html>
<html>
<header> 
<title>Heart Hunter Game</title>
</header>
<body>
<canvas id="gameCanvas" width="2400" height=1000>
     Your browser does not support the canvas tag.</canvas>
<script src="hearthunter.js"></script>
</body>
</html>

Primarily my script file is empty, but it will soon bee filled.

I will consider my screen as a 25x41 grid. I'll start with a static size of 16x16 rectangles as items. The startposition of the hunter is in the middle. So to setup the screen I invested one hour and I came up with the following piece of code:

(function () {
// some constants
numToAvoid = 50;
numTargets = 50;
fieldWidth = 41;
fieldHeight = 25;
itemWidth = 16;
itemHeight = 16;
scrWidth = fieldWidth * itemWidth;
scrHeight = fieldHeight * itemHeight;
curStartPos = 20;
numFields = fieldWidth * fieldHeight;

var canvas=document.getElementById('gameCanvas');
var ctx=canvas.getContext('2d');
var fields = new Array(numFields);
var cursorPos = curStartPos;
initField(fields, cursorPos); 
drawField(fields, cursorPos);

function initField(fieldArray, cursorposition){
	// Clear the field
	for (i = 0; i < numFields; i++){
		fieldArray[i] = 0;
	}
	
	// Place the targets and avoidables
	for (i = 0; i < numToAvoid + numTargets ; i++){
		x = Math.floor(Math.random() * numFields);
		while (fieldArray[x] != 0 || x == cursorposition){
			x++;
			if (x > numFields) x = 0;
		}
		if (i < numToAvoid) fieldArray[x] =  1;
		else fieldArray[x] =  2;		
	}
}

function drawField(fieldArray, cursorposition){
    // draw a rectangle as background
	ctx.fillStyle='#DDDDFF';
	ctx.fillRect(0,0,scrWidth,scrHeight);
	//draw the hunter
    ctx.fillStyle='#0000FF';
	ctx.fillRect(cursorposition*itemWidth
	            ,(fieldHeight-1)*itemHeight,itemWidth,itemHeight);
	
	//draw the other fields
	for ( k = 1; k < 3; k++){
	    if (k == 1) ctx.fillStyle='#FF0000';
		else ctx.fillStyle='#00FF00';
		for ( i = 0; i < fieldHeight; i++){
			for ( j = 0; j < fieldWidth; j++){
				if (fieldArray[j + i * fieldWidth] == k) 
				    ctx.fillRect(j*itemWidth
					            ,(fieldHeight-i-1)*itemHeight
								,itemWidth,itemHeight);
			}
		}
	}
}
})();

When I started up my first HTML5-with-jscript page, it looked like:

first result

To check that result, click here.

 


Day1 Day2 Day3
Day4 Day5 Day6 Day7
back to index