Whack-A-Moo
A Javascript Whack-a-Mole game for Moo Challenge #2
by haliphax
HTML
<button type="button" id="start">Start</button>
<div id="game">
<div id="pitch"></div>
<div id="score-label">Score: <span id="score">0</span> points</div>
</div>
CSS
#game {
display: none;
}
#pitch div {
width: 20px;
height: 20px;
margin: 1px;
float: left;
background-color: lightgray;
}
#pitch div.first {
clear: left;
}
#pitch div.moo {
background-color: green;
}
#score-label {
clear: both;
}
JavaScript
// @haliphax
document.querySelector("#start").onclick = function()
{
var
WIDTH = Math.max(prompt("Width in cells", 15) | 0, 5)
, HEIGHT = Math.max(prompt("Height in cells", 15) | 0, 5)
, field = document.querySelector("#pitch")
, gamelength = Math.max(prompt("Length of game in seconds", 60) | 0, 10) * 1000
, timer
, score = 0
;
for(var row = 0; row < HEIGHT; row++)
{
var first = true;
for(var col = 0; col < WIDTH; col++)
{
var cell = document.createElement("div");
if(first)
{
cell.setAttribute("class", "first");
first = false;
}
field.appendChild(cell);
}
}
alert("Get ready!");
timer = setInterval(function()
{
var
myrow = (Math.random() * HEIGHT) | 0
, mycol = (Math.random() * WIDTH) | 0
, mycell
, myclass
, moo
;
moo = document.querySelector("#pitch .moo");
if(moo != null)
{
moo.setAttribute("class", moo.getAttribute("class").replace(/^moo /, ""));
}
moo = document.querySelectorAll("#pitch div")[myrow * WIDTH + mycol];
myclass = moo.getAttribute("class");
if(! myclass)
{
myclass = "";
}
moo.setAttribute("class", "moo " + myclass);
}
, 1125);
setTimeout(function()
{
clearInterval(timer);
alert("GAME OVER, MAN!");
}
, gamelength);
document.onclick = function(e)
{
var target = (e.target || e.srcElement);
if(/^moo /.exec(target.getAttribute("class")))
{
score++;
target.setAttribute("class", target.getAttribute("class").replace(/^moo /, ""));
}
else
{
...