这篇文章主要是对javascript贪吃蛇完整版(源码)进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
javascript贪吃蛇完整版 注释完整,面向对象 代码如下: <html> <head> <title>贪吃蛇 Snake v2.4</title> <style> body{ font-size:9pt; } table{ border-collapse: collapse; border:solid #333 1px; } td{ height: 10px; width: 10px; font-size: 0px; } .filled{ background-color:blue; } </style> </head> <script> function $(id){return document.getElementById(id);} /************************************************************** * javascript贪吃蛇 v2.4 <br /> * v2.4修正了蛇身颜色可以随着蛇前进而移动 **************************************************************/ //贪吃蛇类 var Snake = { tbl: null, /** * body: 蛇身,数组放蛇的每一节, * 数据结构{x:x0, y:y0, color:color0}, * x,y表示坐标,color表示颜色 **/ body: [], //当前移动的方向,取值0,1,2,3, 分别表示向上,右,下,左, 按键盘方向键可以改变它 direction: 0, //定时器 timer: null, //速度 speed: 250, //是否已经暂停 paused: true, //行数 rowCount: 30, //列数 colCount: 30, //初始化 init: function(){ var colors = ['red','orange','yellow','green','blue','purple','#ccc']; this.tbl = $("main"); var x = 0; var y = 0; var colorIndex = 0; //产生初始移动方向 this.direction = Math.floor(Math.random()*4); //构造table for(var row=0;row<this.rowCount;row++){ var tr=this.tbl.insertRow(-1); for(var col=0;col<this.colCount;col++) { var td=tr.insertCell(-1); } } //产生20个松散节点 for(var i=0; i<10; i++){ x = Math.floor(Math.random()*this.colCount); y = Math.floor(Math.random()*this.rowCount); colorIndex = Math.floor(Math.random()*7); if(!this.isCellFilled(x,y)){ this.tbl.rows[y].cells[x].style.backgroundColor = colors[colorIndex]; } } //产生蛇头 while(true){ x = Math.floor(Math.random()*this.colCount); y = Math.floor(Math.random()*this.rowCount); if(!this.isCellFilled(x,y)){ this.tbl.rows[y].cells[x].style.backgroundColor = "black"; this.body.push({x:x,y:y,color:'black'}); break; } } this.paused = true; //添加键盘事件 document.onkeydown= function(e){ if (!e)e=window.event; switch(e.keyCode | e.which | e.charCode){ case 13: { if(Snake.paused){ Snake.move(); Snake.paused = false; } else{ //如果没有暂停,则停止移动 Snake.pause(); Snake.paused = true; } break; } case 37:{//left //阻止蛇倒退走 if(Snake.direction==1){ break; } Snake.direction = 3; break; } case 38:{//up //快捷键在这里起作用 if(event.ctrlKey){ Snake.speedUp(-20); break; } if(Snake.direction==2){//阻止蛇倒退走 break; } Snake.direction = 0; brea