Skip to content

Commit 9ae2e1f

Browse files
committed
snake moves with key controls
1 parent 813b0c5 commit 9ae2e1f

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

src/App.js

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,18 @@ for (var i = 0; i <= 50; i++) {
99
GRID_ARRAY.push(i);
1010
}
1111

12+
const KEY_CODES_MAPPER = {
13+
38: 'UP',
14+
39: 'RIGHT',
15+
37: 'LEFT',
16+
40: 'BOTTOM',
17+
};
18+
1219
const CONTROLS = {
1320
UP: 'UP',
14-
BOTTOM: 'BOTTOM',
1521
RIGHT: 'RIGHT',
1622
LEFT: 'LEFT',
23+
BOTTOM: 'BOTTOM',
1724
};
1825

1926
const DIRECTION_TICKS = {
@@ -24,14 +31,20 @@ const DIRECTION_TICKS = {
2431
};
2532

2633
// TODO compose instead
27-
const setSnakePosition = (prevState) => ({
34+
const applySnakePosition = (prevState) => ({
2835
snake: {
2936
position: {
3037
...DIRECTION_TICKS[prevState.controls.direction](prevState.snake.position.x, prevState.snake.position.y),
3138
},
3239
},
3340
});
3441

42+
const doChangeDirection = (direction) => () => ({
43+
controls: {
44+
direction,
45+
},
46+
});
47+
3548
class App extends Component {
3649
constructor(props) {
3750
super(props);
@@ -57,19 +70,30 @@ class App extends Component {
5770
}
5871

5972
componentDidMount() {
60-
this.interval = setInterval(this.tick, 150);
73+
this.interval = setInterval(this.onTick, 150);
74+
75+
window.addEventListener('keyup', this.onChangeDirection, false);
6176
}
6277

6378
componentWillUnmount() {
6479
clearInterval(this.interval);
80+
81+
window.removeEventListener('keyup', this.onChangeDirection, false);
6582
}
6683

67-
tick = () => {
68-
this.setState(setSnakePosition)
84+
onTick = () => {
85+
this.setState(applySnakePosition);
86+
}
87+
88+
onChangeDirection = (e) => {
89+
if (KEY_CODES_MAPPER[e.keyCode]) {
90+
this.setState(doChangeDirection(KEY_CODES_MAPPER[e.keyCode]));
91+
}
6992
}
7093

7194
render() {
72-
const { snake, snack } = this.state;
95+
const { snake, snack } = this.state
96+
console.log(this.state.controls.direction);;
7397
return (
7498
<div>
7599
<Grid

0 commit comments

Comments
 (0)