<!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>
uj5u.com熱心網友回復:
<!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>
上面這個可以
uj5u.com熱心網友回復:
有什么區別?看不出來┐(─__─)┌
uj5u.com熱心網友回復:
第8行 有問題少了應該闊號
uj5u.com熱心網友回復:
這是原版https://bbs.csdn.net/topics/390988009
你這個錯誤有
<canvas后面多個>
有兩個分號寫成中文的了";"
if(n ==food)后面少個{
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/129812.html
標籤:JavaScript
