Make Snake Game Using Html, CSS, and JavaScript (With Code)

1
Make Snake Game Using Html, CSS, and JavaScript (With Code)
Do you want to make a snake game using only HTML, CSS, and javascript programming code?

If your answer is yes, I will fully assist you in this article. In this article, I will tell you how to make a great and professional game using simple program code. JavaScript programming language is mainly used for making any game. Exactly the same way I used JavaScript programming code to make this game and also used some amount of HTML and some amount of CSS. Keeping in mind the new programmers, I have tried to make the ones used here as simple and simple as possible. 
Hopefully, from this article, you can learn JavaScript programming language better. And learn how to make a professional game.

Some special information about this snake game

💢 This game is made using JavaScript programming language and some amount of HTML and CSS code. Which is very simple and simple.
💢 The main feature of this game is that you can play this game with the mouse. That means you can't use the keyboard in this case.
💢 Here are all the features of a snake game.
💢 In this case, there is a rectangular box. In that box, a snake wanders around and tries to eat the food. The length of the snake will increase as you eat the food.
💢 The dishes have been colored green so that they look very nice on a black background. In this game, like any other game, you will be knocked out of the game when you hit that square box.
💢 Each meal has a specific point. The sooner you can eat those foods, the more points you will get. You get out of this game when you hit the wall. Then a pop-up box will open.

 All in all, it is a beautiful and professional snake game. Hope you are particularly interested in making this game.
How to make this snake game


How to make this snake game

Below I have shown how I made this game using simple programming code. You follow the following three methods.

First of all, you create an HTML and a CSS file. To create HTML files, you need to open any text editor on your computer, such as Notepad. Then copy the programming code below and paste it into that editor. Then you save that file. When saving, rename it as you like and save it by adding dot HTML.

<html>
<head>
    <style>
         Add Css Code
    </style>
</head>
<body>
         Add HTML Code 
      <script>
              Add JavaScript Code
      </script>
      
</body>
</html>

 Similarly, you create a CSS file. To create a CSS file, open Notepad and save it with that file without typing anything. When saving you add the rename of your choice and save it by adding dot CSS to it.

 Of course, you must attach the CSS file to the HTML file. Then you paste the following three codes such as HTML code, CSS code, and JavaScript programming code into your HTML and CSS file.


ADD HTML CODE (<body> Add Code </body>)

The following codes are HTML codes. This project uses a small amount of HTML code. You copy these codes and paste the above structure in the place where the HTML is written here.


<canvas height="512" width="512" id="gameCanvas"> </canvas>


ADD CSS CODE (<head><style> Add code </style></head>)

The codes given below are CSS codes. Basically, a small amount of CSS code has been used in this game. Copy the following codes and paste them into your created CSS file. Then save the file. Make sure you attach your CSS file to the HTML file.


 htmlbody {
  height100%;
}

body {
  display: -webkit-box;
  displayflex;
  -webkit-box-packcenter;
          justify-contentcenter;
  -webkit-box-aligncenter;
          align-itemscenter;
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
canvas {
  backgroundblack;
  font-size2vw;
  box-shadow1em 1em 0.5em rgba(0000.25);
  outline1px solid white;
  outline-offset-2px;
}


ADD JAVASCRIPT CODE (<body><script> Add code</script></body>)

The code shown below is a JavaScript programming code. Which has been used the most to make this snake game. You copy the code below and then paste it in the upper structure where the ad javascript is written.


var cnv = document.getElementById('gameCanvas'),
    ctx = cnv.getContext('2d'),
    
    segmentLength = 10,
    startingSegments = 20,
    spawn = { x: 0y:cnv.height/2 },
    snakeSpeed = 5,
    maxApples = 5,
    appleLife = 500,
    segmentsPerApple = 3,
    /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    snakeWidth = 5,
    appleWidth = 5,
    cursorSize = 10,
    
    snakeColor =     [ 1002551001],
    appleColor =     [   0255,   01],
    cursorColor =    [ 2552552551],
    cursorColorMod = [   0,-255,-2550],
    targetColor =    [   0,   02551],
    targetColorMod = [ 255,   0,-2550],
    scoreColor =     [ 2552552551],
    /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    cursorSpin = 0.075,
    
    snake,
    cursor,
    target,
    apples,
    score,
    gameState,
    deathMeans;

function distance(p1,p2){
  var dx = p2.x-p1.x;
  var dy = p2.y-p1.y;
  /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  return Math.sqrt(dx*dx + dy*dy);
}

function lineIntersect(p0_xp0_yp1_xp1_yp2_xp2_yp3_xp3_y) {
  var  s1_x = p1_x - p0_x,
      s1_y = p1_y - p0_y,
      s2_x = p3_x - p2_x,/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      s2_y = p3_y - p2_y,
      s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y),
      t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

  if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
    return true;
  }

  return false;
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function SGM(anglexy) {
  this.x = x || 0;
  this.y = y || 0;
  this.angle = angle || 0;
  this.parent = null;
};

