SpreadQuiz/class/Tasks/SingleChoiceTask.php
2025-09-30 22:44:06 +02:00

85 lines
2.2 KiB
PHP

<?php
require_once "PicturedTask.php";
class SingleChoiceTask extends PicturedTask
{
private array $answers; // possible answers
// -----------------
function __construct(array $a = null)
{
parent::__construct("singlechoice", $a);
$this->answers = $a["answers"] ?? [];
$ca = $a["correct_answer"] ?? -1;
if (gettype($ca) === "string") { // backward compatibility
$this->correct_answer = array_search($a["correct_answer"], $this->answers);
} else {
$this->correct_answer = (int)($ca);
}
$this->player_answer = $a["player_answer"] ?? -1;
}
function addAnswer(string $answer): void
{
$this->answers[] = $answer;
}
function getAnswers(): array
{
return $this->answers;
}
private function isAnswerIdInsideBounds($ansid): bool
{
return ($ansid >= 0) && ($ansid <= count($this->answers));
}
function saveAnswer(mixed $ans): bool
{
$ansidx = (int)($ans); // cast answer to integer as it is a number
if ($this->isAnswerIdInsideBounds($ansidx)) {
$this->player_answer = $ansidx;
return true;
}
return false;
}
function clearAnswer(): void
{
$this->player_answer = -1;
}
public function getMark(): float
{
return ($this->player_answer == $this->correct_answer) ? 1.0 : 0.0;
}
function toArray(): array
{
$a = parent::toArray();
$a["answers"] = $this->answers;
$a["correct_answer"] = $this->correct_answer;
return $a;
}
function randomize(): void{
$ordering = range(0, count($this->answers) - 1); // create an ordered range
shuffle($ordering); // shuffle indices
$shans = [];
$ca_remapped = false; // avoid remapping the correct answer multiple times
for ($i = 0; $i < count($this->answers); $i++) { // shuffle answers
$orig_pos = $ordering[$i];
$shans[] = $this->answers[$orig_pos];
if ((!$ca_remapped) && ($orig_pos == $this->correct_answer)) {
$this->correct_answer = $i;
$ca_remapped = true;
}
}
$this->answers = $shans;
}
}