-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
294 lines (257 loc) · 12.6 KB
/
Copy pathindex.html
File metadata and controls
294 lines (257 loc) · 12.6 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Бесконечный таймер цветов (контроль повторов)</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
font-family: sans-serif;
background-color: #808080;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
#setup-ui {
text-align: center;
background: white;
padding: 25px 30px;
border-radius: 16px;
box-shadow: 0 10px 25px rgba(0,0,0,0.3);
z-index: 10;
}
.input-group {
display: flex;
flex-direction: column;
gap: 15px;
margin-bottom: 20px;
}
.field {
display: flex;
justify-content: space-between;
align-items: center;
gap: 15px;
}
.field label {
font-size: 16px;
font-weight: 500;
}
input {
padding: 10px;
font-size: 18px;
width: 90px;
border: 1px solid #aaa;
border-radius: 8px;
text-align: center;
}
button.start-btn {
padding: 12px 30px;
font-size: 20px;
font-weight: bold;
cursor: pointer;
background-color: #27ae60;
color: white;
border: none;
border-radius: 40px;
box-shadow: 0 4px 0 #1e7e4a;
transition: 0.1s ease;
}
button.start-btn:hover {
background-color: #2ecc71;
transform: translateY(-2px);
box-shadow: 0 6px 0 #1e7e4a;
}
button.start-btn:active {
transform: translateY(2px);
box-shadow: 0 2px 0 #1e7e4a;
}
/* Полноэкранный слой */
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: none;
justify-content: center;
align-items: center;
z-index: 100;
}
#countdown-text {
font-size: 15rem;
font-weight: bold;
color: black;
user-select: none;
text-shadow: 2px 2px 8px rgba(255,255,255,0.5);
}
/* Кнопка Стоп в углу */
#stop-btn {
position: absolute;
top: 20px;
right: 20px;
padding: 10px 20px;
background: rgba(0, 0, 0, 0.6);
color: white;
border: 2px solid white;
border-radius: 40px;
cursor: pointer;
font-size: 18px;
font-weight: bold;
z-index: 101;
backdrop-filter: blur(4px);
transition: 0.2s;
}
#stop-btn:hover {
background: rgba(220, 20, 60, 0.9);
transform: scale(1.05);
}
</style>
</head>
<body>
<div id="setup-ui">
<h2>⚙️ Настройки таймера</h2>
<div class="input-group">
<div class="field">
<label>⏱️ Секунд на цвет:</label>
<input type="number" id="seconds-input" min="1" value="5">
</div>
<div class="field">
<label>🔁 Макс. повторов цвета:</label>
<input type="number" id="repeat-limit-input" min="1" value="2" title="Сколько раз подряд может появиться один и тот же цвет">
</div>
</div>
<button class="start-btn" onclick="startInfiniteCycle()">▶ Старт!</button>
</div>
<div id="overlay">
<button id="stop-btn" onclick="stopEverything()">⏹ СТОП</button>
<div id="countdown-text">0</div>
</div>
<script>
(function() {
const colors = ['red', 'blue', 'green', 'yellow'];
const overlay = document.getElementById('overlay');
const countdownText = document.getElementById('countdown-text');
const secondsInput = document.getElementById('seconds-input');
const repeatLimitInput = document.getElementById('repeat-limit-input');
let timerInterval;
let globalSeconds = 5; // базовые секунды
let maxConsecutive = 2; // лимит повторов (по умолчанию)
// Состояние для отслеживания повторов
let lastColor = null; // предыдущий цвет (строка)
let consecutiveCount = 0; // сколько раз подряд он встретился
// Функция выбора цвета с учётом лимита повторений
function pickColorAvoidingRepeat() {
// Если лимит не задан или меньше 1, то просто случайный (без ограничений)
const limit = (maxConsecutive >= 1) ? maxConsecutive : 1;
// Если последний цвет не задан (первый запуск) — просто случайный
if (lastColor === null) {
const randomIndex = Math.floor(Math.random() * colors.length);
lastColor = colors[randomIndex];
consecutiveCount = 1;
return lastColor;
}
// Проверяем, достигли ли мы лимита для текущего цвета
if (consecutiveCount >= limit) {
// Достигли лимита — нужно выбрать другой цвет (исключаем lastColor)
const otherColors = colors.filter(c => c !== lastColor);
// otherColors не может быть пустым, т.к. colors.length > 1 (минимум 4)
const newColor = otherColors[Math.floor(Math.random() * otherColors.length)];
// Сбрасываем счётчик для нового цвета
lastColor = newColor;
consecutiveCount = 1;
return newColor;
} else {
// Лимит ещё не исчерпан, можно с некоторой вероятностью оставить текущий цвет
// Но чтобы было действительно "максимальное количество идущих подряд",
// мы должны разрешить остаться на том же цвете, но не превысить лимит.
// Случайность: либо остаёмся, либо меняем. При этом нужно следить за лимитом.
// Решение: генерируем случайный цвет из ВСЕХ, но если выпал тот же самый, проверяем лимит.
// Если выпал тот же и лимит позволяет — берём его. Если лимит будет превышен — пробуем снова.
// Упростим: будем выбирать случайный цвет, но если выбран тот же самый и лимит будет превышен (consecutiveCount+1 > limit),
// то отбрасываем его и выбираем любой другой.
let attempts = 0;
const maxAttempts = 20; // защита от бесконечного цикла
while (attempts < maxAttempts) {
const candidate = colors[Math.floor(Math.random() * colors.length)];
if (candidate === lastColor) {
// Если кандидат совпадает с предыдущим
if (consecutiveCount + 1 <= limit) {
// Можно использовать, лимит не будет превышен
lastColor = candidate;
consecutiveCount++;
return candidate;
} else {
// Нельзя, пробуем другой цвет
attempts++;
continue;
}
} else {
// Новый цвет
lastColor = candidate;
consecutiveCount = 1;
return candidate;
}
}
// Если по какой-то причине зациклились (например, лимит 1 и всегда выпадает тот же),
// принудительно берём другой цвет
const forcedColor = colors.find(c => c !== lastColor) || colors[0];
lastColor = forcedColor;
consecutiveCount = 1;
return forcedColor;
}
}
function startInfiniteCycle() {
// Считываем значения из полей
const secVal = parseInt(secondsInput.value);
const repeatVal = parseInt(repeatLimitInput.value);
if (isNaN(secVal) || secVal <= 0) {
alert("Введите корректное количество секунд (целое положительное число).");
return;
}
if (isNaN(repeatVal) || repeatVal < 1) {
alert("Максимальное количество повторов должно быть не меньше 1.");
return;
}
globalSeconds = secVal;
maxConsecutive = repeatVal;
// Сброс состояния при каждом новом старте (обнуляем историю цветов)
lastColor = null;
consecutiveCount = 0;
overlay.style.display = 'flex';
runNextCycle();
}
function runNextCycle() {
// Очищаем предыдущий интервал
clearInterval(timerInterval);
// Получаем цвет с учётом логики повторов
const nextColor = pickColorAvoidingRepeat();
overlay.style.backgroundColor = nextColor;
let timeLeft = globalSeconds;
countdownText.innerText = timeLeft;
timerInterval = setInterval(() => {
timeLeft--;
if (timeLeft <= 0) {
// Завершился цикл — запускаем новый (с новым цветом)
runNextCycle();
} else {
countdownText.innerText = timeLeft;
}
}, 1000);
}
function stopEverything() {
clearInterval(timerInterval);
overlay.style.display = 'none';
// Не сбрасываем lastColor и consecutiveCount, но это не важно, т.к. после старта они переинициализируются
}
// Делаем функции глобальными (для onclick)
window.startInfiniteCycle = startInfiniteCycle;
window.stopEverything = stopEverything;
})();
</script>
</body>
</html>