H 5 canvasヘビを食いしん坊にするゲームを実現(完備を待つ)
4456 ワード
h5 ( )
function addEvent(obj,type,fn){
if (obj.addEventListener) {
obj.addEventListener(type,fn,false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + type,function(){
fn.call(obj);
})
}
}
var c = document.getElementById('my_canvas');
var ctx = c.getContext('2d');
var body = {
x: new Array(),
y: new Array()
}
body.x.push(15);
body.y.push(15);
var x,y;
var r = 15; //
var step = r*2; //
var x_random;
var y_random;
var speed = 500;
//
function setCir(){
x_random = 15+30*getRandomFromTwoNumber(1,15);
y_random = 15+30*getRandomFromTwoNumber(1,15);
ctx.beginPath();
ctx.fillStyle = '#f00';
ctx.arc(x_random,y_random,r,0,2*Math.PI);
ctx.fill();
}
setCir();
move(step,0);
//
function move(h,s){
//
if (body.x[0] + h > 500-15 || body.y[0] + s > 500-15 || body.x[0] + h < 15 || body.y[0] + h < 15) {
alert(' !');
window.location.reload();
}
//
if (body.x[0] + h === x_random && body.y[0] + s === y_random) {
body.x.splice(2,0,body.x[1]);
body.y.splice(2,0,body.y[1]);
console.log('+1');
clearHead();
headMove(h,s);
ctx.beginPath();
ctx.fillStyle = '#0f0';
ctx.fillRect(body.x[2],body.y[2],r*2,r*2);
setCir();
speed = speed - 100;
return;
}
//
clearBody();
//
if (body.x.length>2) {
for (var i = body.x.length-1; i > 1; i--) {
ctx.beginPath();
ctx.fillStyle = '#0f0';
ctx.fillRect(body.x[i]=body.x[i-1],body.y[i]=body.y[i-1],r*2,r*2);
}
}
//
headMove(h,s);
}
//
function clearHead(){
for (var i = 0; i < 2; i++) {
if (i == 0) {
ctx.clearRect(body.x[i]-r,body.y[i]-r,r*2,r*2);
}else {
ctx.clearRect(body.x[i],body.y[i],r*2,r*2);
}
}
}
//
function clearBody(){
for (var i = 0; i < body.x.length; i++) {
if (i == 0) {
ctx.clearRect(body.x[i]-r,body.y[i]-r,r*2,r*2);
}else {
ctx.clearRect(body.x[i],body.y[i],r*2,r*2);
}
}
}
//
function getRandomFromTwoNumber(start,end){
var result = Math.floor(Math.random()*(Math.abs(end-start)+1) + start);
return result;
}
//
function headMove(h,s){
ctx.beginPath();
ctx.fillStyle = '#0f0';
ctx.fillRect(body.x[1]=body.x[0]-r,body.y[1]=body.y[0]-r,r*2,r*2);
ctx.beginPath();
ctx.fillStyle = '#f00';
ctx.arc(body.x[0]=body.x[0]+h,body.y[0]=body.y[0]+s,r,0,2*Math.PI);
ctx.fill();
}
var orient = 1;
addEvent(document,'keydown',function(evt){
// console.log(evt.keyCode);
if (evt.keyCode == 'W'.charCodeAt() || evt.keyCode == 38) {
// move(0,-step);
orient = 4;
} else if (evt.keyCode == 'A'.charCodeAt() || evt.keyCode == 37) {
// move(-step,0);
orient = 3;
} else if (evt.keyCode == 'S'.charCodeAt() || evt.keyCode == 40) {
// move(0,step);
orient = 2;
} else if (evt.keyCode == 'D'.charCodeAt() || evt.keyCode == 39) {
// move(step,0);
orient = 1;
}
})
setInterval(function(){
switch (orient){
case 1:
move(step,0);
break;
case 2:
move(0,step);
break;
case 3:
move(-step,0);
break;
case 4:
move(0,-step);
break;
}
},speed);