We can play the game but we aren't keeping score yet. The score in 2048 increases when tiles merge. The value of the old tiles is added to the score. so if we merge two tiles with a value of 2 each, 4 points are added to the score. Merging two tiles with a value of 8 each would add 16 to the score.
To get started we're going to create a new struct called Game to store the game state, like the score. We can derive Default for the Game struct in this case because the default for a u32 is 0 and we don't need any World access to set an integer to 0.
#[derive(Default, Resource)]
struct Game {
score: u32,
}
We'll use init_resource on our App builder to initialize the Game state.
.init_resource::<Game>()
The board_shift system is where we decide whether or not to merge two tiles, which is when we need to add to the total score as well. We need to ask the Bevy system for a ResMut<Game> so we can mutate the Game resource.
fn board_shift(
...
mut game: ResMut<Game>,
) {
After we merge the tiles and set tile.2.value we can take the new value of the tile that is left and add it to the game score.
tile.2.value = tile.2.value
+ real_next_tile.2.value;
game.score += tile.2.value;
We won't actually see the score going up at this point, but we can add a dbg above the new tile event.
dbg!(game.score);
tile_writer.send(NewTileEvent);
This will log out the game score as we play. Remember to remove it if you don't want to see the output.
[src/main.rs:362] game.score = 432
[src/main.rs:362] game.score = 436
[src/main.rs:362] game.score = 476
[src/main.rs:362] game.score = 544
[src/main.rs:362] game.score = 552
[src/main.rs:362] game.score = 556
[src/main.rs:362] game.score = 560