Skip to content

Commit 0b00398

Browse files
committed
part 03
1 parent 8c63111 commit 0b00398

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/App.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,35 @@ import cs from 'classnames';
33

44
import './App.css';
55

6+
const TICK_RATE = 100;
67
const GRID_SIZE = 35;
78
const GRID = [];
89

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

14+
const DIRECTIONS = {
15+
UP: 'UP',
16+
BOTTOM: 'BOTTOM',
17+
RIGHT: 'RIGHT',
18+
LEFT: 'LEFT',
19+
};
20+
21+
const DIRECTION_TICKS = {
22+
UP: (x, y) => ({ x, y: y - 1 }),
23+
BOTTOM: (x, y) => ({ x, y: y + 1 }),
24+
RIGHT: (x, y) => ({ x: x + 1, y }),
25+
LEFT: (x, y) => ({ x: x - 1, y }),
26+
};
27+
28+
const KEY_CODES_MAPPER = {
29+
38: 'UP',
30+
39: 'RIGHT',
31+
37: 'LEFT',
32+
40: 'BOTTOM',
33+
};
34+
1335
const isBorder = (x, y) =>
1436
x === 0 || y === 0 || x === GRID_SIZE || y === GRID_SIZE;
1537

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

51+
const applySnakePosition = (prevState) => {
52+
const directionFn = DIRECTION_TICKS[prevState.playground.direction];
53+
const coordinate = directionFn(prevState.snake.coordinate.x, prevState.snake.coordinate.y);
54+
55+
return {
56+
snake: {
57+
coordinate,
58+
},
59+
};
60+
};
61+
62+
const doChangeDirection = (direction) => () => ({
63+
playground: {
64+
direction,
65+
},
66+
});
67+
2968
class App extends Component {
3069
constructor(props) {
3170
super(props);
3271

3372
this.state = {
73+
playground: {
74+
direction: DIRECTIONS.RIGHT,
75+
},
3476
snake: {
3577
coordinate: {
3678
x: 20,
@@ -46,6 +88,28 @@ class App extends Component {
4688
};
4789
}
4890

91+
componentDidMount() {
92+
this.interval = setInterval(this.onTick, TICK_RATE);
93+
94+
window.addEventListener('keyup', this.onChangeDirection, false);
95+
}
96+
97+
componentWillUnmount() {
98+
clearInterval(this.interval);
99+
100+
window.removeEventListener('keyup', this.onChangeDirection, false);
101+
}
102+
103+
onChangeDirection = (event) => {
104+
if (KEY_CODES_MAPPER[event.keyCode]) {
105+
this.setState(doChangeDirection(KEY_CODES_MAPPER[event.keyCode]));
106+
}
107+
}
108+
109+
onTick = () => {
110+
this.setState(applySnakePosition);
111+
}
112+
49113
render() {
50114
const {
51115
snake,

0 commit comments

Comments
 (0)