SGM.prototype.endX = function() {
  return this.x + Math.cos(this.angle) * segmentLength;
};/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/

SGM.prototype.endY = function() {
  return this.y + Math.sin(this.angle) * segmentLength;
};

SGM.prototype.pointAt = function(xy) {
  var dx = x - this.x,
      dy = y - this.y;

  this.angle = Math.atan2(dydx);
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
SGM.prototype.target = function(xy) {
  this.targetX = x;
  this.targetY = y;
  this.arrived = false;
  this.totalDist = distance({x:this.endX(), y: this.endY()}, {x: this.targetXy: this.targetY});
  this.currentDist = parseInt(this.totalDist);
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
SGM.prototype.gotoTarget = function() {
  if(!this.arrived) {
    if(this.targetX > this.x + segmentLength || this.targetX < this.x - segmentLength || this.targetY > this.y + segmentLength || this.targetY < this.y - segmentLength) {
      this.pointAt(this.targetXthis.targetY);
    }
    else {
      this.arrived = true;
    }
    /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    this.currentDist = distance({x:this.endX(), y: this.endY()}, {x: this.targetXy: this.targetY});
  }
  
  this.x += (this.endX() - this.x) / snakeSpeed;
  this.y += (this.endY() - this.y) / snakeSpeed;

  this.parent.drag(this.xthis.y);
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
SGM.prototype.drag = function(xy) {
  this.pointAt(xy);

  this.x = x - Math.cos(this.angle) * segmentLength;
  this.y = y - Math.sin(this.angle) * segmentLength;

  if(this.parent) {
    this.parent.drag(this.xthis.y);
  }
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
SGM.prototype.render = function(context) {
  context.lineTo(this.endX(), this.endY());
};

function IKR(xy) {
  this.ix = x || 0;
  this.iy = y || 0;
  this.sgms = [];
  this.lastArm = null;
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
IKR.prototype.addSeg = function(angle) {
  var arm = new SGM(angle);

  if(this.lastArm !== null) {
    arm.x = this.lastArm.endX();
    arm.y = this.lastArm.endY();

    arm.parent = this.lastArm;
  }
  else {
    arm.x = this.ix;
    arm.y = this.iy;
  }
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  this.sgms.push(arm);
  this.lastArm = arm;
};

IKR.prototype.grow = function() {
  var tail = this.sgms[0],
      arm = new SGM(tail.angle);
  
  arm.x = tail.x - Math.cos(tail.angle) * segmentLength;
  arm.y = tail.y - Math.sin(tail.angle) * segmentLength;
  /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  tail.parent = arm;
  this.sgms.unshift(arm);
}

IKR.prototype.drag = function(xy) {
  this.lastArm.drag(xy);
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function CUR(x,y) {
  this.x = x;
  this.y = y;
  this.rotation = 0;
};

CUR.prototype.render = function(context) {
  context.save();
  /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  context.translate(this.xthis.y);
  context.rotate(this.rotation);
  
  context.beginPath();
  
  context.moveTo(0, -cursorSize);
  context.lineTo(0, -cursorSize/2);
  context.moveTo(0cursorSize/2);
  context.lineTo(0cursorSize);
  /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  context.moveTo(-cursorSize0);
  context.lineTo(-cursorSize/20);
  context.moveTo(cursorSize/20);
  context.lineTo(cursorSize0);
  
  context.stroke();
  context.restore();
  
  this.rotation = (this.rotation + cursorSpin) % 360;
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function Apple(xy) {
  this.x = x;
  this.y = y;
  this.life = appleLife;
  this.rotation = 0;
}

Apple.prototype.update = function() {
  this.life--;
};
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
Apple.prototype.render = function(context) {
  context.beginPath();
  context.arc(this.xthis.yappleWidth0Math.PI*2);
  context.fill();
  
  if(gameState !== 'dead') {
    context.save();
    
    context.fillStyle = 'white';
    context.font = '8px sans-serif';
    context.fillText(this.lifethis.x+10this.y+10);
    
    context.restore();
  /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    CUR.prototype.render.call(thiscontext);
  }
};

function init() {
  snake = new IKR(spawn.xspawn.y);
  cursor = new CUR(-20, -20);
  target = new CUR(spawn.x + segmentLength * (startingSegments + 5), spawn.y);
  apples = [];
  score = 0;
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  for(var i = 0i < startingSegmentsi++) {
    snake.addSeg();
  }
  
  snake.lastArm.target(target.xtarget.y);
  
  gameState = 'play';
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
init();

cnv.addEventListener('mousemove'function(e) {
  switch(gameState) {
    case 'play':
      cursor.x = e.offsetX;
      cursor.y = e.offsetY;
    break;
  }
});
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
cnv.addEventListener('mousedown'function(e) {
  switch(gameState) {
    case 'play':
      target.x = e.offsetX;
      target.y = e.offsetY;
      snake.lastArm.target(target.xtarget.y);
    break;
    case 'dead':
      init();
    break;
  }
});
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function badPlacement(apple) {
  for(var s = 0s < snake.sgms.lengths++) {
    var seg = snake.sgms[s];
    
    if(Math.min(distance(apple, {x:seg.endX(), y:seg.endY()}), distance(apple, {x:seg.x,y:seg.y})) < appleWidth*2) {
      return true;
    }
  }
  return false;
}

function addScoreSegments() {
 for(var i = 0i < segmentsPerApplei++) {
   snake.grow();
 } 
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function update() {
  if(gameState !== 'dead') {
    snake.lastArm.gotoTarget();
    
    if(snake.lastArm.endX() > cnv.width - 2 || snake.lastArm.endX() < 2 || snake.lastArm.endY() > cnv.height - 2 || snake.lastArm.endY() < 2) {
      gameState = 'dead';
      deathMeans = 'You hit the wall...';
      return;
    } 
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    for(var s = 0s < snake.sgms.length-2s++) {
      var seg = snake.sgms[s];
      
      if(lineIntersect(snake.lastArm.xsnake.lastArm.ysnake.lastArm.endX(), snake.lastArm.endY(), seg.xseg.yseg.endX(), seg.endY())) {
        gameState = 'dead';
        deathMeans = 'You bit yourself!';
        return;
      }
      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      for(var a in apples) {
        var apple = apples[a];
        
        if(Math.min(distance(apple, {x:seg.endX(), y:seg.endY()}), distance(apple, {x:seg.x,y:seg.y})) < appleWidth*2) {
          score += Math.round(apple.life/2); // half  score if absorbed by the tail
          apples.splice(a1);
          addScoreSegments();
        }
      }
    }
    /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
    for(var a in apples) {
      var apple = apples[a];
      
      apple.update();
      
      if(apple.life <= 0) {
        apples.splice(a,1);
        continue;
      }
      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      if(distance(apple,{x:snake.lastArm.endX(),y:snake.lastArm.endY()})  < appleWidth*2) {
        score += apple.life;
        apples.splice(a,1);
        
        addScoreSegments();
      }
    }
    
    if(apples.length < maxApples && Math.random()<.1) {
      var offset = appleWidth*10,
          apple = new Apple(
            offset/2+Math.floor(Math.random()*(cnv.width-offset)),
            offset/2+Math.floor(Math.random()*(cnv.height-offset))
          );
      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      
      while(badPlacement(apple)) {
        apple.x = offset/2+Math.floor(Math.random()*(cnv.width-offset));
        apple.y = offset/2+Math.floor(Math.random()*(cnv.height-offset));
      }
      
      apples.push(apple);
    }
  }
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function drawTarget(targetModFactor) {
  if(!snake.lastArm.arrived) {
    ctx.strokeStyle = 'rgba('+
      (targetColor[0] + targetColorMod[0]*targetModFactor).toFixed(0) + ',' +
      (targetColor[1] + targetColorMod[1]*targetModFactor).toFixed(0) + ',' +
      (targetColor[2] + targetColorMod[2]*targetModFactor).toFixed(0) + ',' +
      (targetColor[3] + targetColorMod[3]*targetModFactor).toFixed(0)
      +')';
    ctx.lineWidth = 1;
    target.render(ctx);
  }
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function drawSnake() {
  ctx.beginPath();
  ctx.strokeStyle = ctx.fillStyle = 'rgba('snakeColor[0] +','snakeColor[1] +','snakeColor[2] +','snakeColor[3]+')';
  ctx.lineWidth = snakeWidth;

  ctx.moveTo(snake.sgms[0].xsnake.sgms[0].y);

  for(var s in snake.sgms) {
    snake.sgms[s].render(ctx);
  }
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  ctx.stroke();
  
  ctx.beginPath();
  ctx.arc(snake.lastArm.endX(), snake.lastArm.endY(), appleWidth*.750Math.PI*2);
  ctx.fill();
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function drawCursor(targetModFactor) {
  ctx.strokeStyle = 'rgba('+
    (cursorColor[0] + cursorColorMod[0]*targetModFactor).toFixed(0) + ',' +
    (cursorColor[1] + cursorColorMod[1]*targetModFactor).toFixed(0) + ',' +
    (cursorColor[2] + cursorColorMod[2]*targetModFactor).toFixed(0) + ',' +
    (cursorColor[3] + cursorColorMod[3]*targetModFactor).toFixed(0)
    +')';
  ctx.lineWidth = 1;
  cursor.render(ctx);
}/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/

function drawApples() {
  ctx.fillStyle = 'rgba('+
    appleColor[0] +','+
    appleColor[1] +','+
    appleColor[2] +','+
    appleColor[3]
    +')';
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
  for(var a in apples) {
    var apple = apples[a],
        appleTargetMod = 1 - apple.life / appleLife;
    ctx.strokeStyle = 'rgba('+
      (cursorColor[0] + cursorColorMod[0]*appleTargetMod).toFixed(0) + ',' +
      (cursorColor[1] + cursorColorMod[1]*appleTargetMod).toFixed(0) + ',' +
      (cursorColor[2] + cursorColorMod[2]*appleTargetMod).toFixed(0) + ',' +
      (cursorColor[3] + cursorColorMod[3]*appleTargetMod).toFixed(0)
      +')';
    ctx.lineWidth = 1;
    apple.render(ctx);
  }
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function render() {
  var targetModFactor = 1 - snake.lastArm.currentDist / snake.lastArm.totalDist;
  
  switch(gameState) {
    case 'play':
      ctx.clearRect(00cnv.widthcnv.height);

      drawTarget(targetModFactor);
      
      drawSnake();
      
      drawApples();
      
      drawCursor(targetModFactor);

      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      ctx.fillStyle = 'rgba('+
        scoreColor[0] +','+
        scoreColor[1] +','+
        scoreColor[2] +','+
        scoreColor[3]
      +')';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';
      ctx.fillText('Score: '+score1010);
    break;
      
    case 'dead':
      ctx.clearRect(00cnv.widthcnv.height);
      
      drawSnake();
      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      drawApples();
      ctx.fillStyle = 'rgba(255,0,0,0.5)';
      ctx.fillRect(100100cnv.width - 200cnv.height - 200);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = ctx.strokeStyle = 'white';
      ctx.font = 'bold 30px sans-serif'
      ctx.fillText('DEAD'cnv.width/2cnv.height/2-70);
      
      ctx.font = 'bold 25px sans-serif'
      ctx.fillText(deathMeanscnv.width/2cnv.height/2-30);
      /*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
      ctx.font = '20px sans-serif';
      ctx.fillText('Score:'cnv.width/2cnv.height/2+15);
      ctx.font = 'bold 60px sans-serif';
      ctx.fillText(scorecnv.width/2cnv.height/2+60);
      ctx.font = 'lighter 10px sans-serif';
      ctx.lineWidth = 1;
      ctx.strokeRect(103103cnv.width - 206cnv.height - 206);
    break;
  }
}
/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/
function animate() {
  update();
  render();
  requestAnimationFrame(animate);
}

snake.lastArm.target(target.xtarget.y);
animate();/*-webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;*/



 After following these three steps correctly, you can easily enhance this snake game. If you encounter any problems while making this game or if you have any questions or concerns, please let me know in the comments. I will help you to fully learn and know how I made this game. Special thanks to you for reading up on the article.


❤Sharing is caring❤



Post a Comment

1 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment
To Top