Javascript snake full version of the source code

  • 2020-03-30 00:46:45
  • OfStack

Javascript snake full version full comments, object-oriented

<html>
<head>
    <title> snake  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 snake  v2.4 <br />
* v2.4 Fixed a bug where snake body colors could move with the snake 
**************************************************************/
    //Greedy snake
    var Snake = {
        tbl: null,
        
        body: [],
        //The current direction of movement is 0,1,2,3, which means up, right, down and left respectively. Press the keyboard direction key to change it
        direction: 0,
        //The timer
        timer: null,
        // speed 
        speed: 250,
        //Has it been suspended
        paused: true,
        // The number of rows 
        rowCount: 30,
        // The number of columns 
        colCount: 30,
        //Initialize the
        init: function(){
            var colors = ['red','orange','yellow','green','blue','purple','#ccc'];
            this.tbl = $("main");
            var x = 0;
            var y = 0;
            var colorIndex = 0;
            //Produces the initial direction of movement
            this.direction = Math.floor(Math.random()*4);
            //Construct a 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);
                }
            }
            //Generates 20 loose nodes
            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];
                }
            }
            //Produce the snake
            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;
            //Add keyboard events
            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{
                       //If there is no pause, stop moving
                      Snake.pause();
                      Snake.paused = true;
                    }
                    break;
                  }
                    case 37:{//left
                        //Stop the snake from walking backwards
                        if(Snake.direction==1){
                            break;
                        }
                        Snake.direction = 3;
                        break;
                    }
                    case 38:{//up
                       //The shortcut key works here
                      if(event.ctrlKey){
                         Snake.speedUp(-20);
                        break;
                      }
                        if(Snake.direction==2){//Stop the snake from walking backwards
                            break;
                        }
                        Snake.direction = 0;
                        break;
                    }
                    case 39:{//right
                        if(Snake.direction==3){//Stop the snake from walking backwards
                            break;
                        }
                        Snake.direction = 1;
                        break;
                    }
                    case 40:{//down
                      if(event.ctrlKey){
                         Snake.speedUp(20);
                        break;
                      }
                        if(Snake.direction==0){//Stop the snake from walking backwards
                            break;
                        }
                        Snake.direction = 2;
                        break;
                    }
                }
            }
        },
        // mobile 
        move: function(){
            this.timer = setInterval(function(){
                Snake.erase();
                Snake.moveOneStep();
                Snake.paint();
            }, this.speed);
        },
        //Move a body segment
        moveOneStep: function(){
            if(this.checkNextStep()==-1){
                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 one food is eaten, another food is produced
                this.generateDood();
                return;
            }
            //window.status = this.toString();
            var point = this.getNextPos();
            //Keep the color of the first section
            var color = this.body[0].color;
            //The color moves forward
            for(var i=0; i<this.body.length-1; i++){
              this.body[i].color = this.body[i+1].color;
            }
            //Snake tail minus a section, snake tail plus a section, to show the snake forward effect
            this.body.pop();
            this.body.unshift({x:point.x,y:point.y,color:color});
            //window.status = this.toString();
        },
        //Where will the search take you next
        pause: function(){
          clearInterval(Snake.timer);
          this.paint();
        },
        getNextPos: function(){
            var x = this.body[0].x;
            var y = this.body[0].y;
            var color = this.body[0].color;
            // upward 
            if(this.direction==0){
                y--;
            }
            // To the right 
            else if(this.direction==1){
                x++;
            }
            // down 
            else if(this.direction==2){
                y++;
            }
            // To the left 
            else{
                x--;
            }
            //Return a coordinate
            return {x:x,y:y};
        },
        //Check what is the next step to move to
        checkNextStep: function(){
            var point = this.getNextPos();
            var x = point.x;
            var y = point.y;
            if(x<0||x>=this.colCount||y<0||y>=this.rowCount){
                return -1;//Touch the boundary, game over
            }
            for(var i=0; i<this.body.length; i++){
                if(this.body[i].x==x&&this.body[i].y==y){
                    return -1;//Touch your body, game over
                }
            }
            if(this.isCellFilled(x,y)){
                return 1;//There is something
            }
            return 0;// clearing 
        },
        //Erase the snake
        erase: function(){
            for(var i=0; i<this.body.length; i++){
                this.eraseDot(this.body[i].x, this.body[i].y);
            }
        },
        //Draw a snake body
        paint: function(){
            for(var i=0; i<this.body.length; i++){
                this.paintDot(this.body[i].x, this.body[i].y,this.body[i].color);
            }
        },
        //Erase the section
        eraseDot: function(x,y){
            this.tbl.rows[y].cells[x].style.backgroundColor = "";
        },
        paintDot: function(x,y,color){
            this.tbl.rows[y].cells[x].style.backgroundColor = color;
        },
        //I get a color in coordinates
        getColor: function(x,y){
            return this.tbl.rows[y].cells[x].style.backgroundColor;
        },
        //Used for debugging
        toString: function(){
            var str = "";
            for(var i=0; i<this.body.length; i++){
                str += "x:" + this.body[i].x + " y:" + this.body[i].y + " color:" + this.body[i].color + " - ";
            }
            return str;
        },
        //Check if a coordinate point is filled
        isCellFilled: function(x,y){
            if(this.tbl.rows[y].cells[x].style.backgroundColor == ""){
                return false;
            }
            return true;
        },
        //Start all over again
        restart: function(){
            if(this.timer){
                clearInterval(this.timer);
            }
            for(var i=0; i<this.rowCount;i++){
              this.tbl.deleteRow(0);
            }
            this.body = [];
            this.init();
            this.speed = 250;
        },
        // To speed up 
        speedUp: function(time){
          if(!this.paused){
            if(this.speed+time<10||this.speed+time>2000){
              return;
            }
            this.speed +=time;
            this.pause();
            this.move();
          }
        },
        //Produce food.
        generateDood: function(){
          var colors = ['red','orange','yellow','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)){
                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 / suspended " /> Click or press the left button Enter start / Pause the game <br />
<input type="button" id="reset" value="Start all over again" /><br />
<input type="button" id="upSpeed" value=" To speed up " /> Click or press the left button Ctrl +  Write to accelerate <br />
<input type="button" id="downSpeed" value=" Slow down " /> Click or press the left button Ctrl +  Left to slow down 
<script>
  $('btn').onclick = function(){
    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(20);
  };
</script>
</body>
</html>

Related articles: