<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇重构</title>
<style>
#mubu {
width: 400px;
height: 400px;
margin: 0 auto;
}
div{
width: 100px;
height: 70px;
margin: 0 auto;
}
#fuwei{
width: 100px;
height: 70px;
margin: 0 auto;
}
</style>
</head>
<body>
<div>分数为:<span id="fenshu" >-1</span>分</div>
<div id="mubu"><canvas id="can" width="400px" height="400px" style="background-color: black">对不起,您的浏览器不支持canvas</canvas></div>
<script>
var snake = [41, 40],
direction = 1,
food = 43,
n,
box = document.getElementById('can').getContext('2d');
function draw(seat, color) {
网页链接 = color;
box.fillRect(seat % 20 * 20 + 1, ~~(seat / 20) * 20 + 1, 18, 18);
}
网页链接 = 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 (snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || direction == 1 && n % 20 == 0 || direction == -1 && n % 20 == 19) {
return alert("GAME OVER!");
}
draw(n, "lime");
if (n == food) {
while (snake.indexOf(food = parseInt(Math.random() * 400)) > 0);
draw(food, "yellow");
document.getElementById("fenshu").innerHTML++;
} else {
draw(snake.pop(), "black");
}
setTimeout(argument