39315-vm/api/leaderboard.php
2026-03-25 15:17:29 +00:00

43 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../tetris_data.php';
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
function tetrisApiScoreRow(array $run): array
{
$timestamp = strtotime((string) ($run['created_at'] ?? ''));
return [
'id' => (int) ($run['id'] ?? 0),
'player_name' => (string) ($run['player_name'] ?? ''),
'score' => (int) ($run['score'] ?? 0),
'lines_cleared' => (int) ($run['lines_cleared'] ?? 0),
'level_reached' => (int) ($run['level_reached'] ?? 1),
'duration_seconds' => (int) ($run['duration_seconds'] ?? 0),
'created_at_iso' => $timestamp ? gmdate(DATE_ATOM, $timestamp) : null,
];
}
try {
$leaderboard = array_map('tetrisApiScoreRow', tetrisFetchLeaderboard(8));
$recentRuns = array_map('tetrisApiScoreRow', tetrisFetchRecent(5));
$bestRun = tetrisFetchBestScore();
echo json_encode([
'success' => true,
'updated_at' => gmdate(DATE_ATOM),
'best_run' => $bestRun ? tetrisApiScoreRow($bestRun) : null,
'leaderboard' => $leaderboard,
'recent_runs' => $recentRuns,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Unable to load leaderboard right now.',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}