//////////////////
//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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.