Today teach you how to use JS to write a web version of the snake.
The specific effects are as follows:
var Block=function(col,row,size) { this.col=col; this.row=row; this.size=size; }; // Define Block function prototype method draw; Block.prototype.draw =function() { ctx.fillRect(this.col*this.size,this.row*this.size,this.size,this.size) }Copy the code
I’m going to start with the basic definition, which is to define a square, which is actually the part of the snake. I need to draw the square, fill it.
Var snake ={body:[new Block(20,20,10), new Block(20,21,10), new Block(20,22,10)], direction:"right",}; Draw =function() {for(var I =0; i<this.body.length; i++) { this.body[i].draw(); }};Copy the code
Then there is the definition of the snake, where the initial body of the snake is composed of three parts, so there are three blocks.
snake.move = function() { var head = this.body[0]; if(snake.direction=="right") { var newhead=new Block(head.col+1,head.row,head.size) } if(snake.direction =="left") { var newhead = new Block(head.col-1,head.row,head.size); } if(snake.direction=="up") { var newhead=new Block(head.col,head.row-1,head.size) } if(snake.direction=="down") { var newhead=new Block(head.col,head.row+1,head.size) } if(newhead.col<0 || newhead.col>39 ) { clearInterval(intervalId); gameover(); } if(newhead.row<0 || newhead.row>39 ) { clearInterval(intervalId); gameover(); } for(var i=0; i<this.body.length; i++) { if(this.body[i].col==newhead.col &&this.body[i].row==newhead.row) { clearInterval(intervalId); gameover(); } } this.body.unshift(newhead); if(newhead.col==apple.posX &&newhead.row==apple.posY) { score=score+100; while(true) { var checkApple =false; apple.posX=Math.floor(Math.random()*40); apple.posY=Math.floor(Math.random()*40); for(var i=0; i<this.body.length; i++) { if(this.body[i].col==apple.posX &&this.body[i].row==apple.posY) checkApple=true; } if(! checkApple) break; } } else{ this.body.pop(); }};Copy the code
And then this part is the core, which defines the movement of the snake up and down and left and right, and the refreshment of the food. After the snake eats the food.
The complete core code, as shown above, is not as difficult as it might seem. You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.