SpreadQuiz/class/Tasks/TruthTableTask.php
2025-10-11 20:38:20 +02:00

93 lines
2.6 KiB
PHP

<?php
require_once "OpenEndedTask.php";
require_once "class/LogicFunction.php";
require_once "class/Utils.php";
class TruthTableTask extends PicturedTask
{
private LogicFunction $lf; // logic functions
private string $output_variable; // output variable
public function __construct(array $a = null)
{
parent::__construct("truthtable", $a);
if (isset($a["function"])) { // fetching from a JSON-stored object
$this->lf = LogicFunction::fromArray($a["function"]);
} else if (isset($a["expression"], $a["input_variables"])) { // building from the scratch
$this->lf = new LogicFunction($a["expression"], $a["input_variables"]);
} else {
$this->lf = new LogicFunction();
}
$this->setOutputVariable($a["output_variable"] ?? "f");
}
public function staticCheck(): void
{
$ans_tt = $this->player_answer;
$cans_tt = $this->lf->getTruthTable();
$errs = 0;
for ($i = 0; $i < $this->lf->getNStates(); $i++) {
if (($ans_tt[$i] ?? " ") != $cans_tt[$i]) {
$errs++;
}
}
$mark = ($errs === 0) ? 1.0 : 0.0;
$this->setMark($mark);
}
public function setOutputVariable(string $ovar): void {
$this->output_variable = $ovar;
}
public function getOutputVariable(): string {
return $this->output_variable;
}
public function setLogicFunction(LogicFunction $lf): void {
$this->lf = $lf;
}
public function getLogicFunction(): LogicFunction {
return $this->lf;
}
public function getLogicFunctionExpr(string $fmt = "verilog_bitwise"): string {
return $this->lf->getExpression($fmt);
}
public function getLogicFunctionDNF(): string {
return $this->lf->toDNF();
}
public function toArray(string $mode = "all"): array
{
$a = parent::toArray($mode);
if ($mode === "all") {
$a["function"] = $this->lf->toArray();
}
$a["correct_answer"] = $this->lf->getTruthTable();
$a["input_variables"] = $this->lf->getInputVars();
$a["output_variable"] = $this->output_variable;
return $a;
}
public function randomize(): void
{
if ($this->hasFlag("drawnetwork")) {
$svg_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid("truthtable_") . ".svg";
$this->lf->drawNetwork($svg_file);
$this->setImageData(file_get_contents($svg_file) ?? "");
$this->setImageType("svg");
@unlink($svg_file);
}
parent::randomize();
}
}