-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
151 lines (127 loc) · 4.33 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const questions = [
{
question: "Как называется самое глубокое место на Земле?",
answers: [
"Бермудский треугольник",
"Марианская впадина",
"Мертвое море",
"Тихоокеанский желоб"
],
correct: 2,
},
{
question: "Кто такой кукусик?",
answers: [
"Название семечек",
"Маменькин сынок",
"Гражданин похожий на гопника",
"кукус-пупус, только ещё маленький",
],
correct: 2,
},
{
question: "Как называется художественный стиль, связанный с Сальвадором Дали?",
answers: [
"Кубизм",
"Реализм",
"Сюрреализм",
"Абстракционизм",
],
correct: 3,
},
{
question: "Какая планета в Солнечной системе самая большая?",
answers: ["Земля", "Венера", "Юпитер", "Сатурн"],
correct: 3,
},
];
// Находим элементы
const headerContainer = document.querySelector('#header');
const listContainer = document.querySelector('#list');
const submitBtn = document.querySelector('#submit');
// Переменные игры
let score = 0; // кол-во правильных ответов
let questionIndex = 0; // текущий вопрос
clearPage();
showQuestion();
submitBtn.onclick = checkAnswer;
function clearPage() {
headerContainer.innerHTML = '';
listContainer.innerHTML = '';
}
function showQuestion() {
// Вопрос
const headerTemplate = `<h2 class="title">%title%</h2>`;
const title = headerTemplate.replace('%title%', questions[questionIndex]['question']);
headerContainer.innerHTML = title;
// Варианты ответов
let answerNumber = 1;
for (answerText of questions[questionIndex]['answers']) {
const questionTemplate =
`<li>
<label>
<input value="%number%" type="radio" class="answer" name="answer" />
<span>%answer%</span>
</label>
</li>`;
const answerHTML = questionTemplate.replace('%answer%', answerText).replace('%number%', answerNumber);
listContainer.innerHTML += answerHTML;
answerNumber++;
}
}
function checkAnswer() {
// Находим выбранную радио кнопку
const checkedRadio = listContainer.querySelector('input[type="radio"]:checked');
console.log(checkedRadio);
// Если ответ не выбран - ничего не делаем, выходим из функции
if (!checkedRadio) {
submitBtn.blur();
return;
}
// Узнаём номер ответа пользоваеля
const userAnswer = parseInt(checkedRadio.value);
// Если ответил верно - увеличиваем счёт
if (userAnswer === questions[questionIndex]['correct']) {
score++
}
if (questionIndex !== questions.length - 1) {
questionIndex++;
clearPage();
showQuestion();
return;
} else {
clearPage();
showResults();
}
}
function showResults() {
const resultsTemplate = `
<h2 class="title">%title%</h2>
<h3 class="summary">%message%</h3>
<p class="result">%result%</p>
`;
let title, message;
// Варианты заголовков и текста
if (score === questions.length) {
title = 'Мои поздравления! 🎉';
message = 'Вы молодец, ответили на все вопросы правильно! 😎💪👍';
} else if ((score * 100) / questions.length >= 50) {
title = 'Хороший результат! 😜';
message = 'У Вас больше половины правильных ответов 🧐👍👀';
} else {
title = 'Уверен, Вы можете лучше! 🤨😱';
message = 'У Вас меньше половины правильных ответов 👶';
}
// Результат
let result = `${score} из ${questions.length}`;
// Финальный ответ, подставляем данные в шаблон
const finalMessage = resultsTemplate
.replace('%title%', title)
.replace('%message%', message)
.replace('%result%', result);
headerContainer.innerHTML = finalMessage;
// Меняем кнопку на "Играть снова"
submitBtn.blur();
submitBtn.innerText = 'Начать заново';
submitBtn.onclick = () => history.go();
}