Last active
September 17, 2017 18:40
-
-
Save vanceingalls/b96436da2c008ab814182153df1ea6dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Direction from './direction'; | |
function randomCoords(xMax, yMax) { | |
return {x: Math.floor(Math.random() * xMax), y: Math.floor(Math.random() * yMax)}; | |
} | |
var SnakeGameLogic = function SnakeGameLogic(rows, cols, initialSnakePoints, initialDirection) { | |
var appleCoords = randomCoords(cols, rows); | |
var getApplePoint = function getApplePoint() { | |
return appleCoords; | |
}; | |
var score = 0; | |
var getScore = function getScore() { | |
return score; | |
}; | |
var snakePoints = initialSnakePoints; | |
var getSnakePoints = function getSnakePoints() { | |
return snakePoints; | |
}; | |
var canContinue = true; | |
var shouldContinue = function shouldContinue() { | |
return canContinue; | |
}; | |
var direction = initialDirection; | |
var input = function input(code) { | |
if (Math.abs(direction - code) !== 2) { | |
direction = code; | |
} | |
}; | |
var update = function update() { | |
var head = snakePoints[snakePoints.length - 1]; | |
var newHead = {x: head.x, y: head.y}; | |
switch (direction) { | |
case 0: newHead.y -= 1; break; | |
case 1: newHead.x += 1; break; | |
case 2: newHead.y += 1; break; | |
case 3: newHead.x -= 1; break; | |
} | |
snakePoints.push(newHead); | |
// if ate apple | |
if (newHead.x === appleCoords.x && newHead.y === appleCoords.y) { | |
appleCoords = randomCoords(cols, rows); | |
score += 1; | |
} else { | |
snakePoints.shift(); | |
} | |
// if hit wall | |
canContinue = !(newHead.x > cols - 1 || newHead.y > rows - 1 || newHead.x < 0 || newHead.y < 0); | |
}; | |
return { | |
getApplePoint: getApplePoint, | |
getScore: getScore, | |
getSnakePoints: getSnakePoints, | |
input: input, | |
shouldContinue: shouldContinue, | |
update: update | |
}; | |
}; | |
export default SnakeGameLogic; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment