- ·上一篇文章:同一个页面使用多个不同的jQuery版本冲突的解决方法
- ·下一篇文章:用js得到当前页面的url相关信息方法(JS获取当前域名信息)
当前位置:K88软件开发 → 文章中心 → 编程语言 → JavaScript → JS01 → 文章内容
js游戏:20行代码搞定的贪吃蛇游戏
<
canvas id="can" width="400" height="400" style="background:Black">
<
/canvas>
<
script>
var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d")
function draw(t,c)
{
 
 
ctx.fillStyle=c
 
 
ctx.fillRect(t%20*20+1,~~(t/20)*20+1,18,18)
}
document.onkeydown=function(e)
{fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n}
!function()
{
 
 
sn.unshift(n=sn[0]+fx)
 
 
if(sn.indexOf(n,1)>
0 || n<
0||n>
399||fx==1&
&
n%20==0||fx==-1&
&
n%20==19) return alert("GAME OVER")
 
 
draw(n,"Lime")
 
 
if(n==dz)
{
 
 
 
 
while(sn.indexOf(dz=~~(Math.random()*400))>
=0)
 
 
 
 
draw(dz,"Yellow")
 
 
}else
 
 
 
 
draw(sn.pop(),"Black")
 
 
setTimeout(arguments.callee,130)
}()
<
/script>
这是高手写的js贪吃蛇游戏,把它保存为.html文件后,打开就可以玩了。
canvas id="can" width="400" height="400" style="background:Black">
<
/canvas>
<
script>
var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d")
function draw(t,c)
{
 
 
ctx.fillStyle=c
 
 
ctx.fillRect(t%20*20+1,~~(t/20)*20+1,18,18)
}
document.onkeydown=function(e)
{fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n}
!function()
{
 
 
sn.unshift(n=sn[0]+fx)
 
 
if(sn.indexOf(n,1)>
0 || n<
0||n>
399||fx==1&
&
n%20==0||fx==-1&
&
n%20==19) return alert("GAME OVER")
 
 
draw(n,"Lime")
 
 
if(n==dz)
{
 
 
 
 
while(sn.indexOf(dz=~~(Math.random()*400))>
=0)
 
 
 
 
draw(dz,"Yellow")
 
 
}else
 
 
 
 
draw(sn.pop(),"Black")
 
 
setTimeout(arguments.callee,130)
}()
<
/script>
这是高手写的js贪吃蛇游戏,把它保存为.html文件后,打开就可以玩了。
js游戏:20行代码搞定的贪吃蛇游戏