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

HTML5 Canvas Snake - version 2

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

Problem

`const GAME_STATE = (function() {
let canvas = document.getElementById('gameboard');
let scoreBoard = document.querySelector('.scoreboard');
let highscoreLabel = document.querySelector('.highscore');

canvas.width = 800;
canvas.height = 600;

let ctx = canvas.getContext('2d'),
gameBoardHeight = canvas.height,
gameBoardWidth = canvas.width,
player,
snake,
snakeHead,
apple;

function init() {
definePlayerProperties();
defineSnakeProperties();
defineAppleProperties();
update();
displayGameboard();
bindEvents();
}

function dispose() {
unbindEvents();
canvas.style.display = 'none';
GAME.init();
}

function displayGameboard() {
canvas.style.display = 'block';
}

function definePlayerProperties() {
player = {
points: 0,
name: '',
isSaved: false
};
}

function defineSnakeProperties() {
snake = {
body: [{
x: 60,
y: 60,
color:'red',
lastPosX: null,
lastPosY: null
}],
direction: 'right',
blockSize: 20
}
snakeHead = snake.body[0];

for( let i = 0; i {
if( ( bodySegment.x === this.x ) && ( bodySegment.y === this.y ) ) {
return false;
}
});
return true;
},
setValidPosition: function() {
while( this.isReachable === false ){
if( (( this.x % snake.blockSize === 0 ) && ( this.y % snake.blockSize === 0 )) && this.isOutsideSnakeBody() ) {
this.isReachable = true;
}
else {
this.x = Math.floor( Math.random() * gameBoardWidth );
this.y = Math.floor( Math.random() * gameBoardHeight );
}
}
}
};
apple.setValidPosition();
}

function handleInput( event ) {
if(snake.direction === 'right' && event.keyCode === 37) {
return;
}
else if(snake.direction === 'left' && event.keyCode === 39) {
return;

Solution

The function handleInput(e) on line 92 does not need 4 if statements to determine if you are going the opposite direction. You can concatonate that in your switch and make a comment about it:

// handle snake direction and make sure you can't go to the opposite direction
    switch ( event.keyCode ) {
        case 38 && snake.direction != 'down':  /* Up arrow was pressed */
            snake.direction = 'up';
            break;
        case 40 && snake.direction != 'up':  /* Down arrow was pressed */
            snake.direction = 'down';
            break;
        case 37 && snake.direction != 'right':  /* Left arrow was pressed */
            snake.direction = 'left';
            break;
        case 39 && snake.direction != 'left':  /* Right arrow was pressed */
            snake.direction = 'right';
            break;
    }


You have an update function on line 123, with a forEach method. That method takes a function as parameter, and provides one argument. You have this on line 126:

snake.body.forEach( (s) => {
        draw(s);
    });


You pass that variable in a function and do nothing else then calling another function with the same parameter. You could replace that like this:

snake.body.forEach( draw );


This does not work for line 327 (functor push will throw error)

Example:



let two = ['test', 'me'];

// first argument = array element
// second argument = element index
// third argument = array
two.forEach(console.log);




I like what you do with defineAppleProperties, using the while loop to determine the apple location, but it could cause issues;

If the player has a perfect game, the snake will fill the entire map if he ate the last apple. If that happens, you have an endless while loop, causing a tab/browser crash. I would check the snake length vs amount of positions on the game board to fix that.

Code Snippets

// handle snake direction and make sure you can't go to the opposite direction
    switch ( event.keyCode ) {
        case 38 && snake.direction != 'down':  /* Up arrow was pressed */
            snake.direction = 'up';
            break;
        case 40 && snake.direction != 'up':  /* Down arrow was pressed */
            snake.direction = 'down';
            break;
        case 37 && snake.direction != 'right':  /* Left arrow was pressed */
            snake.direction = 'left';
            break;
        case 39 && snake.direction != 'left':  /* Right arrow was pressed */
            snake.direction = 'right';
            break;
    }
snake.body.forEach( (s) => {
        draw(s);
    });
snake.body.forEach( draw );

Context

StackExchange Code Review Q#135780, answer score: 2

Revisions (0)

No revisions yet.