1
+ Game . Screens . Play . Score = class Score extends Engine . Layer {
2
+ constructor ( screen , snakes ) {
3
+ super ( screen ) ;
4
+
5
+ this . snakes = snakes ;
6
+ this . scoreSprites = [ ] ;
7
+ this . scores = [ ] ;
8
+
9
+ // It's important to match indexes to each snake since the number of snakes
10
+ // can be reduced along the way as we play
11
+ snakes . forEach ( ( snake , index ) => {
12
+ snake . index = index ;
13
+ } ) ;
14
+ }
15
+
16
+ draw ( context ) {
17
+ this . scoreSprites . forEach ( ( scoreSprite ) => {
18
+ scoreSprite . draw ( context ) ;
19
+ } ) ;
20
+ }
21
+
22
+ update ( span ) {
23
+ this . snakes . forEach ( snake => {
24
+ let index = snake . index ;
25
+ if ( this . scores [ index ] == snake . score ) return ;
26
+
27
+ // The sprite might be changed along the way so it's important to recreate it
28
+ // over and over again. If no change was made the cache will be used by the engine
29
+ this . scoreSprites [ index ] = this . createScoreSprite ( snake ) ;
30
+ this . scores [ index ] = snake . score ;
31
+ } ) ;
32
+ }
33
+
34
+ createScoreSprite ( snake ) {
35
+ let minecraftiaFont = this . assets . minecraftiaFont ;
36
+ minecraftiaFont . save ( ) ;
37
+ minecraftiaFont . color = snake . color ;
38
+
39
+ // Create a score sprite for the snake
40
+ let scoreTexture = minecraftiaFont . createTexture ( `${ snake . score } ` , {
41
+ noOffsets : true ,
42
+ noSpaces : true
43
+ } ) ;
44
+
45
+ let scoreSprite = new Engine . Sprite ( scoreTexture ) ;
46
+
47
+ // Size of score board is dynamic to screen size
48
+ scoreSprite . setPercentage ( "width" , this . width , 4 , "height" ) ;
49
+
50
+ // Set alignment modes.
51
+ // Once we add more snakes we should add more cases here
52
+ switch ( snake . index ) {
53
+ case 0 :
54
+ scoreSprite . align = "top-left" ;
55
+ break ;
56
+ case 1 :
57
+ scoreSprite . align = "top-right" ;
58
+ scoreSprite . x = this . width ;
59
+ break ;
60
+ }
61
+
62
+ // Restore the font to its original color
63
+ minecraftiaFont . restore ( ) ;
64
+ return scoreSprite ;
65
+ }
66
+ } ;
0 commit comments