PHP Trivia Game - Day 1
Here is an updated version of the trivia game code. I’ve added some code make the game completely playable and to keep track of score. Look for “new!” in comments below to see what has changed.
You can also play the game itself on this website!
/web/www/index.php
Unchanged from the starter code!
/web/src/trivia/TriviaController.php
Our updated controller!
<?php
class TriviaController {
private $questions = [];
private $db;
private $errorMessage = "";
/**
* Constructor
*/
public function __construct($input) {
// Start the session! (new!)
session_start();
$this->input = $input;
$this->loadQuestions();
// Start score at 0 if no session (new!)
$_SESSION["score"] = 0;
}
/**
* Run the server
*
* Given the input (usually $_GET), then it will determine
* which command to execute based on the given "command"
* parameter. Default is the welcome page.
*/
public function run() {
// Get the command
$command = "question";
if (isset($this->input["command"]))
$command = $this->input["command"];
switch($command) {
case "login": // new!
// TODO: maybe we should check name/email?
break;
case "answer":
$this->answerQuestion();
break;
case "logout": // new!
$this->logout(); // notice no break (new!)
case "question":
default:
$this->showQuestion();
break;
}
}
/**
* Logout function. We **need** to clear the session somehow.
* When the user wants to start over, we should allow them to
* reset the game. I'll call it logout, so this function destroys
* the session and immediately starts a new one. (new!)
*/
public function logout() {
// Destroy the session
session_destroy();
// Start a new session. Why? We want to show the next question.
session_start();
$_SESSION["score"] = 0;
}
/**
* Load questions from a file, store them as an array
* in the current object.
*/
public function loadQuestions() {
$this->questions = json_decode(file_get_contents("/opt/src/trivia/data/trivia-s25.json"), true);
}
/**
* Our getQuestion function, now as a method!
*/
function getQuestion($id = null) {
// Todo: Think about how to change this function to get
// the qid from the session rather than needing the id
// passed in. Would this be better?
if ($id == null) {
$randid = array_rand($this->questions);
// Add the question ID to the session (new!)
$_SESSION["qid"] = $randid;
return array_merge(["id"=>$randid], $this->questions[$randid]);
}
return array_merge(["id"=>$id], $this->questions[$id]);
}
/**
* Show a question to the user. This function loads a
* template PHP file and displays it to the user based on
* properties of this object.
*/
public function showQuestion($message = "") {
$question = $this->getQuestion();
$score = $_SESSION["score"]; // score variable, make the template easier to read (new!)
include("/opt/src/trivia/templates/question.php");
}
/**
* Check the user's answer to a question.
*/
public function answerQuestion() {
$message = "";
if (isset($_POST["answer"]) && isset($_POST["qid"]) && is_numeric($_POST["qid"])) {
$question = $this->getQuestion($_POST["qid"]);
if (strtolower(trim($_POST["answer"])) == strtolower($question["answer"])) {
$message = "<div class=\"alert alert-success\" role=\"alert\">
Correct!
</div>";
// Remove the question ID from the session (new!)
unset($_SESSION["qid"]);
// Update the user's score (new!)
$_SESSION["score"] += 10; // + 10 points!
}
else {
$message = "<div class=\"alert alert-danger\" role=\"alert\">
Incorrect!
</div>";
}
}
$this->showQuestion($message);
}
}
/web/src/trivia/templates/question.php
Our view
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="CS4640 Spring 2025">
<meta name="description" content="Our Front-Controller Trivia Game">
<title>PHP Form Example - Trivia</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 15px;">
<div class="row">
<div class="col-xs-12">
<h1>Trivia Game</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<?=$message?>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="card">
<div class="card-header">
Question
</div>
<div class="card-body">
<h5 class="card-title"><?=$question["question"]?></h5>
</div>
</div>
<div class="m-4">
<form action="?command=answer" method="post">
<input type="hidden" name="qid" value="<?=$question["id"]?>">
<div class="mb-3">
<label for="answer" class="form-label">Trivia Answer: </label>
<input type="text" class="form-control" id="trivia-answer" name="answer">
</div>
<button type="submit" class="btn btn-primary">Submit Answer</button>
<a href="?command=logout" class="btn btn-danger">End Game</a>
</form>
</div>
</div>
<div class="col-4">
<div class="card">
<div class="card-header">
Game Info
</div>
<div class="card-body">
<p class="card-text">Score: <?=$score?></p> <!-- new! -->
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>
</html>
/web/src/trivia/data/trivia-s25.json
Unchanged from starter code!