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