ProgMaster._.

CREATING SNAKE GAME USING HTML, CSS & JS.





This tutorial will guide you through CREATING SNAKE GAME USING HTML, CSS & JS. Follow all the given step :

Step 1 : Create Index.html and add given html code on it.
Step 2 : Create style.css and add given css code on it.
Step 3 : Create index.js and add given JavaScript code on it.

HTML


HTML Code for SNAKE GAME.



<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Snake Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div class="wrap">
        <div class="game-card" id="gamecard">
            <div class="canvas-wrap">
                <canvas id="gameCanvas" width="600" height="600" aria-label="Snake Game"></canvas>
            </div>

            <div class="overlay" id="overlay" style="display: none;">
                <div class="box" id="overlayBox">
                    <h2 id="overlayTitle">Paused</h2>
                    <p id="overlayMsg">Press Resume to continue</p>
                    <div style="margin-top: 12px;">
                        <button id="resumeBtn" class="secondary">Resume</button>
                        <button id="restartBtn">Restart</button>
                    </div>
                </div>
            </div>
        </div>

        <aside class="panel">
            <div>
                <h1>Snake Game</h1>
                <p class="small">Move the snake,eat the glowing food, and grow. Avid Hitting walls or yourself.</p>
            </div>
            
            <div class="stats">
                <div class="stat">
                    <span style="font-size: 12px; color: var(--muted);">Score</span>
                    <strong id="score">0</strong>
                </div>
                <div class="stat">
                    <span style="font-size: 12px; color: var(--muted);">High Score</span>
                    <strong id="highScore">0</strong>
                </div>
            </div>

            <div class="buttons">
                <button id="startBtn">Start game</button>
                <button id="pauseBtn" class="secondary">Pause</button>
                <button id="speedBtn" class="secondary">Speed: Normal</button>
            </div>

            <p class="hint">Controls: Arrow keys or WASD. On Mobile, use the D-pad below.</p>

            <div class="touch-controls" id="touchControls">
                <div class="dpad">
                    <div></div>
                    <button data-dir="up">↑</button>
                    <div></div>

                    <button data-dir="left">←</button>
                    <button data-dir="down">↓</button>
                    <button data-dir="right">→</button>
                </div>
            </div>
        </aside>
    </div>

    <script src="index.js"></script>
</body>
</html>

    


CSS


CSS Code for SNAKE GAME.

    

:root{
    --bg1: #071021;
    --bg2: #0f1724;
    --panel: rgba(255,255,255,0.03);
    --accent: #00f5a0;
    --accent2: #7c5cff;
    --glass: rgba(255,255,255,0.04);
    --text: #d8f8ef;
    --muted: rgba(216,248,239,0.6);
}

*{
    box-sizing: border-box;
}

html,body{
    height: 100%;
}

body{
    margin: 0;
    font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial; 
    background: radial-gradient(1200px 600px at 10% 10%, rgba(124,92,255,0.07), transparent), 
                radial-gradient(800px 500px at 90% 90%, rgba(0,245,160,0.03), transparent), 
                linear-gradient(180deg,var(--bg1),var(--bg2));  
    color: var(--text);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;    
    background: #000;
}

.wrap{
    width: 100%;
    max-width: 980px;
    display: grid;
    grid-template-columns: 1fr 360px;
    gap: 20px;
}

.game-card{
    background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
    border-radius: 14px;
    padding: 18px;
    box-shadow: 0 8px 20px rgba(2,6,23,0.6), inset 0 1px 0 rgba(255,255,255,0.02);
    position: relative;
    min-height: 480px;
}

.canvas-wrap{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    min-height: 420px;
    background: linear-gradient(180deg, rgba(255,255,255,0.01), transparent);
    border-radius: 10px;
    padding: 14px;
}

canvas{
    background: linear-gradient(transparent 0 55%, rgba(255,255,255,0.01) 55% 100%),
                linear-gradient(circle at 10% 10%, rgba(124,92,255,0.04), transparent 5%),
                rgba(0,0,0,0.25);
    border-radius: 8px;
    width: 100%;
    height: 100%;
    max-height: 640px;
    box-shadow: 0 12px 30px rgba(0,0,0,0.6), 0 0 40px rgba(124, 92, 255, 0.05);
    display: block;   
}

