Command:
$ cat html5game_snake.html
Result:
<canvas id="gc" width="640" height="480"></canvas>
<script>
rh=rv=0;
//Resolution horizontal and vertical
sx=sy=1;
//Snake position x and y
gx=gy=1;
//Grid x and y
fps=60;
//Frames per second
a=0.1;
//Acceleration
v=1
//Velocity
vx=0;
//Velocity x
vy=0;
//Velocity y
dx=0;
//Distance x
dy=0;
//Distance y
gd=10;
//Grid dimension
kc=39;
//Key code
s=0;
//Score
window.onload=function() {
c=document.getElementById('gc');
cc=c.getContext('2d');
setInterval(update,1000/fps); //reflesh screen fps times a second
window.addEventListener("keydown", function(e){
console.log(e.keyCode);
kc=e.keyCode;
});
rh=c.width/gd;
rv=c.height/gd;
}
function update(){
v+=a/fps;
//Accelerate
if(kc==37){
//left
vx=-v;
vy=0;
} else if (kc==38) {
//up
vx=0;
vy=-v;
} else if (kc==39) {
//right
vx=v;
vy=0;
} else if (kc==40) {
//down
vx=0;
vy=v;
}
dx=vx/fps;
dy=vy/fps;
s+=Math.abs(dx);
s+=Math.abs(dy);
sx+=dx;
sy+=dy;
//Snake boundary condition for x
while(sx<0 || sx>rh){
if(sx<0){
sx+=rh;
} else if(sx>rh){
sx-=rh;
}
}
//Snake boundary condition for y
while(sy<0 || sy>rv){
if(sy<0){
sy+=rv;
} else if(sy>rv){
sy-=rv;
}
}
gx=Math.round(sx);
gy=Math.round(sy);
if (gx < 1){
gx=rh;
} else if (gx>rh) {
gx=1;
}
if (gy < 1){
gy=rv;
} else if (gy>rv) {
gy=1;
}
//Finally Display
cc.fillStyle='black';
cc.fillRect(0,0,c.width,c.height);
//Food
cc.fillStyle='white';
cc.fillRect(gd*Math.round(rh/2),gd*Math.round(rv/2),gd,gd);
//Snake
cc.fillStyle='white';
cc.fillRect(gd*(gx-1),gd*(gy-1),gd,gd);
cc.fillText(v,100,100);
cc.fillText("score:" + Math.round(s),c.width-100,100);
}
</script>
Command:
$ open html5game_snake.html
Result:
|
HTML5 Snake Alpha |