From 1908a36f8264e28b90469340c9f12552d77a9171 Mon Sep 17 00:00:00 2001 From: Fredrik Jensen Date: Mon, 14 Aug 2017 22:18:46 +0200 Subject: [PATCH] collision function... :snake: --- src/index.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/index.js b/src/index.js index 3ccb97d..3f22fee 100644 --- a/src/index.js +++ b/src/index.js @@ -145,9 +145,24 @@ const makeFood = () => { const x = _.random(50); const y = _.random(50); + if (_.find(snakeBody, { x, y })) { + console.log('food placed under the snake...'); + + /** + * Food was placed under the snake + */ + return makeFood(); + /** + * So we made food again... yolo + */ + } + food.x = x; food.y = y; + const snakeLength = snake.log.length - 1; + const snakeBody = snake.log.slice((snakeLength - snake.body), snakeLength); + setBrickColor('blue', x, y); }; @@ -163,11 +178,26 @@ const checkIfSnakeIsEating = () => { } }; +/** + * Check collision + */ + +const checkCollision = () => { + const snakeLength = snake.log.length - 2; + const snakeBody = snake.log.slice((snakeLength - snake.body), snakeLength); + const snakeHead = { x: snake.x, y: snake.y }; + + if (_.find(snakeBody, snakeHead)) { + alert('Oh noooo! Collision.... Start again?'); + } +} + /** * Run game */ setInterval(() => { + checkCollision(); moveSnake(snake.direction); checkIfSnakeIsEating(); }, snake.speed);