Created
January 15, 2018 11:01
-
-
Save atoko/aa3a422f524c3751d779dc6eb1bb5544 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
export const GAME_HEIGHT = 32; | |
export const GAME_WIDTH = 32; | |
export const moveSnake = ({x, y}) => ({ | |
type: "MOVE_SNAKE", | |
xVelocity: x, | |
yVelocity: y | |
}); | |
export const spawnDot = ({x = Math.random() * GAME_WIDTH, y = Math.random() * GAME_HEIGHT}) => ({ | |
type: "SPAWN_DOT", | |
x, | |
y | |
}) | |
const moveResult = (state = {}, action) => { | |
const { snake, snakeFrames, dots } = state; | |
const { xVelocity, yVelocity } = action; | |
let snakeNextFrame = { | |
...snake, | |
x: snake.x + xVelocity, | |
y: snake.y + yVelocity | |
}; | |
let {x, y} = snakeNextFrame; | |
if (x < 0 || x > GAME_WIDTH) { | |
return { gameOver: true, ...state }; | |
} | |
if (y < 0 || y > GAME_HEIGHT) { | |
return { gameOver: true, ...state }; | |
} | |
let points = 0; | |
let dotsNextFrame = dots.filter((dot) => { | |
if (dot.x === snakeNextFrame.x && dot.y === snakeNextFrame.y) { | |
points++; | |
return false; | |
} | |
return true; | |
}) | |
return { | |
...state, | |
snake: snakeNextFrame, | |
snakeFrames: [...snakeFrames, snake], | |
dots: dotsNextFrame, | |
points: state.points + points | |
} | |
} | |
const spawnResult = (state = {}, action) => { | |
const {x, y} = action; | |
const dot = { | |
x, | |
y | |
}; | |
const dots = [...state.dots, dot]; | |
return {...state, dots}; | |
} | |
let initialState = () => ({ | |
snake: { x: GAME_WIDTH / 2, y: GAME_HEIGHT / 2 }, | |
snakeFrames: [], | |
dots: [], | |
points: 0 | |
}) | |
export default (state = initialState(), action = {}) => { | |
switch (action.type) { | |
case "MOVE_SNAKE": | |
return moveResult(state, action); | |
case "SPAWN_DOT": | |
return spawnResult(state, action); | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment