Skip to content

Commit 3e94b0d

Browse files
committed
Step 6.7: Create 'Score' layer
1 parent 40071c1 commit 3e94b0d

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
};

views/game.html

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
<script type="text/javascript" src="/scripts/engine/game.js"></script>
2525
<script type="text/javascript" src="/scripts/game/entities/snake.js"></script>
2626
<script type="text/javascript" src="/scripts/game/screens/play/index.js"></script>
27+
<script type="text/javascript" src="/scripts/game/screens/play/score.js"></script>
2728
<script type="text/javascript" src="/scripts/game/screens/play/snake.js"></script>
2829
<script type="text/javascript" src="/scripts/game/screens/play/ready.js"></script>
2930
<script type="text/javascript" src="/scripts/game/screens/menu/index.js"></script>

0 commit comments

Comments
 (0)