Using JavaScript to realize a matching game in web browse.
Purpose: find the extra “smile” in the left side, compared to the right side. Each time we click the ‘right’ smile, the number of pic will increase by 5. In this case, the difficulty will increase correspondingly.
So JS code is as follow:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Match Game - Part4</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberofFaces = 5;
function generateFaces(){
var num = numberofFaces;
var theBody = document.getElementsByTagName("body")[0];
var theleftside = document.getElementById("leftSide");
// can't put this line outside of func because at this time, the page doesn't load "leftside" div,
//so the variable "theleftside" will be null. This is the most common mistake for the beginner.
while(num>0){
var imgNode = document.createElement("img");
var x = 400 * Math.random();
var y = 400 * Math.random();
imgNode.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
imgNode.style.top = x + "px";
imgNode.style.left = y + "px";
theleftside.appendChild(imgNode);
num--;
}
var therightside = document.getElementById("rightSide");
var leftsideimg = theleftside.cloneNode(true);
leftsideimg.removeChild(leftsideimg.lastChild);
therightside.appendChild(leftsideimg);
theleftside.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
numberofFaces += 5;
// delete all the children
while(theleftside.firstChild){
theleftside.removeChild(theleftside.firstChild);
}
while(therightside.firstChild){
therightside.removeChild(therightside.firstChild);
}
generateFaces();
};
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theleftside.lastChild.onclick = null;
}
}
</script>
</head>
<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>