Pop the Monster
* Start game by pressing ENTER key. * Monster appears on every set millisecond. * When hit, monster turns to yellow and hit score is added by 1. * When missed *during click only*, monster turns to red and chances left will be subtracted by 1. * When the game is over, check if player has the top score.
by Aya Alao
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<canvas id="canvas" width="450" height="450"></canvas>
JavaScript
$(document).ready(function()
{
// canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
// monster
var locX;
var locY;
var monsterSize = 50;
var monSpaceX; // space occupied by monster in X
var monSpaceY; // space occupied by monster in Y
// colors
var bgColor = "white";
var strokeColor = "black";
var monsterColor = "blue";
var monsterHitColor;
// other variables
var text; // label on canvas
var topScore = 0;
var topText;
var hitScore; // number of hits
var isHit;
var missLimit;
var interval;
var msec = 700;
var play; // game is ongoing
init();
// ** ----- FUNCTIONS ----- **
// initialize
function init()
{
// initialize variables
hitScore = 0;
missScore = 0;
missLimit = 5;
text = "Click ENTER key to play.";
topText = "Top Score: " + topScore;
play = false;
window.clearInterval(interval);
// draw canvas
paintCanvas();
}
// draw canvas
function paintCanvas()
{
// format canvas by setting BG color and border
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = strokeColor;
ctx.strokeRect(0, 0, w, h);
setLabel();
}
// draw monster
function placeMonster()
{
// set score label
text = "Score: " + hitScore + "; Chance left: " + missLimit;
setLocation(); // random location
paintCanvas(); // draw canvas to cover past monsters
// monster
ctx.fillStyle = monsterColor;
ctx.fillRect(locX, locY, monsterSize, monsterSize);
}
// paint monster to indicate it is hit or not
function paintMonsterHit()
{
ctx.fillStyle = monsterHitColor;
ctx.fillRect(locX, locY, monsterSize, monsterSize);
}
// place label on canvas
function setLabel()
{
// set top score label above
ctx.fillStyle = strokeColor;
ctx.fillText(topText, 5, 10);
// set label below
ctx.fillStyle = strokeColor;
ctx.fillText(text, 5, h - 5);
}
// randomly generate...