prepare("SELECT * FROM sp_games WHERE user_id=? AND game='guess' AND status='active' ORDER BY id DESC LIMIT 1"); $s->execute([$uid]); return $s->fetch() ?: null; } function guess_new(int $uid): array { $st = json_encode(['n' => random_int(1, 100), 'tries' => 0, 'log' => []]); $now = time(); db()->prepare("INSERT INTO sp_games (game,user_id,state,created_at,updated_at) VALUES ('guess',?,?,?,?)")->execute([$uid, $st, $now, $now]); return guess_load($uid); } $msg = ''; $done = false; $g = guess_load((int)$me['id']); if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_csrf(); if (($_POST['act'] ?? '') === 'new') { if ($g) db()->prepare("UPDATE sp_games SET status='abandoned' WHERE id=?")->execute([$g['id']]); $g = guess_new((int)$me['id']); $msg = 'New game! Guess a number between 1 and 100.'; } else { if (!$g) $g = guess_new((int)$me['id']); $st = json_decode($g['state'], true); $gv = (int)($_POST['guess'] ?? 0); if ($gv < 1 || $gv > 100) { $msg = 'Enter a number from 1 to 100.'; } else { $st['tries']++; $st['log'][] = $gv; if ($gv === (int)$st['n']) { $score = max(1, 110 - 10 * (int)$st['tries']); db()->prepare("UPDATE sp_games SET status='won', state=?, updated_at=? WHERE id=?") ->execute([json_encode($st), time(), $g['id']]); db()->prepare("INSERT INTO scores (game,user_id,score,detail,created_at) VALUES ('guess',?,?,?,?)") ->execute([$me['id'], $score, $st['tries'] . ' tries', time()]); $msg = "Correct! $gv was the number, in {$st['tries']} tries. Score: $score"; $done = true; $g = null; } else { $msg = $gv . ' is too ' . ($gv < (int)$st['n'] ? 'LOW' : 'HIGH') . '. Tries: ' . $st['tries']; db()->prepare("UPDATE sp_games SET state=?, updated_at=? WHERE id=?") ->execute([json_encode($st), time(), $g['id']]); $g['state'] = json_encode($st); } } } } page_start('Guess the Number', ['back' => '/games.php']); if ($msg) p_para($msg); if ($g) { $st = json_decode($g['state'], true); if ($st['log']) p_para('Previous: ' . implode(', ', array_slice($st['log'], -8))); p_form('/games/guess.php', [ ['name' => 'guess', 'label' => 'Your guess (1-100)', 'maxlength' => 3, 'format' => '*N'], ], 'Guess'); } else { if (!$done) p_para('Guess the secret number between 1 and 100. Fewer tries = more points.'); } p_form('/games/guess.php', [ ['name' => 'act', 'type' => 'hidden', 'value' => 'new'], ], $g ? 'Restart' : 'New game'); p_links([['/games/scores.php', 'High scores', ['g' => 'guess']], ['/games.php', 'Games']]); page_end();