78 lines
2.3 KiB
PHP
78 lines
2.3 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* สาธารณะ (อ่านอย่างเดียว) — กระดานผู้นำ High Score
|
|
* GET ?limit=50&playerKey=<optional>
|
|
* คืน { ok, total, top: [ { rank, name, score, coins } ], me?: { rank, name, score } }
|
|
* จัดอันดับจากค่า score สะสม (ไม่ลดเมื่อใช้เหรียญ)
|
|
*/
|
|
require __DIR__ . '/_common.php';
|
|
|
|
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
|
|
json_response(['ok' => false, 'error' => 'Use GET'], 405);
|
|
}
|
|
|
|
$limit = (int) ($_GET['limit'] ?? 50);
|
|
if ($limit < 1) $limit = 1;
|
|
if ($limit > 200) $limit = 200;
|
|
|
|
$caseId = preg_replace('/[^0-9]/', '', (string) ($_GET['caseId'] ?? ''));
|
|
|
|
$store = read_store();
|
|
$accounts = (isset($store['accounts']) && is_array($store['accounts'])) ? $store['accounts'] : [];
|
|
|
|
$rows = [];
|
|
foreach ($accounts as $a) {
|
|
if ($caseId !== '') {
|
|
$score = max(0, (int) (($a['scoreByCase'][$caseId] ?? 0)));
|
|
} else {
|
|
$score = max(0, (int) ($a['score'] ?? 0));
|
|
}
|
|
if ($score <= 0) {
|
|
continue;
|
|
}
|
|
$name = trim((string) ($a['lbName'] ?? ''));
|
|
if ($name === '') $name = trim((string) ($a['displayName'] ?? ''));
|
|
if ($name === '' || $name === 'Guest') $name = 'ผู้เล่น';
|
|
$rows[] = [
|
|
'name' => $name,
|
|
'score' => $score,
|
|
'coins' => max(0, (int) ($a['coins'] ?? 0)),
|
|
'key' => (string) ($a['providerUserId'] ?? ''),
|
|
];
|
|
}
|
|
|
|
usort($rows, function ($x, $y) {
|
|
if ($y['score'] !== $x['score']) {
|
|
return $y['score'] - $x['score'];
|
|
}
|
|
return strcmp((string) $x['name'], (string) $y['name']);
|
|
});
|
|
|
|
$total = count($rows);
|
|
|
|
$me = null;
|
|
$myKey = trim((string) ($_GET['playerKey'] ?? ''));
|
|
if ($myKey !== '') {
|
|
for ($i = 0; $i < $total; $i++) {
|
|
if ($rows[$i]['key'] === $myKey) {
|
|
$me = ['rank' => $i + 1, 'name' => $rows[$i]['name'], 'score' => $rows[$i]['score'], 'coins' => $rows[$i]['coins']];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
$top = [];
|
|
$n = min($limit, $total);
|
|
for ($i = 0; $i < $n; $i++) {
|
|
$top[] = [
|
|
'rank' => $i + 1,
|
|
'name' => $rows[$i]['name'],
|
|
'score' => $rows[$i]['score'],
|
|
'coins' => $rows[$i]['coins'],
|
|
];
|
|
}
|
|
|
|
json_response(['ok' => true, 'total' => $total, 'top' => $top, 'me' => $me]);
|