HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

canvas snake game

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gamecanvassnake

Problem

i made a simple js snake game with canvas, the code is all mine so it can have some drawbacks or not so good parts. I will be glad to hear some opinions.

https://github.com/vitaliyterziev/snake



`var Poly = {
//polyfill Set()
set: function (array) {
'use strict';
var cleanList = [];
var bool = false;

array.forEach(function (itemDup) {
cleanList.forEach(function (noDup) {
if (noDup[0] === itemDup[0] && noDup[1] === itemDup[1]) {
bool = true;
}
});
if (!bool) {
cleanList.push(itemDup);
}
bool = false;
});
return cleanList;
}
};

/*
main game object is below

*/
var SnakeGame = {

setup: function() {
'use strict';
// initial variables
var canvas = document.getElementById('basic'),
ctx = canvas.getContext('2d'),
gameStatus = document.querySelectorAll('h3')[0],
gameRestart = document.querySelectorAll('#restart')[0],
snakeLength = 5,
snakeSpeed = 300,
snakeWidth = 10,
snakeHeight = 10,
snake = [],
x = 10,
y = 10,
direction = 39,
up = 38,
down = 40,
left = 37,
right = 39,
foodCoordinates = [],
xFoodCoordinate,
yFoodCoordinate,
doneMove = false,
feeding = false,
gameOver = false;

// draw object, painting and clearing rectangles
var draw = {
fill: function(x, y) {
ctx.fillRect(x, y, snakeWidth, snakeHeight);
},
clear: function(x, y) {
ctx.clearRect(x, y, snakeWidth, snakeHeight);
}
};

// gradient effects
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "yell

Solution

I think you should try to split your program into multiple objects like Snake, FoodFactory, Field...

And then a Game object which will "just" connect them:

snake.move(direction);
snake.draw();
if(hasCollision(snake.head, snake.queue) || 
   hasCollision(snake.head, field)){
  // display game over
}

if(hasCollision(snake.head, food.position)){
  points += 1;
  snake.increaseLength();
  do{
    food = FoodFactory.create
  while(hasCollision(snake.body, food));
}
//...


So you can separate the rules of the game (the logic) and the actual implementation.

Code Snippets

snake.move(direction);
snake.draw();
if(hasCollision(snake.head, snake.queue) || 
   hasCollision(snake.head, field)){
  // display game over
}

if(hasCollision(snake.head, food.position)){
  points += 1;
  snake.increaseLength();
  do{
    food = FoodFactory.create
  while(hasCollision(snake.body, food));
}
//...

Context

StackExchange Code Review Q#112027, answer score: 5

Revisions (0)

No revisions yet.