Game state is now preserved in a file

This commit is contained in:
2026-03-06 19:03:55 +01:00
parent 4c21d309e9
commit 016b1eafb5
5 changed files with 27 additions and 6 deletions
+1
View File
@@ -1 +1,2 @@
main
save.dat
+5
View File
@@ -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) {
+4 -3
View File
@@ -1,5 +1,6 @@
#pragma once
#include <raylib.h>
#include <stdio.h>
#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);
+8
View File
@@ -1,6 +1,7 @@
#include "raylib.h"
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
@@ -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
+9 -3
View File
@@ -3,6 +3,7 @@
#include <math.h>
#include <raylib.h>
#include <stdbool.h>
#include <stdio.h>
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;