<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>贪吃蛇</title>
<style>
body 
{ display: flex; justify-content: center; align-items: center;}
</style>
</head>
<body>
<canvas>id="can"width="400"height="400"style="background-color: red">不支持canver</canvas>
<script type="text/javascript">
var snake=[200,199],direction = 1,food=201,n;
var box=document.getElementById('can').getContext('2d');function draw(seat,color){
box.fillStyle=color;
box.fillRect(seat%20*20+1,~~(seat/20)*20+1,18,18);}for(i=0;i<=399;i++)
{ draw(i,"black");}
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(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=~~(Math.random()*400))>0); draw(food,"yellow");}
else { draw(snake.pop(),"black");}setTimeout(arguments.callee,150); }();
</script>
</body>
</html>

解决方案 »

  1.   

    <!DOCTYPE html> <html>
    <head> <meta charset="utf-8">
    <title>贪吃蛇</title>
    <style>
    { display: flex; justify-content: center; align-items: center;}
    </style>
    </head> <body>
    <canvas>id="can"width="400"height="400"style="background-color: red">不支持canver</canvas>
    <script type="text/javascript">
    var snake=[200,199],direction = 1,food=201,n;
    var box=document.getElementById('can').getContext('2d');function draw(seat,color){
    box.fillStyle=color;
    box.fillRect(seat%20*20+1,~~(seat/20)*20+1,18,18);}for(i=0;i<=399;i++)
    { draw(i,"black");}
    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(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=~~(Math.random()*400))>0); draw(food,"yellow");}
    else { draw(snake.pop(),"black");}setTimeout(arguments.callee,150); }();
    </script>
    </body> </html>
    上面这个可以
      

  2.   

    这是原版
    https://bbs.csdn.net/topics/390988009你这个错误有
    <canvas后面多个>
    有两个分号写成中文的了";"
    if(n ==food)后面少个{