JavaScript greedy Snake full version

Source: Internet
Author: User
Tags getcolor reset rowcount javascript snake

  This article is mainly on the JavaScript full version of the snake (source code) for a detailed analysis of the introduction, the need for friends can come to the reference, I hope to help you.

JavaScript greedy full version annotation complete, object-oriented code as follows: <html> <head>     <title> Snake v2.4</title> <s tyle>     body{        font-size:9pt         table{        Border-collapse:collapse;         Border:solid #333 1px;    }     td{        height:10px;         width:10px &nbsp ;       font-size:0px;    }    . filled{        background-color:blue    , </style> & lt;/head> <script>     function $ (ID) {return document.getElementById (ID);}/********************** * JavaScript greedy snake v2.4 <br/> * v2.4 fixed snake body color can move along with the snake ******************* /   //greedy snake     var Snake = {        Tbl:null,        /**         * Body: snakes, array of snake each section,         * Data structure {x:x0, y:y0, Color:c OLOR0},         * x,y for coordinates, color = color       **/        Body: [],        //current moving direction, value 0,1,2,3, respectively, indicating up, right, down, left, press the keyboard direction key can change it         direction:0, & nbsp      //timer         Timer:null,        /speed         speed:250        //have been paused         Paused:true,       &NB Sp Number of rows         rowcount:30,        //List of         COLCOUNT:30,        //init         init:function () {            var colors = [' red ', ' orange ', ' yellow ', ' green ', ' blue ', ' purple ', ' #ccc '];             THIS.TBL = $ ("main"); &nbsp           var x = 0;             var y = 0;             var colorindex = 0;            //Generate initial move direction             this.direction = Math.floor (Math.random () *4);            //Construction table             for (Var row=0;row<this.ro wcount;row++) {                var tr=this.tbl.insertrow ( -1);                 for (Var col=0;col<this.colcount;col++) {                    var Td=tr.insertcell (-1);                            }            //generating 20 loose nodes             for (var i=0 i<10; i++) {    &nbs P       &NBSP   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)) {          &N Bsp         This.tbl.rows[y].cells[x].style.backgroundcolor = Colors[colorindex];                            }            //produce snake head             while (true) {          &NB Sp     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;            //Add keyboard event             document.onkeydown= function ( e) {                if (!e) e=window.event,           &NBS P     switch (e.keycode | e.which | e.charcode) {                  CAS E: {                    if (snake.paused) {      &NBSP ;               Snake. Move ();                       snake.paused = false;                                   & nbsp     else{                       //stop moving if not paused &nbs P                     snake.pause ();                       snake.paused = true;                                   & nbsp     break;                   {                & nbsp   Case 37:{//left                        //stop Snake from going backwards                        if (snake.direction==1) {                            break;                                   & nbsp             snake.direction = 3;                         break;                                   & nbsp     Case 38:{//up                        //shortcut key works here                       if (Event.ctrlkey) {      &NBS P                  snake.speedup (-20);                         break;                                               if (snake.direction==2) {//Prevent Snake from going backwards                             break;                                   & nbsp             snake.direction = 0;                         break;                                   & nbsp     Case 39:{//right                         if (Snak e.direction==3) {//Prevent Snake from going backwards                             Break                 &NBsp      }                         Snake.direction = 1;                         break;                                   & nbsp     Case 40:{//down                       if (Event.ctrlke Y) {                         snake.speedup   &N Bsp                     break;                                   & nbsp           if (snake.direction==0) {//stop Snake from going back to                             break;       &nbsp                                   & nbsp     snake.direction = 2;                         break;                                   & nbsp {           }        },        //Mobile   &NBSP ;     Move:function () {            This.timer = setinterval (function () {  &nbs P             snake.erase ();                 snake.moveonestep ();                 snake.paint ();            }, This.speed);        },        //Moving a section of the body         moveOnestep:function () {            if (This.checknextstep () ==-1) {        & nbsp       clearinterval (This.timer);                 alert ("Game over!/npress restart to continue.");                 return;                         if (This.checknextstep () ==1) {                var _point = This.getnextpos ();                 var _x = _point.x;                 var _y = _point.y;                 var _color = This.getcolor (_x,_y);                 This.body.unshift ({x:_x,y:_y,color:_color});                //Because eat a food, so again produce a food                 This.generatedood ();                 return;                        //window.status = this.tostring ();             var point = This.getnextpos ();            //Preserve the first section of the color             var color = this.body[0].co Lor            //color forward-move             for (Var i=0 i<this.body.l Ength-1; i++) {              This.body[i].color = this.body[i+1].color       &NB Sp    }            //Snake tail minus one section, Snake Tail plus one, showing snake forward effect           &NBSP ; This.body.pop ();             This.body.unshift ({x:point.x,y:point.y,color:color});            //window.status = this.tostring ();       },        //Explore what to do next where         pause:function () {& nbsp         clearinterval (Snake.timer);           this.paint ();        },         getnextpos:function () {          &NBS P var x = this.body[0].x;             var y = this.body[0].y;             var color = This.body[0].color;            //up             if (this.direction==0) {  &NB Sp             y--;                        //Right         &NB Sp   Else if (this.direction==1) {                x + + &nbsp       ;    }           &NBSP Down             ELSE if (this.direction==2) {            &NBSP ;   y++;                        //left         &NB Sp   else{                x--           } &nbs P          //back to a coordinate             return {x:x,y:y};        },        //Check what the next step to move to is         Checknextstep:fun Ction () {            var point = This.getnextpos ();           &NBSP ; var x = point.x;             var y = point.y;             if (x<0| | x>=this.colcount| | y<0| | Y>=this.rowcount) {              return-1;//touch boundary, game over &NBSp           {            for (var i=0 i<this.body.length; i++) {& nbsp               if (this.body[i].x==x&&this.body[i].y==y) {      & nbsp             return-1;//encounter their body, game end                                         if (this.iscellfilled (x,y)) {&nbsp ;               return 1;//have something            }             return 0;//open space        },        //Erase snake body         Erase:function () {            for (var i=0 i<this.body.length; i++) {&nbsp ;               This.erasedot (this.body[i].x, THIS.BODY[I].Y);         &NBSp          },        //Draw snake body       paint:function () {             for (var i=0 i<this.body.length; i++) {          &NB Sp     This.paintdot (this.body[i].x, This.body[i].y,this.body[i].color);             {       },        //Erase a section of   &NBSP ;     Erasedot:function (x,y) {            THIS.TBL.ROWS[Y].CELLS[X]. Style.backgroundcolor = "";        },         Paintdot:function (x,y,color) {        &NBS P   This.tbl.rows[y].cells[x].style.backgroundcolor = color;        },        //Get a color of coordinates         Getcolor:function (x,y ) {            return This.tbl.rows[y].cells[x].style.backgroundcoloR        },        //For debugging         tostring:function () {            var str = "";             for (var i=0 i<this.body.length; i++) {          &NB Sp     STR + + "x:" + this.body[i].x + "y:" + this.body[i].y + "color:" + This.body[i].color + "-";                         return str;        },        /check if a coordinate point has not been filled in         ISCELLFILLED:FUNCT Ion (X,y) {            if (This.tbl.rows[y].cells[x].style.backgroundcolor = "") {  &NB Sp             return false;                         return true;        },        //re-start       &NBsp Restart:function () {            if (This.timer) {            & nbsp   Clearinterval (This.timer);                         for (var i=0 i<this.rowcount;i++) {              This.tbl.deleteRow (0);             &NBS P           this.body = [];             this.init ();             this.speed = 250;        },        //accelerated         Speedup:function (time) {&nbsp ;         if (!this.paused) {            if (this.speed+time<10| | this.speed+time>2000) {              return           &NBS P }             This.speed =Time             this.pause ();             this.move ();           {       },        //produce food.         generatedood:function () {          var colors = [' red ', ' orange ', ' Yel Low ', ' green ', ' blue ', ' purple ', ' #ccc '];         var x = Math.floor (Math.random () *this.colcount);             var y = Math.floor (Math.random () *this.rowcount);             var ColorIndex = Math.floor (Math.random () *7);             if (!this.iscellfilled (x,y)) {              &N Bsp This.tbl.rows[y].cells[x].style.backgroundcolor = Colors[colorindex];            }         {   }; </script> <body onload= "Snake.init ();" >/**********************<br/> * JavaScript snake v2.4<br/> ******************************* /<br/> <table id= "main" border= "1" cellspacing= "0" cellpadding= "0" ></ table> <input type= "button" id= "BTN" value= "Start/pause"/> Point left button or press ENTER to start/pause game <br/> <input type= "button" id= "Reset" value= "restart"/><br/> <input type= "button" id= "Upspeed" value= "acceleration"/> The left button or press CTRL +↑ to accelerate <BR/& Gt <input type= "button" id= "Downspeed" value= "deceleration"/> point left button or press CTRL +↓ deceleration <script>   $ (' btn '). onclick = Functio N () {    if (snake.paused) {      snake.move ();       snake.paused = false;         else{      Snake.pause ()       snake.paused = true;    }  };   $ ("reset"). onclick = function () {    snake.restart ();     This.blur ();  };   $ ("Upspeed"). onclick = function () {     Snake.speedup (-20);  };   $ ("Downspeed"). onclick = function () {    snake.speedup ();  }; </script> </body> </html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.