.panel{
    background: var(--panel);
    border-radius: 14px;
    padding: 18px;
    min-height: 420px;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

h1{
    margin: 0;
    font-size: 20px;
    letter-spacing: 0.6px;
}

p.small{
    margin: 0;
    color: var(--muted);
    font-size: 13px;
}

.stats{
    display: flex;
    gap: 10px;
    margin-top: 6px;
}

.stat{
    flex: 1;
    background: var(--glass);
    padding: 10px;
    border-radius: 10px;
    text-align: center;
}

.stat strong{
    display: block;
    font-size: 18px;
}

.buttons{
    display: flex;
    gap: 10px;
    margin-top: 10px;
}

button{
    background: linear-gradient(180deg, var(--accent), var(--accent2));
    color: #02121a;
    border: none;
    padding: 10px 12px;
    border-radius: 10px;
    cursor: pointer;
    font-weight: 700;
    box-shadow: 0 8px 20px rgba(124, 92, 255, 0.12);
}

button.secondary{
    background: transparent;
    border: 1px solid rgba(255,255,255,0.06);
    color: var(--text);
    font-weight: 600;
    box-shadow: none;
}

.hint{
    margin-top: 8px;
    color: var(--muted);
    font-size: 13px;
}

.overlay{
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
}

.overlay .box{
    background: linear-gradient(180deg, rgba(0,0,0,0.6));
    padding: 18px;
    border-radius: 12px;
    text-align: center;
    pointer-events: auto;
    box-shadow: 0 10px 30px rgba(0,0,0,0.6);
}

.overlay h2{
    margin: 0;
    color: var(--accent);
}

.overlay p{
    margin: 8px 0 0;
    color: var(--muted);
}

.touch-controls{
    margin-top: auto;
    display: flex;
    gap: 10px;
    justify-content: center;
    align-items: center;
    user-select: none;
}

.dpad{
    display: grid;
    grid-template-columns: repeat(3, 56px);
    gap: 8px;
    width: 200px;
    justify-content: center;
}

.dpad button{
    background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
    color: var(--text);
    border-radius: 10px;
    padding: 12px;
    border: 1px solid rgba(255,255,255,0.03);
    font-weight: 700;
     cursor: pointer;
     box-shadow: 0 6px 18px rgba(0,0,0,0.5);
}

@media (max-width:980px) {
    .wrap{grid-template-columns: 1fr; padding: 10px;}
    .panel{
        order: 2;
    }
    .game-card{
        order: 1;
    }
}
    


JavaScript


JavaScript code for SNAKE GAME.

    
const config = {
  gridSize: 20,
  initialSnakeLength: 5,
  baseTick: 10,
  speedMultiplier: 1,
  mode: "classic", 
  colors: {
    bg: "#061016",
    snake: "#00f5a0",
    snakeHead: "#7c5cff",
    food: "#ff4d7e",
    grid: "rgba(255,255,255,0.02)",
    neonGlow: "rgba(124,92,255,0.15)"
  }
};

let canvas, ctx;
let logicalSize = 600;
let cellSize;
let snake = [];
let dir = {x:1,y:0};
let pendingDir = null;
let food = null;
let score = 0;
let highScore = 0;
let running = false;
let paused = false;
let gameOver = false;
let tickInterval = 1000 / config.baseTick;
let lastTick = 0;
let speedName = "Normal";

function randInt(min,max){return Math.floor(Math.random()*(max-min+1))+min;}

function init(){
  canvas=document.getElementById("gameCanvas");
  ctx=canvas.getContext("2d");
  canvas.width=logicalSize;
  canvas.height=logicalSize;
  cellSize=Math.floor(logicalSize/config.gridSize);
  highScore=parseInt(localStorage.getItem("neon_snake_highscore")||"0",10);
  document.getElementById("highScore").textContent=highScore;
  attachUI();
  resetGame();
  draw();
  requestAnimationFrame(loop);
}

function resetGame(){
  snake=[];
  for(let i=0;i{
  const k=e.key;
  if(k==="ArrowUp"||k==="w"||k==="W")trySetDir(0,-1);
  if(k==="ArrowDown"||k==="s"||k==="S")trySetDir(0,1);
  if(k==="ArrowLeft"||k==="a"||k==="A")trySetDir(-1,0);
  if(k==="ArrowRight"||k==="d"||k==="D")trySetDir(1,0);
  if(k===" ")togglePause();
});

function trySetDir(x,y){
  if(pendingDir)return;
  if(x===-dir.x&&y===-dir.y)return;
  pendingDir={x,y};
}

function attachDpad(){
  const dpad=document.querySelectorAll(".dpad button");
  dpad.forEach(btn=>{
    const set=(d)=>{if(d==="up")trySetDir(0,-1);
      if(d==="down")trySetDir(0,1);
      if(d==="left")trySetDir(-1,0);
      if(d==="right")trySetDir(1,0);}
    btn.addEventListener("touchstart",e=>{e.preventDefault();set(btn.dataset.dir);},{passive:false});
    btn.addEventListener("mousedown",e=>{e.preventDefault();set(btn.dataset.dir);});
  });
}

function placeFood(){
  let valid=false;let tries=0;
  while(!valid&&tries<5000){
    const fx=randInt(0,config.gridSize-1),fy=randInt(0,config.gridSize-1);
    if(!snake.some(s=>s.x===fx&&s.y===fy)){food={x:fx,y:fy};valid=true;}
    tries++;
  }
  if(!valid)food={x:Math.floor(config.gridSize/2)+2,y:Math.floor(config.gridSize/2)+1};
}

function step(){
  if(pendingDir){dir=pendingDir;pendingDir=null;}
  const head={x:snake[0].x+dir.x,y:snake[0].y+dir.y};

  if(config.mode==="wrap"){
    if(head.x<0)head.x=config.gridSize-1;
    if(head.x>=config.gridSize)head.x=0;
    if(head.y<0)head.y=config.gridSize-1;
    if(head.y>=config.gridSize)head.y=0;
  }else{
    if(head.x<0||head.x>=config.gridSize||head.y<0||head.y>=config.gridSize){endGame();return;}
  }

  if(snake.some(seg=>seg.x===head.x&&seg.y===head.y)){endGame();return;}

  snake.unshift(head);
  if(food&&head.x===food.x&&head.y===food.y){
    score+=10;
    if(score%50===0&&config.speedMultiplier<3){
      config.speedMultiplier+=0.2;
      updateSpeedLabel();
      tickInterval=1000/(config.baseTick*config.speedMultiplier);
    }
    placeFood();
  }else snake.pop();
  document.getElementById("score").textContent=score;
}

function endGame(){
  running=false;gameOver=true;
  if(score>highScore){
    highScore=score;
    localStorage.setItem("neon_snake_highscore",String(highScore));
    document.getElementById("highScore").textContent=highScore;
  }
  showOverlay("Game Over",`Score: ${score}`);
  playSound(120,0.06,"sawtooth");
}

function clear(){ctx.fillStyle=config.colors.bg;ctx.fillRect(0,0,canvas.width,canvas.height);}
function drawGrid(){
  ctx.strokeStyle=config.colors.grid;ctx.lineWidth=1;
  for(let i=0;i<=config.gridSize;i++){
    const pos=i*cellSize+0.5;
    ctx.beginPath();ctx.moveTo(pos,0);ctx.lineTo(pos,logicalSize);ctx.stroke();
    ctx.beginPath();ctx.moveTo(0,pos);ctx.lineTo(logicalSize,pos);ctx.stroke();
  }
}
function drawCell(x,y,fillStyle,glowColor=null){
  const px=x*cellSize,py=y*cellSize;
  if(glowColor){ctx.save();ctx.shadowColor=glowColor;ctx.shadowBlur=Math.max(8,cellSize*0.6);
    ctx.fillStyle=fillStyle;ctx.fillRect(px+2,py+2,cellSize-4,cellSize-4);ctx.restore();}
  else{ctx.fillStyle=fillStyle;ctx.fillRect(px+2,py+2,cellSize-4,cellSize-4);}
}
function draw(){
  clear();drawGrid();
  if(food){drawCell(food.x,food.y,config.colors.food,config.colors.neonGlow);
    ctx.fillStyle="rgba(255,255,255,0.06)";
    ctx.fillRect(food.x*cellSize+cellSize*0.3,food.y*cellSize+cellSize*0.3,cellSize*0.4,cellSize*0.4);}
  for(let i=snake.length-1;i>=0;i--){
    const seg=snake[i];
    if(i===0){const gx=ctx.createLinearGradient(seg.x*cellSize,seg.y*cellSize,(seg.x+1)*cellSize,(seg.y+1)*cellSize);
      gx.addColorStop(0,config.colors.snakeHead);gx.addColorStop(1,config.colors.snake);
      drawCell(seg.x,seg.y,gx,config.colors.neonGlow);}
    else drawCell(seg.x,seg.y,config.colors.snake);
  }
  ctx.fillStyle="rgba(255,255,255,0.04)";
  ctx.fillRect(10,10,210,36);
  ctx.fillStyle="rgba(255,255,255,0.7)";
  ctx.font="600 14px Inter, system-ui, Arial";
  ctx.fillText(`Score: ${score}`,20,32);
  ctx.fillText(`Speed x${config.speedMultiplier.toFixed(1)}`,120,32);
  ctx.fillText(config.mode==="wrap"?"Mode: Wrap":"Mode: Classic",20,54);
}

function loop(ts){
  if(!lastTick)lastTick=ts;
  requestAnimationFrame(loop);
  if(!running||paused)return;
  const elapsed=ts-lastTick;
  if(elapsed>=tickInterval){
    lastTick=ts-(elapsed%tickInterval);
    step();draw();
  }
}

function attachUI(){
  document.getElementById("startBtn").addEventListener("click",()=>{
    if(gameOver)resetGame();
    running=true;paused=false;hideOverlay();lastTick=performance.now();playSound(880,0.06,"sine");
  });
  document.getElementById("pauseBtn").addEventListener("click",togglePause);
  document.getElementById("resumeBtn").addEventListener("click",()=>{
    paused=false;hideOverlay();lastTick=performance.now();
  });
  document.getElementById("restartBtn").addEventListener("click",()=>{
    resetGame();running=true;hideOverlay();lastTick=performance.now();
  });

  document.getElementById("speedBtn").addEventListener("click",()=>{
    if(config.speedMultiplier<=0.6){config.speedMultiplier=1;speedName="Normal";}
    else if(config.speedMultiplier<=1.1){config.speedMultiplier=1.5;speedName="Fast";}
    else if(config.speedMultiplier<=1.6){config.speedMultiplier=2;speedName="Very Fast";}
    else{config.speedMultiplier=0.5;speedName="Slow";}
    tickInterval=1000/(config.baseTick*config.speedMultiplier);
    updateSpeedLabel();
  });

  const modeBtn=document.createElement("button");
  modeBtn.id="modeBtn";
  modeBtn.className="secondary";
  modeBtn.textContent="Mode: Classic";
  document.querySelector(".buttons").appendChild(modeBtn);
  modeBtn.addEventListener("click",()=>{
    config.mode=config.mode==="classic"?"wrap":"classic";
    modeBtn.textContent=config.mode==="classic"?"Mode: Classic":"Mode: Wrap";
    playSound(440,0.08,"square");
  });

  attachDpad();
  window.addEventListener("blur",()=>{if(running&&!paused){paused=true;showOverlay("Paused","Window lost focus");}});
}

function updateSpeedLabel(){
  document.getElementById("speedBtn").textContent=`Speed: ${speedName}`;
}

function showOverlay(title,message){
  const ov=document.getElementById("overlay");
  document.getElementById("overlayTitle").textContent=title;
  document.getElementById("overlayMsg").textContent=message;
  ov.style.display="flex";
}
function hideOverlay(){document.getElementById("overlay").style.display="none";}
function updateOverlay(){paused?showOverlay("Paused","Press Resume to continue"):hideOverlay();}
function togglePause(){if(!running)return;paused=!paused;updateOverlay();}

const audioCtx=new(window.AudioContext||window.webkitAudioContext)();
function playSound(freq=440,duration=0.08,type="sine"){
  try{
    const o=audioCtx.createOscillator(),g=audioCtx.createGain();
    o.type=type;o.frequency.value=freq;g.gain.value=0.0001;o.connect(g);g.connect(audioCtx.destination);
    const now=audioCtx.currentTime;
    g.gain.linearRampToValueAtTime(0.12,now+0.005);
    o.start(now);g.gain.exponentialRampToValueAtTime(0.0001,now+duration);
    o.stop(now+duration+0.02);
  }catch(e){}
}

window.addEventListener("resize",()=>{});
init();
    



Download Source Code



What is HTML

HTML, or HyperText Markup Language, is the standard markup language used to create and design documents on the World Wide Web. It's essentially the backbone of web pages, providing the structure and content that web browsers interpret and display.

HTML consists of a series of elements, which are enclosed by tags to define their purpose and function on a webpage. These elements can include headings, paragraphs, images, links, lists, forms, and more. By using a combination of HTML elements, web developers can organize and present information in a structured and visually appealing manner.

HTML is not a programming language but rather a markup language. This means it doesn't have the capability to perform calculations or execute complex logic like programming languages do. Instead, HTML focuses on describing the structure and content of a document, leaving the presentation and functionality to other technologies like CSS (Cascading Style Sheets) for styling and JavaScript for interactivity.

In summary, HTML serves as the foundation for building web pages, providing the structure and content necessary for browsers to render and display information to users on the internet.

What is CSS

CSS, or Cascading Style Sheets, is a language used to style the presentation of web documents written in HTML and XML. It provides a way to control the layout, colors, fonts, and other visual aspects of a webpage, enabling developers to create attractive and responsive designs. By separating content from presentation, CSS promotes cleaner code, easier maintenance, and greater flexibility in website design. With CSS, developers can achieve consistent branding, improved user experience, and better accessibility across various devices and screen sizes.

What is JavaScript

JavaScript is a versatile programming language used for creating dynamic and interactive web content. It enables developers to manipulate HTML elements, respond to user actions, and build seamless web applications. With its extensive ecosystem of libraries and frameworks, JavaScript powers both client-side and server-side development, making it an essential tool for modern web development.