Added win and loss conditions along with their respective screens

This commit is contained in:
2026-03-06 18:00:19 +01:00
parent eb8834324e
commit 4c21d309e9
5 changed files with 99 additions and 27 deletions
+29 -8
View File
@@ -1,10 +1,12 @@
#include "game.h"
#include <stdlib.h>
#include <string.h>
// Depending on the direction, move the tiles and check if we can merge with the
// tiles in that direction. We merge the tiles only if they are of the same value
void move(GameState_t *state, MOVE_DIRECTION direction) {
void move(GameState_t *state, move_direction_t direction) {
bool merged[BOARD_HEIGHT][BOARD_WIDTH] = {0};
bool moved = false;
switch (direction) {
case UP: {
for (int y = 1; y < BOARD_HEIGHT; y++) {
@@ -43,6 +45,7 @@ void move(GameState_t *state, MOVE_DIRECTION direction) {
state->board[y][x] = 0;
state->score += state->board[target_y][x];
}
moved = true;
}
}
break;
@@ -77,6 +80,7 @@ void move(GameState_t *state, MOVE_DIRECTION direction) {
state->board[y][x] = 0;
state->score += state->board[target_y][x];
}
moved = true;
}
}
break;
@@ -111,6 +115,7 @@ void move(GameState_t *state, MOVE_DIRECTION direction) {
state->board[y][x] = 0;
state->score += state->board[y][target_x];
}
moved = true;
}
}
break;
@@ -145,22 +150,21 @@ void move(GameState_t *state, MOVE_DIRECTION direction) {
state->board[y][x] = 0;
state->score += state->board[y][target_x];
}
moved = true;
}
}
break;
}
}
state->moves_made++;
if (moved)
state->moves_made++;
}
void reset_board(GameState_t *state) {
for (int y = 0; y < BOARD_HEIGHT; y++) {
for (int x = 0; x < BOARD_WIDTH; x++) {
state->board[y][x] = 0;
}
}
memset(state->board, 0, sizeof(state->board));
state->score = 0;
state->moves_made = 0;
state->status = PLAYING;
int tile_count = 0;
while (tile_count != STARTING_TILES) {
@@ -196,4 +200,21 @@ bool spawn_tile(GameState_t *state) {
int spawn_x = empty_tiles[random_index][1];
state->board[spawn_y][spawn_x] = (rand() % 10 == 0) ? 4 : 2; // 10% chance to spawn a 4
return true;
}
}
// This function will only run, if every tile is filled (checked by `spawn_tile`). We can take advantage of that and
// just check every neighboring cell for equal values for merging
bool can_move(GameState_t *state) {
for (int y = 0; y < BOARD_HEIGHT; y++) {
for (int x = 0; x < BOARD_WIDTH; x++) {
if (state->board[y][x] == 0)
return true;
if (x < BOARD_WIDTH - 1 && state->board[y][x] == state->board[y][x + 1])
return true;
if (y < BOARD_HEIGHT - 1 && state->board[y][x] == state->board[y + 1][x])
return true;
}
}
return false;
}