Skip to content

Commit

Permalink
part 03
Browse files Browse the repository at this point in the history
  • Loading branch information
rwieruch committed Sep 2, 2017
1 parent 8c63111 commit 0b00398
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,35 @@ import cs from 'classnames';

import './App.css';

const TICK_RATE = 100;
const GRID_SIZE = 35;
const GRID = [];

for (let i = 0; i <= GRID_SIZE; i++) {
GRID.push(i);
}

const DIRECTIONS = {
UP: 'UP',
BOTTOM: 'BOTTOM',
RIGHT: 'RIGHT',
LEFT: 'LEFT',
};

const DIRECTION_TICKS = {
UP: (x, y) => ({ x, y: y - 1 }),
BOTTOM: (x, y) => ({ x, y: y + 1 }),
RIGHT: (x, y) => ({ x: x + 1, y }),
LEFT: (x, y) => ({ x: x - 1, y }),
};

const KEY_CODES_MAPPER = {
38: 'UP',
39: 'RIGHT',
37: 'LEFT',
40: 'BOTTOM',
};

const isBorder = (x, y) =>
x === 0 || y === 0 || x === GRID_SIZE || y === GRID_SIZE;

Expand All @@ -26,11 +48,31 @@ const getCellCs = (snake, snack, x, y) =>
}
);

const applySnakePosition = (prevState) => {
const directionFn = DIRECTION_TICKS[prevState.playground.direction];
const coordinate = directionFn(prevState.snake.coordinate.x, prevState.snake.coordinate.y);

return {
snake: {
coordinate,
},
};
};

const doChangeDirection = (direction) => () => ({
playground: {
direction,
},
});

class App extends Component {
constructor(props) {
super(props);

this.state = {
playground: {
direction: DIRECTIONS.RIGHT,
},
snake: {
coordinate: {
x: 20,
Expand All @@ -46,6 +88,28 @@ class App extends Component {
};
}

componentDidMount() {
this.interval = setInterval(this.onTick, TICK_RATE);

window.addEventListener('keyup', this.onChangeDirection, false);
}

componentWillUnmount() {
clearInterval(this.interval);

window.removeEventListener('keyup', this.onChangeDirection, false);
}

onChangeDirection = (event) => {
if (KEY_CODES_MAPPER[event.keyCode]) {
this.setState(doChangeDirection(KEY_CODES_MAPPER[event.keyCode]));
}
}

onTick = () => {
this.setState(applySnakePosition);
}

render() {
const {
snake,
Expand Down

0 comments on commit 0b00398

Please sign in to comment.