fork download
  1. <?php
  2.  
  3.  
  4. abstract class Question
  5. {
  6. protected $text;
  7. protected $points;
  8. protected $correctAnswer;
  9. protected $hint;
  10.  
  11. abstract function getAsString(): string;
  12. abstract function checkAnswer($answer): array;
  13.  
  14. // Возвращает вопрос
  15. public function getQuestionText(): string
  16. {
  17. $text = $this->text;
  18. return $text;
  19. }
  20.  
  21. // Возвращает количество баллов за правильный ответ
  22. public function getPoints(): int
  23. {
  24. $points = $this->points;
  25. return $points;
  26. }
  27.  
  28. // Возвращает подсказку
  29. public function getQuestionHint(): string
  30. {
  31. $hint = $this->hint;
  32. return $hint;
  33. }
  34. }
  35.  
  36. class MultipleChoiceQuestion extends Question
  37. {
  38. protected $answers;
  39. protected $almostCorrectAnswer;
  40.  
  41. public function __construct(string $text, float $points, array $answers, string $correctAnswer, string $hint)
  42. {
  43. $this->text = $text;
  44. $this->points = $points;
  45. $this->answers = $answers;
  46. $this->correctAnswer = $correctAnswer;
  47. $this->hint = $hint;
  48. }
  49.  
  50. // Функция добавляющая почти корректный ответ
  51. public function addAlmostCorrectAnswer($almostCorrectAnswer)
  52. {
  53. $this->almostCorrectAnswer = $almostCorrectAnswer;
  54. }
  55.  
  56. // Функция отдающая строку со списком вопросов
  57. public function getAsString(): string
  58. {
  59. $string = "{$this->text}\nВарианты ответов:\n";
  60.  
  61. foreach ($this->answers as $letter => $answer) {
  62. $string = $string."{$letter}. {$answer}\n";
  63. }
  64.  
  65. return $string;
  66. }
  67.  
  68. /* Функция получает на вход ответ.
  69. Проверяет его, учитывая почти правильный вариант ответа.
  70. Возвращает в массиве результаты проверки */
  71.  
  72. public function checkAnswer($answer): array
  73. {
  74. $isCorrect = 0;
  75. $isAlmostCorrect = 0;
  76.  
  77. if ($answer == $this->correctAnswer) {
  78. $isCorrect = 1;
  79. } elseif ($answer == $this->almostCorrectAnswer) {
  80. $isAlmostCorrect = 1;
  81. }
  82.  
  83. return array($isCorrect, $isAlmostCorrect);
  84. }
  85.  
  86. }
  87.  
  88. class NumericalQuestion extends Question
  89. {
  90. protected $deviation;
  91.  
  92. function __construct(string $text, string $hint, float $points, float $correctAnswer, float $deviation = 0)
  93. {
  94. $this->text = $text;
  95. $this->points = $points;
  96. $this->correctAnswer = $correctAnswer;
  97. $this->deviation = $deviation;
  98. $this->hint = $hint;
  99. }
  100.  
  101. // Функция возвращает строку со списком вопросов
  102. public function getAsString(): string
  103. {
  104. return "{$this->text}\n";
  105. }
  106.  
  107. /* Функция получает ответ. Проверяет его с учетом возможного отклонения.
  108. Возвращает в массиве результат проверки. */
  109.  
  110. public function checkAnswer($answer): array
  111. {
  112. $isCorrect = 0;
  113.  
  114. if ($answer == $this->correctAnswer or $this->deviation > abs($this->correctAnswer - $answer)) {
  115. $isCorrect = 1;
  116. }
  117.  
  118. return array($isCorrect, $isAlmostCorrect = 0);
  119. }
  120.  
  121. }
  122.  
  123. // Функция создающая массив с вопросами
  124. function createQuestions() {
  125.  
  126. $questions = [];
  127.  
  128. $text = 'Какая планета располагается четвертой по счету от Солнца?';
  129. $answers = array('a' => 'Венера', 'b' => 'Марс', 'c' => 'Юпитер', 'd' => 'Меркурий');
  130. $hint = 'Одноименное название носит шоколадный батончик.';
  131. $q = new MultipleChoiceQuestion($text, 10, $answers, 'b', $hint);
  132.  
  133. $questions[] = $q;
  134.  
  135. $text = 'Какой город является столицей Великобритании?';
  136. $answers = array('a' => 'Париж', 'b' => 'Москва', 'c' => 'Нью-Йорк', 'd' => 'Лондон');
  137. $hint = '%Городнейм% из кэпитал оф грейт британ.';
  138. $q = new MultipleChoiceQuestion($text, 5, $answers, 'd', $hint);
  139.  
  140. $questions[] = $q;
  141.  
  142. $text = 'Кто придумал теорию относительности?';
  143. $answers = array('a' => 'Джон Леннон', 'b' => 'Джим Моррисон', 'c' => 'Альберт Эйнштейн', 'd' => 'Исаак Ньютон');
  144. $hint = 'Этим парнем был...';
  145. $q = new MultipleChoiceQuestion($text, 30, $answers, 'c', $hint);
  146. $q->addAlmostCorrectAnswer('b');
  147.  
  148. $questions[] = $q;
  149.  
  150. $hint = 'Попробуй еще раз, дружок-пирожок!';
  151. $q = new NumericalQuestion('Чему равна скорость света в км/с?', $hint, 15, 299792, 210);
  152.  
  153. $questions[] = $q;
  154.  
  155. $hint = 'Между 2 и 4, подумой.';
  156. $q = new NumericalQuestion('Чему равно число Пи?', $hint, 30, 3.14, 0.01);
  157.  
  158. $questions[] = $q;
  159.  
  160. $hint = 'Сычёв, ты отчислен!';
  161. $q = new NumericalQuestion('В каком году закончилась вторая мировая война?', $hint, 10, 1945);
  162.  
  163. $questions[] = $q;
  164.  
  165. return $questions;
  166. }
  167.  
  168. // Функция выводящая список вопросов с вариантами ответов
  169. function printQuestions($questions) {
  170.  
  171. $number = 1;
  172.  
  173. foreach ($questions as $question) {
  174. echo "\n{$number}. ";
  175. echo $question->getAsString();
  176.  
  177. $number ++;
  178. }
  179.  
  180. }
  181.  
  182. /* Функция получает массивы вопросов и ответов. Проверяет ответы,
  183. считает число баллов и печатает вопросы на которые был дан неправильный ответ. */
  184.  
  185. function checkAnswers($questions, $answers)
  186. {
  187. if (count($questions) != count($answers)) {
  188. die("Число ответов и вопросов не совпадает\n");
  189. }
  190.  
  191. $pointsTotal = 0;
  192. $pointsMax = 0;
  193. $correctAnswers = 0;
  194.  
  195. $totalQuestions = count($questions);
  196.  
  197. for ($i = 0; $i < count($questions); $i++) {
  198.  
  199. $question = $questions[$i];
  200. $answer = $answers[$i];
  201.  
  202. list($isCorrect, $isAlmostCorrect) = $question->checkAnswer($answer);
  203. $points = $question->getPoints();
  204.  
  205. $pointsMax += $points;
  206.  
  207. if ($isCorrect) {
  208.  
  209. $correctAnswers ++;
  210. $pointsTotal += $points;
  211.  
  212. } elseif ($isAlmostCorrect) {
  213.  
  214. $correctAnswers ++;
  215. $pointsTotal += $points / 2;
  216.  
  217. } else {
  218.  
  219. $number = $i + 1;
  220. echo "\nНеправильный ответ на вопрос №{$number} ({$question->getQuestionText()})\n";
  221. echo "\nПодсказка: {$question->getQuestionHint()}\n";
  222.  
  223. }
  224.  
  225. }
  226.  
  227. echo "\nПравильных ответов: {$correctAnswers} из {$totalQuestions}, баллов набрано: $pointsTotal из $pointsMax\n";
  228. }
  229.  
  230. $questions = createQuestions();
  231. printQuestions($questions);
  232. checkAnswers($questions, array('b', 'd', 'b', 299792, 3.14444, 1944));
Success #stdin #stdout 0s 82560KB
stdin
Standard input is empty
stdout
1. Какая планета располагается четвертой по счету от Солнца?
Варианты ответов:
a. Венера
b. Марс
c. Юпитер
d. Меркурий

2. Какой город является столицей Великобритании?
Варианты ответов:
a. Париж
b. Москва
c. Нью-Йорк
d. Лондон

3. Кто придумал теорию относительности?
Варианты ответов:
a. Джон Леннон
b. Джим Моррисон
c. Альберт Эйнштейн
d. Исаак Ньютон

4. Чему равна скорость света в км/с?

5. Чему равно число Пи?

6. В каком году закончилась вторая мировая война?

Неправильный ответ на вопрос №6 (В каком году закончилась вторая мировая война?)

Подсказка: Сычёв, ты отчислен!

Правильных ответов: 5 из 6, баллов набрано: 75 из 100