@@ -32,29 +32,65 @@ const KEY_CODES_MAPPER = {
3232 40 : 'BOTTOM' ,
3333} ;
3434
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+
3544const isBorder = ( x , y ) =>
3645 x === 0 || y === 0 || x === GRID_SIZE || y === GRID_SIZE ;
3746
3847const isPosition = ( x , y , diffX , diffY ) =>
3948 x === diffX && y === diffY ;
4049
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+
4162const getCellCs = ( snake , snack , x , y ) =>
4263 cs (
4364 'grid-cell' ,
4465 {
4566 '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 ) ,
4768 'grid-cell-snack' : isPosition ( x , y , snack . coordinate . x , snack . coordinate . y ) ,
4869 }
4970 ) ;
5071
5172const 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 ;
5487
5588 return {
5689 snake : {
57- coordinate,
90+ coordinates : [ snakeHead , ...snakeTail ] ,
91+ } ,
92+ snack : {
93+ coordinate : snackCoordinate ,
5894 } ,
5995 } ;
6096} ;
@@ -74,16 +110,10 @@ class App extends Component {
74110 direction : DIRECTIONS . RIGHT ,
75111 } ,
76112 snake : {
77- coordinate : {
78- x : 20 ,
79- y : 10 ,
80- } ,
113+ coordinates : [ getRandomCoordinate ( ) ] ,
81114 } ,
82115 snack : {
83- coordinate : {
84- x : 25 ,
85- y : 10 ,
86- } ,
116+ coordinate : getRandomCoordinate ( ) ,
87117 }
88118 } ;
89119 }
0 commit comments