@@ -2,6 +2,7 @@ import React, { Component } from 'react';
2
2
3
3
import Score from '../Score' ;
4
4
import Board from '../Board' ;
5
+ import StartPane from '../StartPane' ;
5
6
6
7
import {
7
8
createInitialBoardState ,
@@ -22,13 +23,14 @@ export default class App extends Component {
22
23
super ( props ) ;
23
24
24
25
this . state = {
26
+ started : false ,
25
27
score : 0 ,
28
+ speed : 200 ,
26
29
direction : "right" ,
27
30
board : createInitialBoardState ( MATRIX_SIZE )
28
31
} ;
29
32
30
- setInterval ( this . tickHandler . bind ( this ) , 150 ) ;
31
-
33
+ this . tickHandler = this . tickHandler . bind ( this ) ;
32
34
this . keyDownHandler = this . keyDownHandler . bind ( this ) ;
33
35
}
34
36
@@ -39,18 +41,32 @@ export default class App extends Component {
39
41
matrixSize : MATRIX_SIZE
40
42
} ) ;
41
43
42
- const nextScore = nextBoardState . food !== this . state . board . food ?
43
- this . state . score + 1 :
44
- this . state . score ;
44
+ let nextScore = this . state . score ;
45
+ let nextSpeed = this . state . speed ;
46
+ if ( nextBoardState . food !== this . state . board . food ) {
47
+ nextScore ++ ;
48
+ nextSpeed = Math . max ( nextSpeed - 2 , 50 ) ;
49
+ }
45
50
46
- this . setState ( { board : nextBoardState , score : nextScore } ) ;
51
+ this . setState ( { board : nextBoardState , score : nextScore , speed : nextSpeed } , ( ) => {
52
+ clearInterval ( this . state . tickerId ) ;
53
+ const tickerId = setInterval ( this . tickHandler , this . state . speed ) ;
54
+ this . setState ( { tickerId} ) ;
55
+ } ) ;
47
56
}
48
57
49
58
keyDownHandler ( event ) {
50
- const direction = KEY_TO_DIRECTION [ event . key ] ;
51
-
52
- if ( direction !== undefined ) {
53
- this . setState ( { direction : direction } ) ;
59
+ if ( ! this . state . started ) {
60
+ this . setState ( { started : true } , ( ) => {
61
+ const tickerId = setInterval ( this . tickHandler , this . state . speed ) ;
62
+ this . setState ( { tickerId } ) ;
63
+ } ) ;
64
+ } else {
65
+ const direction = KEY_TO_DIRECTION [ event . key ] ;
66
+
67
+ if ( direction !== undefined ) {
68
+ this . setState ( { direction : direction } ) ;
69
+ }
54
70
}
55
71
}
56
72
@@ -63,13 +79,14 @@ export default class App extends Component {
63
79
}
64
80
65
81
render ( ) {
82
+ const pane = this . state . started ?
83
+ < Board snake = { this . state . board . snake } food = { this . state . board . food } /> :
84
+ < StartPane /> ;
85
+
66
86
return (
67
87
< div >
68
88
< Score score = { this . state . score } />
69
- < Board
70
- snake = { this . state . board . snake }
71
- food = { this . state . board . food }
72
- />
89
+ { pane }
73
90
</ div >
74
91
) ;
75
92
}
0 commit comments