Native js canvas to achieve a simple snake

Native js canvas to achieve a simple snake

This article shares the specific code of js canvas to implement a simple snake game for your reference. The specific content is as follows

Js native snake: canvas

HTML

<canvas id="can"></canvas>

CSS

#can{
 background: #000000;
 height: 400px;
 width: 850px;
}

JS

//Public section var blockSize = 10;
//Height and width of the map var mapW = 300;
var mapH = 150;
//historical food var
var historyfood = new Array();
//food array var img = new Image()
var arrFood = ["ananas.png","hamburg.png","watermelon.png"]
historyfood = [{x: 0,y:0}];
//Default value of Greedy Snake var snake = [{x:3,y:0},{x:2,y:0},{x:1,y:0}]

//Snake direction var directionX = 1;
var directionY = 0;
//Add a flag to mark whether the food has been eaten //Default value: not eaten var isFood = false;
//Judge the game status //Default game continues var gameState = false;

//Limit the direction of movement of the snake to not be reversed var lockleft = true;
var lockright = true;
var lockup = true;
var lockdown = true;

//Snake score var count = 0;
//Snake speed var speed = 1000 - (count + 5);
$(function () {
 $("#divContainer").height($("#can").height());
 //1, get the canvas object var can = document.getElementById("can");
 //2, get the drawing toolbox var tools = can.getContext('2d');
 tools.beginPath();
 //Set food default values ​​var XY = Randomfood();
 console.log(XY);
 var x1 = Randomfood().x;
 var y1 = Randomfood().y;
 img.src = "/aimless/img/GluttonousSnakeFood/" + arrFood[Math.floor(Math.random() * arrFood.length)];
 //Control the movement of the snake document.addEventListener('keydown',function (e){
  switch (e.keyCode) {
   case 38:
    if (lockup){
     directionX = 0;
     directionY = -1;
     lockdown = false;
     lockleft = true;
     lockright = true;
    }
    break;
   case 40:
    if (lockdown){
     directionX = 0;
     directionY = 1;
     lockup = false;
     lockleft = true;
     lockright = true;
    }
    break;
   case 37:
    if (lockleft){
     directionX = - 1;
     directionY = 0;
     lockright = false;
     lockup = true;
     lockdown = true;
    }
    break;
   case 39:
    if (lockright){
     directionX = 1;
     directionY = 0;
     lockleft = false;
     lockup = true;
     lockdown = true;
    }
    break;
  }
 })
 setIntervalSnake(tools,x1,y1);
 //4, find the location})


function setIntervalSnake(tools,x1,y1){
 setInterval(function (){
  if (gameState){
   return;
  }
  //1, erase the drawing boardtools.clearRect(0,0,850,420);
  var oldHead = snake[0];

  if (oldHead.x < 0 || oldHead.y < 0 || oldHead.x * blockSize >= mapW || oldHead.y * blockSize >= mapH){
   gameState = true;
   alert("Game over");
  }else {
   //Snake moves if (snake[0].x * blockSize === x1 && snake[0].y * blockSize === y1){
    isFood = true;
   } else {
    snake.pop()
   }
   var newHead = {
    x: oldHead.x + directionX,
    y: oldHead.y + directionY
   }
   snake.unshift(newHead);
  }
  //2, determine whether the food has been eaten, refresh if eaten, do not refresh if not eaten if (isFood) {
   count = count + 1;
   $("#count").html(count);
   x1 = Randomfood().x;
   y1 = Randomfood().y;
   img.src = "/aimless/img/GluttonousSnakeFood/" + arrFood[Math.floor(Math.random() * arrFood.length)];
   isFood = false;
  }
  tools.drawImage(img,x1,y1,blockSize,blockSize);
  //Snake body array var Thesnakebody = new Array();
  //3, draw snake for (var i = 0; i < snake.length; i++){
   if (i == 0){
    tools.fillStyle = "#9933CC";
   } else {
    var newHead1 = {
     x: snake[i].x,
     y: snake[i].y
    }
    Thesnakebody.unshift(newHead1);
    tools.fillStyle = "#33adcc";
   }
   tools.fillRect(snake[i].x * blockSize,snake[i].y * blockSize,blockSize,blockSize);
  }
  // //Judge whether the snake head has bitten the snake body Thesnakebody.forEach(item=>{
   if(item.x == snake[0].x && item.y == snake[0].y){
    gameState = true;
    setIntervalSnake(tools,x1,y1);
   }
  })
  //4, draw the map var width = Math.round($("#can").width() / blockSize);
  var height = Math.round($("#can").height() / blockSize);
  for (var i = 1; i < width; i++){
   tools.moveTo(0,blockSize * i);
   tools.lineTo($("#can").width(),blockSize * i);
  }
  for (var i = 1; i < height; i++){
   tools.moveTo(blockSize * i,0);
   tools.lineTo(blockSize * i,$("#can").height());
  }
  tools.strokeStyle = "#FFFFFF";
  //5, draw tools.stroke();
 },speed / 3);
}


//Random food function Randomfood() {
 var RandomX = Math.floor(Math.random() * mapW / blockSize) * blockSize;
 var RandomY = Math.floor(Math.random() * mapH / blockSize) * blockSize;
 setInterval(function (){
  snake.forEach(item=>{
   console.log(RandomX/blockSize, RandomY/blockSize);
   // console.log(item.x,item.y);
   if (item.x == RandomX / blockSize && item.y == RandomY / blockSize) {
    return Randomfood();
   } else {
    return ;
   }
  })
 }, 10 / 3);
 var newRandom = {
  x: RandomX,
  y: RandomY
 }
 return newRandom;
}

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:
  • Snake game written in JS (personal practice)
  • JavaScript Snake full version (source code)
  • js to realize the snake game (easy to understand)
  • A complete example of the snake game implemented in JS
  • Snake game implemented with 20 lines of js code
  • js to write a small game of greedy snake
  • js snake game implementation ideas and source code
  • javascript snake implementation code
  • JavaScript to achieve a simple snake game
  • A complete example of the web version of the snake game implemented in native js

<<:  Solve the problem that the service cannot be started when installing the decompressed version of mysql 5.7.18 winx64 on Win7 x64

>>:  Tutorial diagram of installing zabbix2.4 under centos6.5

Recommend

Example of how to change the line spacing of HTML table

When using HTML tables, we sometimes need to chan...

Detailed explanation of Vue advanced construction properties

Table of contents 1. Directive custom directive 2...

Browser compatibility summary of common CSS properties (recommended)

Why do we need to summarize the browser compatibi...

Vue uses mixins to optimize components

Table of contents Mixins implementation Hook func...

Centos7 mysql database installation and configuration tutorial

1. System environment The system version after yu...

Example code for drawing double arrows in CSS common styles

1. Multiple calls to single arrow Once a single a...

Practice of realizing Echarts chart width and height adaptation in Vue

Table of contents 1. Install and import 2. Define...

How to check where the metadata lock is blocked in MySQL

How to check where the metadata lock is blocked i...

Overview of the basic components of HTML web pages

<br />The information on web pages is mainly...

Css3 realizes seamless scrolling and anti-shake

question The seamless scrolling of pictures and t...

27 Linux document editing commands worth collecting

Linux col command The Linux col command is used t...

Detailed explanation of Angular component life cycle (I)

Table of contents Overview 1. Hook calling order ...

Detailed explanation of three ways to set borders in HTML

Three ways to set borders in HTML border-width: 1...

Trash-Cli: Command-line Recycle Bin Tool on Linux

I believe everyone is familiar with the trashcan,...