>  기사  >  웹 프론트엔드  >  JavaScript Snake 풀버전(소스코드)_javascript 스킬

JavaScript Snake 풀버전(소스코드)_javascript 스킬

WBOY
WBOY원래의
2016-05-16 17:10:111215검색

javascript Snake 정식 버전은 주석 처리가 완벽하고 객체 지향적입니다

코드 복사 코드는 다음과 같습니다.



Snake v2.4


<script><br> function $(id){return document.getElementById(id);}<br>/**************************************************** * **********<br>* javascript Snake v2.4 <br /><br>* v2.4는 뱀이 앞으로 나아갈 때 뱀 몸체의 색상이 움직이도록 수정합니다<br> * ************************************************* ** ***********/<br> //Greedy snakes <br> var Snake = {<br> tbl: null,<br> /**<br> * 몸체: 뱀 몸체, 뱀의 각 부분을 포함하는 배열, <br> * 데이터 구조 {x:x0, y:y0, color:color0}, <br> * x, y는 좌표, color는 색상을 나타냅니다. <br> **/<br> body: [],<br> //현재 이동 방향, 값 ​​0,1,2,3, 위쪽을 의미 , 오른쪽, 아래, 왼쪽 각각 키보드 방향키를 눌러 변경하세요. <br> 방향: 0,<br> : 250,<br> //일시중지 여부<br> 일시중지됨: true,<br> //행 수<br> rowCount: 30,<br> colCount: 30,<br> //초기화<br> init: function(){<br> var colors = ['red','orange',' 노란색','녹색','파란색','보라색','#ccc'];<br> this.tbl = $("main");<br> var x = 0;<br> var y = 0 ;<br> var colorIndex = 0;<br> //초기 이동 방향 생성<br> this .direction = Math.floor(Math.random()*4);<br>                                                          >       tbl.insertRow(-1);<br> for(var col=0;col<this.colCount;col ) {<BR> var td=tr.insertCell(-1);<BR> }<BR>         }<BR>            //产生20个松散节点<BR>            for(var i=0; i<10; i ){<BR>               x = Math.floor(Math.random()*this.colCount);<BR> y = Math.floor(Math.random()*this.rowCount);<BR>                colorIndex = Math.floor(Math.random()*7);<BR>               if(!this.isCellFilled(x,y)) {<BR>                   this.tbl.rows[y].cells[x].style.groundColor = colors[colorIndex];<BR>               }<BR>           }<BR>            //产生蛇头<BR>            동안(true){ <BR>               x = Math.floor(Math.random()*this.colCount);<BR>               y = Math.floor(Math.random()*this.rowCount);<BR>               if(!this.isCellFilled(!this.isCellFilled(!this.isCellFilled(!this.isCellFilled) x,y)){<BR>                   this.tbl.rows[y].cells[x].style.BackgroundColor = "black";<BR>                   this.body.push({x:x,y:y,color :'black'});<BR>                   break;<BR>                }<BR>           }<BR>           this.paused = true;<BR>            //添加键盘事件<BR>            document.onkeydown= function(e){<BR>               if (!e)e=window.event;<BR>                스위치(e.keyCode | e.어느 | e.charCode){<BR>                 사례 13: {<BR>                   if(Snake.paused){<BR>                    Snake.move();<BR>                      Snake.paused = false;<BR>                   }<BR>                   else{<BR>                      //如果没有暂停,则停止移动<BR>                    Snake.pause();<BR>                     Snake.paused = true;<BR>                    }<BR>                   break;<BR>                 }<BR>                사례 37:{//왼쪽<BR>                                                                                                                  break; <BR> Break; <BR>} <BR> case 38: {// up <BR> // Shinbar to play here <BR> if (event. ctrlkey) {<BR> Snake.speedup (-20) (-20) ;<BR> break;<BR> }<BR> if(Snake.direction==2){//뱀이 뒤로 걷는 것을 멈추세요<BR> break;<BR> }<BR> Snake.direction = 0;<BR> break;<BR> }<BR> 케이스 39:{//right<BR> break;<BR> }<BR> Snake.direction = 1;<BR> 휴식;<BR>                                                              if(event.ctrlKey){<BR>                                                            }<BR>                                                                                                             > 🎜> //이동<BR> move: function(){<BR> this .timer = setInterval(function(){<BR> Snake.erase();<BR> Snake .moveneStep (); <BR> Snake.paint (); <BR>}, this.speed); , <BR> // 몸체 이동 <BR> Moveonetep: Function () {<BR> if(this.checkNextStep()==-1){<BR>                                                  <BR> If(this.checkNextStep()== 1){<BR> var _point = this.getNextPos();<BR> var _x = _point.x;<BR> var _y = _point.y;<BR> var _color = this.getColor(_x,_y); <BR> this.body.unshift({x:_x,y:_y,color:_color});<BR> //음식을 먹어서 재생산된 음식<BR> this.generateDood();<BR> return ;<BR> }<BR> //window.status = this.toString();<BR> var point = this.getNextPos();<BR> //첫 번째 섹션의 색상 유지<BR> var color = this.body[0].color;<BR> i 효과<BR> this.body.pop();<BR> this.body.unshift({x:point.x,y:point.y,color:color });<BR> //window.status = this .toString();<BR> },<BR> //다음으로 갈 곳 탐색<BR> 일시 중지: function(){<BR> clearInterval(Snake.timer);<BR> this.paint();<BR> },<BR> getNextPos: function (){<BR> var x = this.body[0].x;<BR> var y = this.body[0].y;<BR> var color = this.body[0].color ;<BR>                                                                                                                                                                   else if(this.direction==1 ){<BR>                       > |                                    <BR> //체크는 다음 단계로 이동됩니다. if (x<0 || i ;//터치되면 자신의 몸으로 게임이 종료됩니다<BR>                                                                                  }<BR>                                                                                    ~ 이                                             ,<BR>        //绘蛇身<BR>        페인트: function(){<BR>            for(var i=0; i<this.body.length; i ){<BR>               this.paintDot(this.body[ i].x, this.body[i].y,this.body[i].color);<BR>            }<BR>        },<BR>        //擦除一节<BR>        erat: function(x ,y){<BR>            this.tbl.rows[y].cells[x].style.BackgroundColor = "";<BR>        },<BR>        PaintDot: 함수(x,y,color){<BR> this.tbl.rows[y].cells[x].style.BackgroundColor = color;<BR>        },<BR>        //得到一个坐标上的颜color<BR>        getColor: function(x,y){<BR>> ;<BR>            for(var i=0; i<this.body.length; i ){<BR>               str = "x:" this.body[i].x " y:" this.body[i]. y " color:" this.body[i].color " - ";<BR>            }<BR>            return str;<BR>        },<BR>        //检查一个坐标点有没有被填充<BR>        isCellFilled: function(x,y){<BR>            if(this.tbl.rows[y].cells[x].style.BackgroundColor == ""){<BR>               return false;<BR>           }<BR>            true 반환 ;<BR>        },<BR>        //중신형<BR>        restart: function(){<BR>            if(this.timer){<BR>              clear Interval(this.timer);<BR>            }<BR>           (var i=0; i<this.rowCount;i ){<BR>              this.tbl.deleteRow(0);<BR>           }<BR>           this.body = [];<BR>            this.init();<BR>            this.speed = 250;<BR>        },<BR>        //加速<BR>        speedUp: function(time){<BR>          if(!this.paused){<BR>            if(this.speed time<10||this. 속도 시간>2000){<BR>              return;<BR>            }<BR>            this.speed =time;<BR>           this.pause();<BR>            this.mo ve();<BR>          }<BR>        } ,<BR>        //생식동물。<BR>        generateDood: function(){<BR>          var colors = ['red','orange','yellow','green','blue','purple','#ccc'];<BR>        var x = Math.floor(Math.random()*this.colCount);<BR>            var y = Math.floor(Math.random()*this.rowCount);<BR>            var colorIndex = Math.floor(Math. 무작위()*7);<BR>            if(!this.isCellFilled(x,y)){<BR>               this.tbl.rows[y].cells[x].style.BackgroundColor = colors[colorIndex];<BR>           }<BR>        }<BR>    };<BR></script>

/**************************************************** * *********

* 자바스크립트 스네이크 v2.4

**************** * *********************************************/< ;br />

点左边按钮或按Enter开始/暂停游戏



点左边按钮或按Ctrl ↑加速

点左边按钮或按Ctrl ↓减速
<script><br>  $('btn').onclick = function(){<br>    if(Snake.paused){<br>      Snake.move();<br>      Snake.paused = false;<br>    }<br>    else{<br>      Snake.pause(); <br>      Snake.paused = true;<br>    }<br>  };<br>  $("reset").onclick = function(){<br>    Snake.restart();<br>    this.blur( );<br>  };<br>  $("upSpeed").onclick = function(){<br>    Snake.speedUp(-20);<br>  };<br>  $("downSpeed").onclick = function(){<br>    Snake.speedUp(20);<br>  };<br></script>


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.