Snake Game Engine

by soggydoughnut54

HTML

<canvas id="myCanvas" width="500" height="500" style="border: 1px solid red"></canvas>
<h2>
The Grid Object
</h2>
<h3>
Cnstructor:
</h3>
<p>
new Grid(cols, rows);
</p>
<h3>
Methods:
</h3>
<p>
drawGrid();
</p>
<p>
drawScore(col, row, color);
</p>
<h2>
The  GamePiece Object
</h2>
<h3>
Contstructor:
</h3>
<p>
new GamePiece(col, row, color);
</p>
<h3>
Methods:
</h3>
<p>
draw();
</p>
<p>
move(col, row);
</p>

JavaScript

//////////////////
//variables for the game
/////////////////
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var playing = false;
var gamePieces = [];
var grid;
var head;
var food;
var key = -1;
var right = 39,
  left = 37,
  up = 38,
  down = 40;
////splash screen
var splashScreen = new Image();
splashScreen.src = "https://imgur.com/jLIzSSQ.png";
/////////////////
//game methods
///////////////////
/**************
Initialize the game or reset
**************/
function init() {
  //reset the playing variable to false
  playing = false;
  //initialize the grid
  grid = new Grid(21, 21);
  //initialize the food
  food = new GamePiece(10, 10, "red");
  //initialize the head
  head = new GamePiece(5, 5, "purple");
}
/***********
Draw the game 
***********/
function draw() {
  //draw the splash screen
  context.drawImage(splashScreen, 0, 0, canvas.width, canvas.height);
  //check to see if game has started
  if (playing === true) {
    //clear the canvas
    context.clearRect(0, 0, canvas.width, canvas.height)
    //draw the grid
    grid.drawGrid();
    //check for collision between the head and the food
    if (head.row === food.row && head.col === food.col) {
      //1. add segment to snake
      new GamePiece(head.col, head.row, head.color)
      //2. move food
      food.move();
    }
    //move the head and check for boundaries
    if (head.move(head.col + head.dirX, head.row + head.dirY) === false) {
      //reset head
      init();
    }
    //draw the head
    head.draw();
    //draw the food
    food.draw()
    //loop through the list of game pieces to draw them all
    for (var i = gamePieces.length - 1; i > 1; i--) {
      //draw the game piece
      gamePieces[i].draw();
      //check for collision with the head
      if (gamePieces[i].col === head.col && gamePieces[i].row === head.row) {
        //dead
        init();
      }
      //move all game pieces that are not the head or the food to previous game piece's...