Для обеспечения того, чтобы функция выбора выполнялась корректно с учетом уникального выбора, я внес изменения в функцию выбора, которая обеспечивает, что при активации режима уникального выбора, люди не дублируются до тех пор, пока все группы не будут выбраны. Кроме того, обработка случай, когда все участники в одной категории были выбраны, также была улучшена. Теперь, если группа закончится, программа будет повторно использовать всех участников.
html Copy code
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Рандомайзер намоток</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vanta/0.5.21/vanta.clouds.min.js"></script>
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--error-color: #e74c3c;
--bg-color: rgba(255, 255, 255, 0.9);
--text-color: #333;
--highlight-color: #e8f4fc;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto', sans-serif;
color: var(--text-color);
position: relative;
min-height: 100vh;
overflow-x: hidden;
}
#vanta-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.content {
position: relative;
z-index: 1;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: var(--bg-color);
margin-top: 20px;
margin-bottom: 20px;
display: none;
}
h1 {
text-align: center;
color: #2c3e50;
margin-bottom: 30px;
}
.group-controls {
display: flex;
justify-content: center;
gap: 30px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.group-input-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
background: rgba(255, 255, 255, 0.8);
padding: 15px;
border-radius: 8px;
min-width: 200px;
}
.main-controls {
margin-top: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.dice-container {
display: inline-block;
margin-right: 10px;
}
.dice {
display: inline-block;
font-size: 1.2em;
transition: transform 0.3s;
}
.rotating {
animation: dice-rotate 1s linear infinite;
}
@keyframes dice-rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.groups {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
margin-top: 20px;
}
.group {
flex: 1;
min-width: 300px;
background-color: rgba(255, 255, 255, 0.8);
padding: 15px;
border-radius: 8px;
}
.person {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 5px;
border-bottom: 1px dotted #eee;
}
.counter {
background: var(--secondary-color);
color: white;
padding: 2px 8px;
border-radius: 10px;
font-size: 0.85em;
min-width: 20px;
text-align: center;
}
.controls {
display: flex;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
margin: 20px 0;
}
.secondary-controls {
display: flex;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 10px;
}
button {
background-color: var(--primary-color);
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
transition: transform 0.2s;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
}
button:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.result {
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
border-radius: 8px;
text-align: center;
font-size: 1.2em;
font-weight: bold;
margin: 20px 0;
min-height: 60px;
}
.stats-container {
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
border-radius: 8px;
margin-top: 20px;
}
.stats-container h2 {
margin-top: 0;
color: var(--primary-color);
border-bottom: 2px solid #eee;
padding-bottom: 10px;
margin-bottom: 15px;
}
.stat-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px dotted #eee;
}
@keyframes glow {
0% {
box-shadow: 0 0 5px #ff0000;
}
50% {
box-shadow: 0 0 20px #ff0000;
}
100% {
box-shadow: 0 0 5px #ff0000;
}
}
.glow-effect {
animation: glow 1s infinite;
}
.progress-bar {
height: 5px;
background-color: #e0e0e0;
border-radius: 3px;
margin-top: 10px;
overflow: hidden;
}
.progress {
height: 100%;
background-color: var(--primary-color);
width: 0%;
transition: width 0.1s linear;
}
.input-container {
display: flex;
justify-content: center;
gap: 10px;
margin-bottom: 20px;
}
input[type="number"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
width: 80px;
text-align: center;
}
.autoplay-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.9);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
color: white;
font-size: 1.5em;
text-align: center;
flex-direction: column;
}
.click-to-start {
margin-top: 20px;
padding: 15px 30px;
background-color: var(--primary-color);
border-radius: 5px;
cursor: pointer;
transition: transform 0.2s;
}
.click-to-start:hover {
transform: scale(1.05);
}
.audio-controls {
position: fixed;
bottom: 20px;
right: 20px;
display: flex;
gap: 10px;
align-items: center;
background-color: rgba(255, 255, 255, 0.8);
padding: 10px;
border-radius: 5px;
z-index: 100;
}
.audio-controls button {
padding: 5px 10px;
font-size: 0.8em;
}
.audio-controls input[type="range"] {
width: 100px;
}
.unique-toggle {
display: flex;
align-items: center;
gap: 10px;
margin: 10px;
}
</style>
</head>
<body>
<div id="vanta-bg"></div>
<div class="content" id="main-content">
<h1>
<span class="dice-container">
<span class="dice">🎲</span>
</span>
Рандомайзер намоток
</h1>
<div class="group-controls">
<div class="group-input-container">
<h3>👨✈️ Старший призыв</h3>
<input type="number" id="senior-count" min="1" max="10" value="1">
<button class="group-random-btn" data-group="senior">🎲 Выбрать</button>
</div>
<div class="group-input-container">
<h3>👶 Младший призыв</h3>
<input type="number" id="junior-count" min="1" max="10" value="1">
<button class="group-random-btn" data-group="junior">🎲 Выбрать</button>
</div>
</div>
<div class="main-controls">
<div class="input-container">
<input type="number" id="count-input" min="1" max="20" value="1">
<button id="random-btn" class="group-random-btn">🎲 Выбрать всех</button>
</div>
<div class="result" id="result">Нажмите кнопку "Выбрать"</div>
<div class="unique-toggle">
<label for="unique-selection">Уникальный выбор:</label>
<input type="checkbox" id="unique-selection" checked>
</div>
<div class="progress-bar">
<div class="progress" id="progress"></div>
</div>
<div class="secondary-controls">
<button id="reset-btn">🔄 Сбросить</button>
<button id="export-btn">💾 Экспорт</button>
<button id="import-btn">📂 Импорт</button>
</div>
</div>
<div class="groups">
<div class="group" id="senior-group">
<h2>👨✈️ Старший призыв</h2>
<div id="senior-list"></div>
</div>
<div class="group" id="junior-group">
<h2>👶 Младший призыв</h2>
<div id="junior-list"></div>
</div>
</div>
<div class="stats-container">
<h2>📊 Статистика выборов</h2>
<div id="stats-list"></div>
</div>
</div>
<div class="autoplay-overlay" id="autoplay-overlay">
<div class="click-to-start" id="start-button">ЖМИ, СУКА</div>
</div>
<div class="audio-controls">
<button id="toggle-bg-audio">🔇</button>
<input type="range" id="bg-audio-volume" min="0" max="1" step="0.1" value="0">
<button id="restart-bg-audio">↻</button>
</div>
<script>
class Randomizer {
constructor() {
this.people = {
senior: ["Артем Ш.", "Артем В.", "Олег Щ.", "Дима Г.", "Никита Л.",
"Максим С.", "Леха Д.", "Антон К.", "Арыслан Х.", "Даня Ч."],
junior: ["Витя М.", "Андрей Л.", "Андрей Б.", "Серега Л.", "Дима З.",
"Камиль Х.", "Гриша М.", "Валера Р.", "Влад Я.", "Вова К."]
};
this.audioFiles = {
"Антон К.": "audio/Anton.mp3",
"Арыслан Х.": "audio/Arislan.mp3",
"Вова К.": "audio/Bova.mp3",
"Андрей Б.": "audio/Burminov.mp3",
"Даня Ч.": "audio/Danny.mp3",
"Дима Г.": "audio/Dima.mp3",
"Камиль Х.": "audio/Hasan.mp3",
"Серега Л.": "audio/Lada.mp3",
"Леха Д.": "audio/Lexa.mp3",
"Андрей Л.": "audio/Luhmarev.mp3",
"Гриша М.": "audio/Mahov.mp3",
"Максим С.": "audio/Maks.mp3",
"Никита Л.": "audio/Nikita.mp3",
"Олег Щ.": "audio/Oleg.mp3",
"Валера Р.": "audio/Raev.mp3",
"Артем Ш.": "audio/Shmel.mp3",
"Артем В.": "audio/Vagi.mp3",
"Витя М.": "audio/Vitya.mp3",
"Влад Я.": "audio/Yahaev.mp3",
"Дима З.": "audio/Zikov.mp3"
};
this.loadingAudio = new Audio('audio/Loading.mp3');
this.openingAudio = new Audio('audio/Otkritie.mp3');
this.commonAudio = new Audio('audio/Obshee.mp3');
this.backgroundAudio = new Audio('audio/arm.mp3');
this.backgroundAudio.loop = true;
this.backgroundAudio.volume = 0; // Начинаем с выключенного звука
this.currentAudio = null;
this.isBackgroundAudioPlaying = false;
this.backgroundAudioPausedTime = 0;
this.isMuted = true;
this.stats = {};
this.STORAGE_KEY = 'randomizer_stats_opt_v3';
this.isSelecting = false;
this.uniqueSelectionEnabled = true;
this.selectedPersons = {
senior: [],
junior: []
};
this.diceElement = document.querySelector('.dice');
this.progressElement = document.getElementById('progress');
this.selectDuration = 3000;
this.countInput = document.getElementById('count-input');
this.autoplayOverlay = document.getElementById('autoplay-overlay');
this.startButton = document.getElementById('start-button');
this.mainContent = document.getElementById('main-content');
this.setupAutoplay();
this.setupAudioControls();
}
setupAudioControls() {
const toggleBtn = document.getElementById('toggle-bg-audio');
const volumeControl = document.getElementById('bg-audio-volume');
const restartBtn = document.getElementById('restart-bg-audio');
toggleBtn.addEventListener('click', () => {
this.toggleMute();
toggleBtn.textContent = this.isMuted ? '🔇' : '🔊';
});
volumeControl.addEventListener('input', () => {
this.backgroundAudio.volume = volumeControl.value;
if (volumeControl.value > 0) {
this.isMuted = false;
toggleBtn.textContent = '🔊';
}
});
restartBtn.addEventListener('click', () => {
this.backgroundAudio.currentTime = 0;
if (!this.isBackgroundAudioPlaying) {
this.playBackgroundAudio();
toggleBtn.textContent = '🔊';
}
});
this.startButton.addEventListener('click', () => {
this.playBackgroundAudio();
toggleBtn.textContent = '🔊';
}, { once: true });
}
toggleMute() {
this.isMuted = !this.isMuted;
this.backgroundAudio.volume = this.isMuted ? 0 : document.getElementById('bg-audio-volume').value;
}
playBackgroundAudio() {
if (this.currentAudio) return;
this.backgroundAudio.currentTime = this.backgroundAudioPausedTime;
this.backgroundAudio.play()
.then(() => {
this.isBackgroundAudioPlaying = true;
})
.catch(e => console.log("Не удалось воспроизвести фоновую музыку:", e));
}
pauseBackgroundAudio() {
this.backgroundAudioPausedTime = this.backgroundAudio.currentTime;
this.backgroundAudio.pause();
this.isBackgroundAudioPlaying = false;
}
setupAutoplay() {
this.startButton.addEventListener('click', () => {
this.autoplayOverlay.style.display = 'none';
this.mainContent.style.display = 'block';
this.playAudio(this.openingAudio);
this.initBackground();
this.initDOM();
this.loadStats();
this.bindEvents();
}, { once: true });
}
initAudio(audio) {
audio.currentTime = 0;
audio.preload = 'auto';
}
async playAudio(audio) {
try {
if (this.currentAudio) {
this.currentAudio.pause();
this.currentAudio.currentTime = 0;
}
if (this.isBackgroundAudioPlaying) {
this.pauseBackgroundAudio();
}
this.currentAudio = audio;
this.currentAudio.currentTime = 0;
await this.currentAudio.play();
this.currentAudio.onended = () => {
this.currentAudio = null;
if (!this.isBackgroundAudioPlaying) {
this.playBackgroundAudio();
}
};
return true;
} catch (err) {
console.log("Ошибка воспроизведения звука:", err);
return false;
}
}
getRandomFromGroup(group, count) {
const available = this.uniqueSelectionEnabled ?
this.people[group].filter(person => !this.selectedPersons[group].includes(person)) :
[...this.people[group]];
if (available.length === 0) {
// Если все люди были выбраны, можно сбросить выбор и начать заново
this.selectedPersons[group] = [];
return this.getRandomFromGroup(group, count); // Рекурсивно выбираем заново
}
const result = [];
for (let i = 0; i < count && available.length > 0; i++) {
const randomIndex = Math.floor(Math.random() * available.length);
result.push(available[randomIndex]);
if (this.uniqueSelectionEnabled) {
this.selectedPersons[group].push(available[randomIndex]);
}
available.splice(randomIndex, 1);
}
return result;
}
selectGroup(group) {
if (this.isSelecting) return;
const count = parseInt(document.getElementById(`${group}-count`).value) || 1;
if (count < 1) {
this.updateResult("Введите число больше 0");
return;
}
this.isSelecting = true;
this.startSelectionAnimation();
this.disableButtons(true);
this.updateResult("Выбираем...");
this.progressElement.style.width = '0%';
anime({
targets: this.progressElement,
width: '100%',
duration: this.selectDuration,
easing: 'linear'
});
this.playAudio(this.loadingAudio);
setTimeout(() => {
const persons = this.getRandomFromGroup(group, count);
this.handleSelectionResult(persons);
this.stopSelectionAnimation();
this.disableButtons(false);
this.isSelecting = false;
}, this.selectDuration);
}
handleSelectionResult(persons) {
if (persons.length === 0) {
this.updateResult("Не удалось выбрать участников");
return;
}
const resultText = persons.length === 1 ?
`Выбран: ${persons[0]}` :
`Выбраны: ${persons.join(', ')}`;
this.updateResult(resultText);
persons.forEach(person => this.updateStats(person));
if (persons.length === 1) {
this.playPersonAudio(persons[0]);
} else {
this.playAudio(this.commonAudio);
}
}
selectPerson() {
if (this.isSelecting) return;
const count = parseInt(this.countInput.value) || 1;
if (count < 1) {
this.updateResult("Введите число больше 0");
return;
}
this.isSelecting = true;
this.startSelectionAnimation();
this.disableButtons(true);
this.updateResult("Выбираем...");
this.progressElement.style.width = '0%';
anime({
targets: this.progressElement,
width: '100%',
duration: this.selectDuration,
easing: 'linear'
});
this.playAudio(this.loadingAudio);
setTimeout(() => {
const persons = this.getRandomPersons(count);
this.handleSelectionResult(persons);
this.stopSelectionAnimation();
this.disableButtons(false);
this.isSelecting = false;
}, this.selectDuration);
}
getRandomPersons(count) {
const result = [];
const allPeople = [...this.people.senior, ...this.people.junior];
const availablePeople = [...allPeople];
for (let i = 0; i < count && availablePeople.length > 0; i++) {
const randomIndex = Math.floor(Math.random() * availablePeople.length);
result.push(availablePeople[randomIndex]);
availablePeople.splice(randomIndex, 1);
}
return result;
}
playPersonAudio(person) {
const audioFile = this.audioFiles[person];
if (audioFile) {
const audio = new Audio(audioFile);
this.playAudio(audio);
}
}
initBackground() {
VANTA.CLOUDS({
el: "#vanta-bg",
mouseControls: true,
touchControls: true,
gyroControls: false,
skyColor: 0x0,
cloudColor: 0x4a6081,
cloudShadowColor: 0x506474,
sunColor: 0xc51f81,
speed: 0.2
});
}
initDOM() {
this.renderList('senior');
this.renderList('junior');
this.updateStatsList();
}
renderList(group) {
const container = document.getElementById(`${group}-list`);
container.innerHTML = this.people[group]
.map(name => `
<div class="person" data-name="${name}">
<span class="person-name">${name}</span>
<span class="counter">${this.stats[name] || 0}</span>
</div>
`)
.join('');
}
loadStats() {
const savedStats = localStorage.getItem(this.STORAGE_KEY);
if (savedStats) {
this.stats = JSON.parse(savedStats);
} else {
this.resetStats();
}
this.updateAllCounters();
}
resetStats() {
this.stats = {};
[...this.people.senior, ...this.people.junior].forEach(name => {
this.stats[name] = 0;
});
this.saveStats();
this.updateAllCounters();
this.updateStatsList();
}
saveStats() {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.stats));
}
exportData() {
const dataStr = JSON.stringify(this.stats);
const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
const exportFileDefaultName = 'randomizer_stats.json';
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
}
importData() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = event => {
try {
const importedStats = JSON.parse(event.target.result);
if (this.validateStats(importedStats)) {
this.stats = importedStats;
this.saveStats();
this.updateAllCounters();
this.updateStatsList();
this.updateResult("Данные успешно импортированы");
} else {
this.updateResult("Ошибка: неверный формат данных");
}
} catch (error) {
this.updateResult("Ошибка при чтении файла");
console.error(error);
}
};
reader.readAsText(file);
};
input.click();
}
validateStats(stats) {
const allPeople = [...this.people.senior, ...this.people.junior];
return allPeople.every(person => stats.hasOwnProperty(person));
}
updateAllCounters() {
document.querySelectorAll('.person').forEach(el => {
const name = el.dataset.name;
el.querySelector('.counter').textContent = this.stats[name] || 0;
});
}
updateStatsList() {
const statsList = document.getElementById('stats-list');
const sortedStats = Object.entries(this.stats)
.sort((a, b) => b[1] - a[1]);
statsList.innerHTML = sortedStats
.map(([name, count]) => `
<div class="stat-item">
<span>${name}</span>
<span>${count}</span>
</div>
`)
.join('');
}
disableButtons(disabled) {
document.querySelectorAll('button').forEach(btn => {
btn.disabled = disabled;
});
}
startSelectionAnimation() {
this.diceElement.classList.add('rotating');
anime({
targets: this.diceElement,
rotate: '+=360',
duration: 1000,
loop: true,
easing: 'linear'
});
}
stopSelectionAnimation() {
this.diceElement.classList.remove('rotating');
anime.remove(this.diceElement);
anime({
targets: this.diceElement,
rotate: 0,
duration: 300
});
}
updateResult(text) {
const resultEl = document.getElementById('result');
resultEl.textContent = text;
}
updateStats(person) {
if (this.stats[person] !== undefined) {
this.stats[person]++;
this.saveStats();
this.updateAllCounters();
this.updateStatsList();
}
}
bindEvents() {
document.getElementById('random-btn').addEventListener('click', () => this.selectPerson());
document.querySelectorAll('.group-random-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
this.selectGroup(e.target.dataset.group);
});
});
document.getElementById('reset-btn').addEventListener('click', () => {
if (confirm('Сбросить статистику?')) {
this.resetStats();
this.updateResult('Статистика сброшена');
}
});
document.getElementById('export-btn').addEventListener('click', () => this.exportData());
document.getElementById('import-btn').addEventListener('click', () => this.importData());
document.getElementById('unique-selection').addEventListener('change', (e) => {
this.uniqueSelectionEnabled = e.target.checked;
// Перезапустите выбор, если уникальный выбор отключен
if (!this.uniqueSelectionEnabled) {
this.selectedPersons = { senior: [], junior: [] };
}
});
}
}
document.addEventListener('DOMContentLoaded', () => {
const randomizer = new Randomizer();
window.addEventListener('beforeunload', () => {
const openingAudio = new Audio('audio/Otkritie.mp3');
openingAudio.volume = 0.5;
openingAudio.play().catch(e => console.log("Не удалось воспроизвести звук при обновлении"));
});
});
</script>
</body>
</html>
Теперь, при активации уникального выбора и нажатии кнопки "выбрать всех", будет осуществляться выбор до тех пор, пока не будут выбраны все кандидаты. После этого кандидат может быть повторно выбран.