Skip to content

Commit 813b0c5

Browse files
committed
snake moves in one direction without input
1 parent 47fc1c6 commit 813b0c5

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

src/App.js

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import React, { Component } from 'react';
2-
import { connect } from 'react-redux';
32
import cs from 'classnames';
43

54
import './App.css';
@@ -10,11 +9,37 @@ for (var i = 0; i <= 50; i++) {
109
GRID_ARRAY.push(i);
1110
}
1211

12+
const CONTROLS = {
13+
UP: 'UP',
14+
BOTTOM: 'BOTTOM',
15+
RIGHT: 'RIGHT',
16+
LEFT: 'LEFT',
17+
};
18+
19+
const DIRECTION_TICKS = {
20+
UP: (x, y) => ({ x, y: y - 1 }),
21+
BOTTOM: (x, y) => ({ x, y: y + 1 }),
22+
RIGHT: (x, y) => ({ x: x + 1, y }),
23+
LEFT: (x, y) => ({ x: x - 1, y }),
24+
};
25+
26+
// TODO compose instead
27+
const setSnakePosition = (prevState) => ({
28+
snake: {
29+
position: {
30+
...DIRECTION_TICKS[prevState.controls.direction](prevState.snake.position.x, prevState.snake.position.y),
31+
},
32+
},
33+
});
34+
1335
class App extends Component {
1436
constructor(props) {
1537
super(props);
1638

1739
this.state = {
40+
controls: {
41+
direction: CONTROLS.RIGHT,
42+
},
1843
snake: {
1944
position: {
2045
x: 10,
@@ -27,12 +52,24 @@ class App extends Component {
2752
y: 25,
2853
},
2954
},
30-
}
55+
};
56+
57+
}
58+
59+
componentDidMount() {
60+
this.interval = setInterval(this.tick, 150);
61+
}
62+
63+
componentWillUnmount() {
64+
clearInterval(this.interval);
65+
}
66+
67+
tick = () => {
68+
this.setState(setSnakePosition)
3169
}
3270

3371
render() {
3472
const { snake, snack } = this.state;
35-
3673
return (
3774
<div>
3875
<Grid

0 commit comments

Comments
 (0)