javascriptが実現したシンプルなタイピングゲームです.
3408 ワード
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> </title>
<style type="text/css">
.label{
position:absolute;left: 0px;
}
</style>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<div id="msg"></div>
<input id="startBtn" type="button" value=" " onclick="startGame(this)"/>
<input type="button" value=" " onclick="stopGame()"/>
</body>
</html>
var CODE = "QWERTYUIOPASDFGHJKLZXCVBNM";
var codeArray = [];
var number = 0;
//
function createCode(){
//0-25
var index = parseInt(Math.random()*26);
return CODE.charAt(index);
};
// label
function createLabel(code){
/**
* <label class="label">
A
</label>
*/
var label = document.createElement("label");
label.className = "label";
label.style.top = "50px";
label.innerHTML = code;
label.code = code;
var html = document.documentElement;
// label x
var labelX = parseInt(Math.random()*html.clientWidth);
if(labelX>100){
labelX-=20;
}
label.style.left = labelX+"px";
return label;
}
window.onload = function(){
document.getElementById("startBtn").disabled = false;
//
document.documentElement.onkeydown=function(event){
var keyCode = event.keyCode; //
var code = String.fromCharCode(keyCode);//A-Z
for ( var i = 0; i < codeArray.length; i++) {
//label
var label = codeArray[i];
if(label.code==code){
clearInterval(label.interval_id);
label.parentNode.removeChild(label);
codeArray.splice(i,1);
number+=10;
document.getElementById("msg").innerHTML = number+" ";
break;
}
}
};
};
// label
function runLabelTop(label){
//
var height = Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight);
label.interval_id = setInterval(function(){
//50px
var top = parseInt(label.style.top);
top+=1;
// label
if(top>height-30){
removeLabel(label,false);
}else{
label.style.top = top+"px";
}
},10);
}
//flag = false
function removeLabel(label,flag){
clearInterval(label.interval_id);
label.parentNode.removeChild(label);
codeArray.shift();
number-=20;
document.getElementById("msg").innerHTML = number+" ";
}
var game_id = null;
//
function startGame(startButton){
startButton.disabled = true;
game_id = setInterval(function(){
//
var code =createCode();
// label
var label = createLabel(code);
// label , style.top
runLabelTop(label);
// label
document.body.appendChild(label);
codeArray.push(label);
},1000);
}
//
function stopGame(){
clearInterval(game_id);
for ( var i = 0; i < codeArray.length; i++) {
clearInterval(codeArray[i].interval_id);
codeArray[i].parentNode.removeChild(codeArray[i]);
}
codeArray = [];
document.getElementById("startBtn").disabled = false;
}