想实现一个允许经过蛇身的贪吃蛇代码,在下面的代码上进行更改
#介绍,该代码思路,划出从左到右,从上到下400个20x20格子,通过不断画蛇头和判断涂黑蛇尾模拟移动.
#现在的问题在于蛇头经过蛇身时该如何更改,应该需要在下面注释的代码那里更改,emm,个人尝试了好多次总是出现bug.
<canvas id="can" width="400" height="400" style="background-color: black;"></canvas>
<script>
var snake = [48, 47, 46, 45, 44, 43, 42, 41, 40],
direction = 1,
food = 49,
n,
nm = 0
box = document.getElementById('can').getContext('2d');
function randint(x, y) {
return parseInt(Math.random() * (x - y + 1) + y);
}
function draw(seat, color) {
box.fillStyle = color;
box.fillRect(seat % 20 * 20 + 1, ~~(seat / 20) * 20 + 1, 18, 18);
}
document.onkeydown = function(evt) {
direction = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(evt || event).keyCode - 37] || direction) ? direction : n;
};
! function() {
snake.unshift(n = snake[0] + direction);
if (n < 0 || n > 399 || direction == 1 && n % 20 == 0 || direction == -1 && n % 20 == 19) {
nm -= 1
return alert("GAME OVER!" + nm + "分");
}
draw(n, "lime");
if (n == food) {
while (snake.indexOf(food = randint(20, 380)) > 0);
draw(food, "yellow");
nm += 1
} else {
// var tem = snake[0];
// if (snake.indexOf(tem) <= 1) {
// draw(snake.pop(), "black")
// }
}
setTimeout(arguments.callee, 88);
}();
</script>