Practice Piano
by egon
HTML
<div id="center">
<hr />
<canvas id="canvas"></canvas>
<hr />
<script type="text/javascript">
canvas = document.getElementById("canvas");
W=800; H=400;
canvas.width = W;
canvas.height = H,
canvas2D = canvas.getContext("2d");
</script>
</div>
CSS
body {
margin : 0 0;
margin-top : 200px;
width : 100%;
background: #000;
}
#center {
align : center;
margin : 0 auto;
margin-top : 30px;
width : 800px;
}
hr {
color: #fff;
}
#logDiv {
font:normal 12px/16px Courier New, monospace;
color: #fff;
height: 200px;
overflow: scroll;
}
JavaScript
high = 0;
function save(){
localStorage.setItem('highscore', high);
}
function load(){
var val = localStorage.getItem('highscore');
if( val ){
val = parseInt(val);
high = val;
}
}
function reset(){
states = {};
lastkey = "";
lastcount = 0;
keys = " UIOP";
order = "PIOUI ";
next = 0;
wait = 7;
correct = 0;
for(var i = 0; i < keys.length; i += 1){
states[ keys[i] ] = { next: false, wrong : false};
}
states[order[0]].next = true;
}
reset();
load();
function draw(){
ctx = canvas2D;
ctx.font = "28px Georgia";
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#000";
ctx.fillRect(0,0,W,H);
w = W / (keys.length + 1);
x = w / 2;
y = w;
for(var i = 0; i < keys.length; i += 1){
var key = keys[i];
if( states[ key ].next ){
ctx.fillStyle = "#2e2";
} else if ( states[key].wrong ){
ctx.fillStyle = "#e22";
} else {
ctx.fillStyle = "#fff";
}
ctx.beginPath();
ctx.rect(x,y,w,w);
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#000";
ctx.fillText( key, x - 8 + w / 2, y + 9 + w / 2 );
x += w;
}
ctx.fillStyle = "#000";
ctx.fillText( "high: " + high, w / 2, w / 2);
ctx.fillText( "cur: " + correct, 200 + w / 2, w / 2);
ctx.font = "11px Georgia";
ctx.fillText( "R: reset", w / 2, w / 6);
}
function onkey(e){
var key = String.fromCharCode( e.keyCode );
if( key === "R" ){ reset(); return; }
if( key != lastkey ){
lastkey = key;
lastcount = 1;
} else {
lastcount += 1;
}
if( lastcount > 2 ) return;
if( key === order[ next ] ){
correct += 1;
if( correct > high ) high = correct;
if( wait === 0 ){
wait = 7;
return;
}
states[ key ].next = false;
...