diff --git a/src/game/analytics.c b/src/game/analytics.c index 7b40b33..74057b1 100644 --- a/src/game/analytics.c +++ b/src/game/analytics.c @@ -167,6 +167,20 @@ EM_JS(void, js_analytics_send_end, (int score, int level_reached, doEnd(sid, endReason, score, level_reached, lives_used, duration_secs); }); +/* Stash current stats as JSON so the beforeunload fallback in + * shell.html has up-to-date data if the user closes the tab. */ +EM_JS(void, js_analytics_stash_stats, (int score, int level_reached, + int lives_used, int duration_secs), { + if (!Module._analyticsUrl) return; + Module._analyticsLastStats = JSON.stringify({ + score: score, + level_reached: level_reached > 0 ? level_reached : 1, + lives_used: lives_used, + duration_seconds: duration_secs, + end_reason: 'quit' + }); +}); + /* ── C wrappers ─────────────────────────────────────────────────── */ void analytics_init(void) { @@ -188,6 +202,16 @@ void analytics_session_end(GameStats *stats, const char *end_reason) { ); } +void analytics_stash_stats(GameStats *stats) { + stats_update_score(stats); + js_analytics_stash_stats( + stats->score, + stats->levels_completed > 0 ? stats->levels_completed : 1, + stats->deaths, + (int)stats->time_elapsed + ); +} + #else /* ── Non-WASM stubs ─────────────────────────────────────────────── */ @@ -202,4 +226,8 @@ void analytics_session_end(GameStats *stats, const char *end_reason) { (void)end_reason; } +void analytics_stash_stats(GameStats *stats) { + (void)stats; +} + #endif /* __EMSCRIPTEN__ */ diff --git a/src/game/analytics.h b/src/game/analytics.h index cc55822..df8b12b 100644 --- a/src/game/analytics.h +++ b/src/game/analytics.h @@ -15,4 +15,8 @@ void analytics_session_start(void); * end_reason: "death", "quit", "timeout", or "completed". */ void analytics_session_end(GameStats *stats, const char *end_reason); +/* Stash current stats so the beforeunload fallback has up-to-date data + * if the user closes the tab mid-session. Call periodically. */ +void analytics_stash_stats(GameStats *stats); + #endif /* JNR_ANALYTICS_H */ diff --git a/src/main.c b/src/main.c index a718758..ac45873 100644 --- a/src/main.c +++ b/src/main.c @@ -578,9 +578,10 @@ static void game_update(float dt) { level_update(&s_level, dt); - /* Accumulate play time */ + /* Accumulate play time and keep the beforeunload fallback current. */ if (s_session_active) { s_stats.time_elapsed += dt; + analytics_stash_stats(&s_stats); } /* Check for level exit transition */