@@ -32,29 +32,65 @@ const KEY_CODES_MAPPER = {
32
32
40 : 'BOTTOM' ,
33
33
} ;
34
34
35
+ const getRandomNumberFromRange = ( min , max ) =>
36
+ Math . floor ( Math . random ( ) * ( max - min + 1 ) + min ) ;
37
+
38
+ const getRandomCoordinate = ( ) =>
39
+ ( {
40
+ x : getRandomNumberFromRange ( 1 , GRID_SIZE - 1 ) ,
41
+ y : getRandomNumberFromRange ( 1 , GRID_SIZE - 1 ) ,
42
+ } ) ;
43
+
35
44
const isBorder = ( x , y ) =>
36
45
x === 0 || y === 0 || x === GRID_SIZE || y === GRID_SIZE ;
37
46
38
47
const isPosition = ( x , y , diffX , diffY ) =>
39
48
x === diffX && y === diffY ;
40
49
50
+ const isSnake = ( x , y , snakeCoordinates ) =>
51
+ snakeCoordinates . filter ( coordinate => isPosition ( coordinate . x , coordinate . y , x , y ) ) . length ;
52
+
53
+ const getSnakeHead = ( snake ) =>
54
+ snake . coordinates [ 0 ] ;
55
+
56
+ const getSnakeWithoutStub = ( snake ) =>
57
+ snake . coordinates . slice ( 0 , snake . coordinates . length - 1 ) ;
58
+
59
+ const getIsSnakeEating = ( { snake, snack } ) =>
60
+ isPosition ( getSnakeHead ( snake ) . x , getSnakeHead ( snake ) . y , snack . coordinate . x , snack . coordinate . y ) ;
61
+
41
62
const getCellCs = ( snake , snack , x , y ) =>
42
63
cs (
43
64
'grid-cell' ,
44
65
{
45
66
'grid-cell-border' : isBorder ( x , y ) ,
46
- 'grid-cell-snake' : isPosition ( x , y , snake . coordinate . x , snake . coordinate . y ) ,
67
+ 'grid-cell-snake' : isSnake ( x , y , snake . coordinates ) ,
47
68
'grid-cell-snack' : isPosition ( x , y , snack . coordinate . x , snack . coordinate . y ) ,
48
69
}
49
70
) ;
50
71
51
72
const applySnakePosition = ( prevState ) => {
52
- const directionFn = DIRECTION_TICKS [ prevState . playground . direction ] ;
53
- const coordinate = directionFn ( prevState . snake . coordinate . x , prevState . snake . coordinate . y ) ;
73
+ const isSnakeEating = getIsSnakeEating ( prevState ) ;
74
+
75
+ const snakeHead = DIRECTION_TICKS [ prevState . playground . direction ] (
76
+ getSnakeHead ( prevState . snake ) . x ,
77
+ getSnakeHead ( prevState . snake ) . y ,
78
+ ) ;
79
+
80
+ const snakeTail = isSnakeEating
81
+ ? prevState . snake . coordinates
82
+ : getSnakeWithoutStub ( prevState . snake ) ;
83
+
84
+ const snackCoordinate = isSnakeEating
85
+ ? getRandomCoordinate ( )
86
+ : prevState . snack . coordinate ;
54
87
55
88
return {
56
89
snake : {
57
- coordinate,
90
+ coordinates : [ snakeHead , ...snakeTail ] ,
91
+ } ,
92
+ snack : {
93
+ coordinate : snackCoordinate ,
58
94
} ,
59
95
} ;
60
96
} ;
@@ -74,16 +110,10 @@ class App extends Component {
74
110
direction : DIRECTIONS . RIGHT ,
75
111
} ,
76
112
snake : {
77
- coordinate : {
78
- x : 20 ,
79
- y : 10 ,
80
- } ,
113
+ coordinates : [ getRandomCoordinate ( ) ] ,
81
114
} ,
82
115
snack : {
83
- coordinate : {
84
- x : 25 ,
85
- y : 10 ,
86
- } ,
116
+ coordinate : getRandomCoordinate ( ) ,
87
117
}
88
118
} ;
89
119
}
0 commit comments