# A Simple HTML5 Game

My son is having summer vacation and he wanted to learn animation and create games. He had learnt Flash and ActionScript a couple of years back. So he started developing a game in Flash. However he ran into few issues and sought my help. Since I don’t know Flash, I could not help him much. But I suggested that if he develops his game in HTML5, I could help him. So while teaching him HTML5 and animation, I ended up creating a very simple game, which I want to share here.

In this game, when you press the ‘Start’ button, a square starts moving inside a bigger square and the goal is to prevent the smaller square hitting the outer square, by controlling its motion using arrow keys. You don’t need to keep the keys pressed, just press and release any arrow key to change direction. The square moves on its own and accelerates as the game progresses. Give it a try –

The animation loop in this game is created using window.setInterval() function, initially in the startGame() function and then later when the square needs to be accelerated, in accelerate() function. Before creating a new interval in the accelerate(), old loop is cancelled by calling window.clearInterval(). The square is drawn in animateFunc(), which is called by setInterval() method at fixed interval. See the code listing at the end of this post.

Acceleration is controlled by three variables; xStep, yStep and interval. xStep and yStep determine how much the square should move along X and Y axis respectively. interval determines how frequently animateFunc() is called. The interval at which acceleration is changed is controlled by changeAccelerationInterval variable. The game can be made as simple or difficult as you want by tweaking values of these variables.

Key down event (for all arrow keys) is handled by handleKeyDown() and up event is handled by handleKeyUp(). The score is calculated by dividing number of seconds played by two.

Note that I haven’t used animation optimizations techniques I had discussed in my earlier posts in this game because there is not much to redraw on the Canvas and performance is quite good.

Though the game is very simple, I had fun developing it.

-Ram Kulkarni

```<html xmlns="http://www.w3.org/1999/xhtml">
<title>Simple Game</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>

<script type="text/javascript">
var currXPos = 0, currYPos = 0;;
var width = 400, height = 300;
var rectWidth = 20, rectHeight = 20;
var xDir = 1, yDir = 1, xStep = 2, yStep = 2, interval = 60;
var changeAccelerationInterval = 4000; //4 seconds
var changeXDir = true, changeYDir = true;
var stopAnimation = true;
var scoreStartTime, acceStartTime = 0;

can1 = \$("#canvas1");
ctx = can1.getContext("2d");

\$(document).keydown(handleKeyDown);
\$(document).keyup(handleKeyUp);
\$("#startBtn").click (startGame);
});

function startGame()
{
xDir = yDir = 1;
xStep = yStep = 2;
interval = 60;
changeXDir = changeYDir = true;
currXPos = (width / 2) - (rectWidth / 2);
currYPos = (height / 2) - (rectHeight / 2);

stopAnimation = false;
scoreStartTime = acceStartTime = (new Date()).getTime();
\$("#startBtn").hide();
\$("#scoreDiv").hide();
animateFunc();
intervalId = window.setInterval(animateFunc, interval);
}

function stopGame()
{
var timePlayed = (new Date()).getTime() - scoreStartTime;
var score = new Number(timePlayed / (1000 * 2)).toFixed(0);
\$("#startBtn").show();
window.clearInterval(intervalId);
stopAnimation = true;
\$("#scoreDiv").html("You scored " + score + " points").show();
}

function accelerate()
{
if (interval > 3)
interval -= 3;

xStep++; yStep++;
window.clearInterval(intervalId);
acceStartTime = new Date().getTime();
intervalId = window.setInterval(animateFunc, interval);
}

function isTimeToaccelerate()
{
if (((new Date()).getTime() - acceStartTime) > changeAccelerationInterval)
return true;
return false;
}

function handleKeyDown (event)
{
if (stopAnimation || (!changeXDir && !changeYDir))
return;

if (event.which < 37 || event.which > 40)
return;

if ((event.which == 38 || event.which == 40) && changeYDir)
{
if (event.which == 38) //up
yDir = -1;
else //down
yDir = 1;
changeYDir = false;
event.preventDefault();
}
else if ((event.which == 37 || event.which == 39) && changeXDir)
{
if (event.which == 37) //left
xDir = -1;
else // right
xDir = 1;
changeXDir = false;
event.preventDefault();
}
}

function handleKeyUp (event)
{
switch (event.which)
{
case 38: //up
case 40: //down
changeYDir = true;
event.preventDefault();
break;
case 37: //left
case 39: //right
changeXDir = true;
event.preventDefault();
break;
}
}

function animateFunc()
{
ctx.beginPath();
ctx.clearRect(0,0,width,height);
ctx.rect(currXPos,currYPos, rectWidth,rectHeight);
ctx.stroke();

currXPos += xStep * xDir;
currYPos += yStep * yDir;

if (currXPos <= 0 || currXPos >= (width - rectWidth) ||
currYPos <= 0 || currYPos >= (height - rectHeight))
{
stopGame();
return;
}

if (isTimeToaccelerate())
accelerate();
}

// get random number between X and Y
function getRand(x, y) {
return Math.floor(Math.random()*y)+x;
}
</script>

<body >
<div id="kineticDiv"></div>
<canvas id="canvas1" height="300" width="400" style="border-style:solid;border-color:#DDD"></canvas><br>
<input id="startBtn" type="button" value="Start"> <br>
<div id="scoreDiv" style="background-color:#AAA;
font-size:larger;border-color:#000;
border-style:outset;display:none;max-width:400px"></div>
</body>
</html>
```

## One Reply to “A Simple HTML5 Game”

1. Shanita says:

Bless you for trying to explain the terminlogy for the starters!
{"ft_lang_label":"__label__en","ft_lang_prob":0.68245584,"math_prob":0.94907963,"size":5529,"snap":"2021-43-2021-49","text_gpt3_token_len":1421,"char_repetition_ratio":0.12506787,"word_repetition_ratio":0.005076142,"special_character_ratio":0.28648943,"punctuation_ratio":0.19367991,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96604776,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-16T12:22:50Z\",\"WARC-Record-ID\":\"<urn:uuid:58b1b3c0-b536-4c71-9a16-988db8b1a4cc>\",\"Content-Length\":\"121917\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7b24db4f-7e78-4a34-b102-5792cc0624ed>\",\"WARC-Concurrent-To\":\"<urn:uuid:3a0f7b2f-85a4-4083-8f3a-1dcba5d7dff9>\",\"WARC-IP-Address\":\"138.197.85.232\",\"WARC-Target-URI\":\"http://ramkulkarni.com/blog/a-simple-html5-game/\",\"WARC-Payload-Digest\":\"sha1:RUPF5TLJVJZO57WLTFKEKBE2YQBKP5AX\",\"WARC-Block-Digest\":\"sha1:MF4GUT3D3RVYV55XKGFSSJ5H3LG46RAZ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323584567.81_warc_CC-MAIN-20211016105157-20211016135157-00414.warc.gz\"}"}