JSFiddle - React, Tailwind, and code Playground

by rga4

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Snake Game</title>
</head>

    <body onload="init()">
        <div id="gameBoard"></div>

        <div id="scoreDiv">
            Score: 
            <span id="score">0</span>
        </div>

        <!-- JavaScript functions will be in here -->
        <script type="text/javascript">

        </script>
    </body>
</html>

CSS

/* Define some basic styles */
        body {
            font-family: monospace;
        }
        
        #gameBoard {
            border: 1px solid black;
        }

        .cell {
            width: 25px;
            height: 25px;
        }
        
        .apple {
            background-color: red;
        }
        
        .snake {
            background-color: green;
        }

        body {margin:0;}

JavaScript

// Function to initialize the board and start new game

     function init() {
         let size = 20; // The size of the board
         
         if(document.getElementById("gameBoard").style.display != 'none') return;

         document.getElementById("gameBoard").style.display='block';

        appleX = Math.floor(Math.random() * (size)); 
        appleY = Math.floor(Math.random() * (size));

        direction = 'right'; 
        score = 0;
        var scoreSpan = document.getElementById("score");
        scoreSpan.innerHTML = "Score: " + score;



        mySnake.push([0, 0]);
        updateCell();
      }

      function updateCell(){     
          
          let size = 20;
          let appleX = Math.floor(Math.random() * (size)); 
          let appleY = Math.floor(Math.random() * (size));
          

          let scoreHTML = ""; 
          scoreHTML += "Score: <span id='score'>"+(score+1)+"</span><br/>";
          

          let count = 2;

          while(count--){ 
              let rowHTML = "";
              

              for(var j = 0; j < size; j++){

                 cellClass = "";

                if((j == appleX && i == appleY)) 
                    cellClass += "apple"; 
            
                else{
                    if(mySnake.length > 1 && checkCell(j,i,(mySnake)))cellClass += " snake";
                    
                } 

                
                rowHTML += "<td class='" + cellClass +"'></td>"; 
            
            }
        
            document.getElementById("gameBoard").innerHTML += rowHTML + "</tr>";
            
        }
        
        mySnake.push([i,j]);   

        document.getElementById("gameBoard").innerHTML =""; // clear the board
        
        if(document.getElementById("gameBoard").style.display !='none'){
        init();} // recursive call of function
     }

     // Check function that checks if the snake can move into a given cell without running into itself or other obstacles
function...