1
1
import React , { Component } from 'react' ;
2
- import { connect } from 'react-redux' ;
3
2
import cs from 'classnames' ;
4
3
5
4
import './App.css' ;
@@ -10,11 +9,37 @@ for (var i = 0; i <= 50; i++) {
10
9
GRID_ARRAY . push ( i ) ;
11
10
}
12
11
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
+
13
35
class App extends Component {
14
36
constructor ( props ) {
15
37
super ( props ) ;
16
38
17
39
this . state = {
40
+ controls : {
41
+ direction : CONTROLS . RIGHT ,
42
+ } ,
18
43
snake : {
19
44
position : {
20
45
x : 10 ,
@@ -27,12 +52,24 @@ class App extends Component {
27
52
y : 25 ,
28
53
} ,
29
54
} ,
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 )
31
69
}
32
70
33
71
render ( ) {
34
72
const { snake, snack } = this . state ;
35
-
36
73
return (
37
74
< div >
38
75
< Grid
0 commit comments