From 016b1eafb5fee5e7d0c2a68bc1edb7451c9fc1da Mon Sep 17 00:00:00 2001 From: Piotr Kozak Date: Fri, 6 Mar 2026 19:03:55 +0100 Subject: [PATCH] Game state is now preserved in a file --- .gitignore | 1 + game.c | 5 +++++ game.h | 7 ++++--- main.c | 8 ++++++++ ui.c | 12 +++++++++--- 5 files changed, 27 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index ba2906d..8fbd6e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ main +save.dat diff --git a/game.c b/game.c index 55d4ac6..5c95a86 100644 --- a/game.c +++ b/game.c @@ -176,6 +176,11 @@ void reset_board(GameState_t *state) { state->board[y][x] = (rand() % 10 == 0) ? 4 : 2; // 10% chance to spawn a 4 tile_count++; } + FILE *f = fopen("save.dat", "wb"); + if (f) { + fwrite(state, sizeof(GameState_t), 1, f); + fclose(f); + } } bool spawn_tile(GameState_t *state) { diff --git a/game.h b/game.h index 41fffcf..88ce570 100644 --- a/game.h +++ b/game.h @@ -1,5 +1,6 @@ #pragma once #include +#include #define BOARD_WIDTH 4 #define BOARD_HEIGHT 4 @@ -9,10 +10,10 @@ typedef enum { UP, DOWN, LEFT, RIGHT } move_direction_t; typedef enum { PLAYING, WON, LOST } game_status_t; typedef struct { - int board[BOARD_HEIGHT][BOARD_WIDTH]; + unsigned int board[BOARD_HEIGHT][BOARD_WIDTH]; game_status_t status; - int score; - int moves_made; + unsigned int score; + unsigned int moves_made; } GameState_t; void move(GameState_t *state, move_direction_t direction); diff --git a/main.c b/main.c index ad946f1..d133fcf 100644 --- a/main.c +++ b/main.c @@ -1,6 +1,7 @@ #include "raylib.h" #include #include +#include #include #include @@ -30,6 +31,13 @@ int main() { srand(time(NULL)); reset_board(&game_state); + FILE* game_file = fopen("save.dat", "rb"); + if (game_file != NULL) { + fseek(game_file, 0, SEEK_SET); + fread(&game_state, sizeof(GameState_t), 1, game_file); + fclose(game_file); + } + InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "2048"); SetTargetFPS(30); // So my laptop doesn't burn diff --git a/ui.c b/ui.c index 0b2a6f5..006fb88 100644 --- a/ui.c +++ b/ui.c @@ -3,6 +3,7 @@ #include #include #include +#include static bool is_dragging; static Vector2 drag_start_pos; @@ -55,15 +56,20 @@ void handle_mouse_input(GameState_t *game_state) { return; } // TODO: Allow for infinite play - for(int y = 0; y < BOARD_HEIGHT; y++) { - for(int x = 0; x < BOARD_WIDTH; x++) { - if(game_state->board[y][x] == 2048) { + for (int y = 0; y < BOARD_HEIGHT; y++) { + for (int x = 0; x < BOARD_WIDTH; x++) { + if (game_state->board[y][x] == 2048) { game_state->status = WON; return; } } } + FILE *f = fopen("save.dat", "wb"); + if (f) { + fwrite(game_state, sizeof(GameState_t), 1, f); + fclose(f); + } } is_dragging = false;