JavaScript to implement the web version of the snake game

JavaScript to implement the web version of the snake game

This article shares the specific code for JavaScript to implement the webpage snake game for your reference. The specific content is as follows

<!DOCTYPE html>
<html>
<head><title>Snake</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
var canv = document.getElementById("canvas");
var ctx = canv.getContext("2d");
var score=0;
//Define a block constructor var Block = function (col, row, size)
{
  this.col=col;
  this.row=row;
  this.size=size;
    };
//Define the prototype method draw of the Block function;
Block.prototype.draw = function()
{
  ctx.fillRect(this.col*this.size,this.row*this.size,this.size,this.size)
   }
//Define object snake var snake = {
  body:[
    new Block(20,20,10),
    new Block(20,21,10),
    new Block(20,22,10)
   ],
  direction:"right",
  };

//Define the function of drawing snake snake.draw=function()
{
   for(var i=0;i<this.body.length;i++)
  {
     this.body[i].draw();
        }
   };

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();
        }         
         };
//Create an apple object var apple={
    posX:Math.floor(Math.random()*40),
    posY:Math.floor(Math.random()*40),
    sizeR:5
}
//Draw apple function apple.draw=function()
{
  ctx.fillStyle="Green";
  ctx.beginPath();
  ctx.arc(this.posX*10+5,this.posY*10+5,5,0,Math.PI*2,false);
  ctx.fill();
  ctx.fillStyle="Black";
     };
//End var gameover = function()
{
  ctx.font="60px Comic Sans MS";
  ctx.textAlign="center";
  ctx.textBaseline="middle";
  ctx.fillText("GAME OVER!",200,200)
    };
// Timing function var intervalId = setInterval (function ()
{
   ctx.clearRect(0,0,400,400);
   ctx.font="20px Arial";
   ctx.fillText("Score:"+score,5,15);
   snake.draw();
   snake.move();
   apple.draw();
   ctx.strokeRect(0,0,400,400);
    },200);
//Snake key control $("body").keydown(function(event)
{
   console.log(event.keyCode);
    if(event.keyCode==37 &&snake.direction!="right")
     {
    snake.direction="left";
         }
    if(event.keyCode==38 &&snake.direction!="down")
     {
    snake.direction="up";
        }
    if(event.keyCode==39 &&snake.direction!="left")
     {
     snake.direction="right";
         }
     if(event.keyCode==40 &&snake.direction!="up")
     {
     snake.direction="down";
         }
              }
);
</script>
</body>
</html> 

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS implements the snake game
  • JavaScript to achieve the idea of ​​​​snake game
  • JavaScript implementation of classic snake game
  • Use js to write a simple snake game
  • JavaScript Snake Implementation Code
  • Implementing the Snake Game in JavaScript
  • Native js to realize a simple snake game
  • Writing Snake Game with Native JS
  • js to implement the snake game with comments
  • JavaScript exquisite snake implementation process

<<:  Detailed explanation of MySQL 30 military rules

>>:  Detailed tutorial on installing Ubuntu 19.10 on Raspberry Pi 4

Recommend

Node.js+express message board function implementation example

Table of contents Message Board Required librarie...

mysql: [ERROR] unknown option '--skip-grant-tables'

MySQL database reports ERROR 1045 (28000): Access...

8 ways to manually and automatically backup your MySQL database

As a popular open source database management syst...

How to use Nginx to proxy multiple application sites in Docker

Preface What is the role of an agent? - Multiple ...

Tutorial on using hyperlink tags in XHTML

Hyperlink, also called "link". Hyperlin...

CocosCreator Skeleton Animation Dragon Bones

CocosCreator version 2.3.4 Dragon bone animation ...

Detailed explanation of MySql installation and login

Check if MySQL is already installed in Linux sudo...

Sharing some wonderful uses of wxs files in WeChat applet

Table of contents Preface application Filters Dra...

How to recover files accidentally deleted by rm in Linux environment

Table of contents Preface Is there any hope after...

Concat() of combined fields in MySQL

Table of contents 1. Introduction 2. Main text 2....

Docker builds CMS on-demand system with player function

Table of contents text 1. Prepare the machine 2. ...