prepare("SELECT * FROM sp_games WHERE user_id=? AND game='quiz' AND status='active' ORDER BY id DESC LIMIT 1"); $s->execute([$uid]); return $s->fetch() ?: null; } $msg = ''; $g = quiz_load((int)$me['id']); if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_csrf(); $act = $_POST['act'] ?? ''; if ($act === 'new' || !$g) { if ($g) db()->prepare("UPDATE sp_games SET status='abandoned' WHERE id=?")->execute([$g['id']]); $keys = array_keys($QUESTIONS); shuffle($keys); $keys = array_slice($keys, 0, 5); $st = json_encode(['q' => $keys, 'i' => 0, 'right' => 0]); $now = time(); db()->prepare("INSERT INTO sp_games (game,user_id,state,created_at,updated_at) VALUES ('quiz',?,?,?,?)")->execute([$me['id'], $st, $now, $now]); $g = quiz_load((int)$me['id']); $msg = 'New quiz: 5 questions.'; } elseif ($act === 'ans') { $st = json_decode($g['state'], true); $qi = $QUESTIONS[$st['q'][$st['i']]]; $pick = (int)($_POST['a'] ?? -1); if ($pick === (int)$qi[2]) { $st['right']++; $msg = 'Correct!'; } else $msg = 'Wrong - it was: ' . $qi[1][$qi[2]]; $st['i']++; if ($st['i'] >= count($st['q'])) { $score = $st['right'] * 20; db()->prepare("UPDATE sp_games SET status='done', 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 ('quiz',?,?,?,?)") ->execute([$me['id'], $score, $st['right'] . '/5', time()]); $msg .= ' Quiz over: ' . $st['right'] . '/5 correct, score ' . $score . '.'; $g = null; } else { 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('Quick Quiz', ['back' => '/games.php']); if ($msg) p_para($msg); if ($g) { $st = json_decode($g['state'], true); $qi = $QUESTIONS[$st['q'][$st['i']]]; p_para('Q' . ($st['i'] + 1) . '/' . count($st['q']) . ': ' . $qi[0]); $opts = []; foreach ($qi[1] as $k => $lab) $opts[(string)$k] = $lab; p_form('/games/quiz.php', [ ['name' => 'act', 'type' => 'hidden', 'value' => 'ans'], ['name' => 'a', 'label' => 'Answer', 'type' => 'select', 'options' => $opts], ], 'Answer'); } else { p_para('A short quiz about WAP and mobile history. 20 points per correct answer.'); p_form('/games/quiz.php', [['name' => 'act', 'type' => 'hidden', 'value' => 'new']], 'Start quiz'); } p_links([['/games/scores.php', 'High scores', ['g' => 'quiz']], ['/games.php', 'Games']]); page_end();