Что за скрипт? <!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<title>Лото Забава Симуляція</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
.ticket {
        display: inline-block;
        margin: 10px;
        border: 2px solid #333;
        padding: 10px;
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
    }

    .field {
        display: grid;
        grid-template-columns: repeat(5, 40px);
        grid-gap: 5px;
        margin-bottom: 10px;
        border: 2px solid #ddd;
        padding: 5px;
        border-radius: 8px;
    }

    .cell {
        width: 40px;
        height: 40px;
        border: 1px solid #ccc;
        text-align: center;
        line-height: 40px;
        font-size: 16px;
        position: relative;
        border-radius: 5px;
        background-color: #f8f8f8;
    }

    .marked {
        background-color: #ffd700;
        color: #333;
        font-weight: bold;
    }

    .horseshoe {
        font-size: 24px;
        color: #e67e22;
    }

    #controls {
        margin: 20px;
    }

    #drawnNumbers {
        margin: 20px;
    }

    #results {
        margin: 20px;
    }

    #tickets {
        margin: 20px;
    }

    .button {
        padding: 10px 15px;
        margin: 5px;
        font-size: 16px;
        border: none;
        border-radius: 5px;
        background-color: #4CAF50;
        color: white;
        cursor: pointer;
    }

    #history {
        margin: 20px;
    }

    .completed-line {
        background-color: red !important;
        color: #fff;
    }

    #buyTicketsInput {
        width: 80px;
        padding: 5px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 5px;
    }

    #drawnCount {
        font-weight: bold;
    }

    #winningTickets {
        margin-top: 10px;
    }

    #info {
        margin: 20px;
        border: 1px solid #ccc;
        padding: 10px;
        border-radius: 5px;
        background-color: #f9f9f9;
    }

    #info p {
        margin: 5px 0;
    }

    #drawHistory li {
        margin-bottom: 10px;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        background-color: #f9f9f9;
    }

    /* Стили для пагинации */
    #pagination-controls {
        margin: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    #pagination-controls .button {
        background-color: #008CBA;
    }

    #page-info {
        margin: 0 15px;
        font-size: 18px;
    }

    /* Стили для поля пошуку */
    #search-container {
        margin: 20px;
        display: flex;
        align-items: center;
    }

    #search-input {
        padding: 8px;
        margin-right: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        font-size: 16px;
    }

    #search-button {
        padding: 8px 15px;
        border: none;
        border-radius: 5px;
        background-color: #4CAF50;
        color: white;
        cursor: pointer;
        font-size: 16px;
    }

    /* Нові стилі для кульок */
    .ball {
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        text-align: center;
        line-height: 40px;
        font-weight: bold;
        margin: 2px;
        opacity: 0;
        transition: opacity 0.5s ease-in-out;
    }

    .ball.white { background-color: #ffffff; color: #000000; border: 1px solid #000000; }
    .ball.yellow { background-color: #ffff00; color: #000000; }
    .ball.green { background-color: #00ff00; color: #000000; }
    .ball.red { background-color: #ff0000; color: #ffffff; }
    .ball.blue { background-color: #0000ff; color: #ffffff; }

    #ballContainer {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        margin-top: 20px;
    }

    /* Нові стилі для контейнерів кольорів та колонок */
    .color-container {
        display: flex;
        flex-direction: row;
        justify-content: center;
        margin: 0 10px 20px 10px;
    }

    .column {
        display: flex;
        flex-direction: column-reverse;
        align-items: center;
        margin: 0 5px;
    }
</style>
</head>
<body>
<h1>Симуляція лотереї "Лото Забава"</h1>
<div id="controls">
<label>Купити білети (1 грн за білет): </label>
<input type="number" id="buyTicketsInput" value="1" min="1">
<button class="button" onclick="buyTickets()">Купити</button>
<button class="button" onclick="startNewDraw()">Почати новий розіграш</button>
<button class="button" onclick="drawNextBall()">Дістати шар</button>
</div>
<div id="info">
<p>Поточний тираж: <span id="currentDraw">1</span></p>
<p>Кількість куплених білетів: <span id="ticketCount">0</span></p>
<p>Загальний призовий фонд: <span id="prizeFund">0</span> грн</p>
</div>
<div id="drawnNumbers">
<h3>Витягнуті номери (<span id="drawnCount">0</span> шарів):</h3>
<div id="ballContainer"></div>
<div id="numbers"></div>
</div>
<div id="results">
<h3>Результати:</h3>
<p>Білетів з 1 лінією: <span id="oneLine">0</span> (виграш <span id="oneLinePrize">0</span> грн)</p>
<p>Білетів з 2 лініями: <span id="twoLines">0</span> (виграш <span id="twoLinesPrize">0</span> грн на кожного)</p>
<p>Білетів з 3 лініями: <span id="threeLines">0</span> (виграш <span id="threeLinesPrize">0</span> грн на кожного)</p>
<p>Білетів з Джек-потом: <span id="jackpotWinners">0</span> (виграш 10,000 грн)</p>
<div id="winningTickets"></div>
</div>
<div id="tickets">
<h3>Ваші білети:</h3>
<div id="search-container">
<input type="number" id="search-input" placeholder="Введіть номер білета">
<button id="search-button" onclick="searchTicket()">Знайти</button>
</div>
<div id="ticketContainer"></div>
<div id="pagination-controls">
<button class="button" id="prevPage" onclick="prevPage()">Попередня сторінка</button>
<span id="page-info">Сторінка 1</span>
<button class="button" id="nextPage" onclick="nextPage()">Наступна сторінка</button>
</div>
</div>
<div id="history">
<h3>Історія розіграшів:</h3>
<ul id="drawHistory"></ul>
</div>
<script>
let currentDrawNumber = 1;
let tickets = [];
let drawnNumbers = [];
let prizeFund = 0;
const ticketPrice = 1;

let oneLineWinners = new Set();
let twoLineWinners = new Set();
let threeLineWinners = new Set();
let jackpotWinners = new Set();

let drawHistory = [];

let drawEnded = false;

// Параметры пагинации
let currentPage = 1;
const ticketsPerPage = 100;

function buyTickets() {
let quantityInput = document.getElementById('buyTicketsInput');
let quantity = parseInt(quantityInput.value);
if (isNaN(quantity) || quantity < 1) {
alert('Введіть коректну кількість білетів.');
return;
}

prizeFund += ticketPrice * quantity;
document.getElementById('prizeFund').innerText = prizeFund;

for (let i = 0; i < quantity; i++) {
let ticket = generateTicket();
tickets.push({
fields: ticket,
linesCompleted: 0,
id: tickets.length, // Unique identifier
completedLines: [[], [], []]
});
}

currentPage = 1; // Сбросить на первую страницу после покупки билетов
updatePaginationControls();
displayTickets();
document.getElementById('ticketCount').innerText = tickets.length;
}

function generateTicket() {
let ticket = [];
for (let i = 0; i < 3; i++) {
ticket.push(generateField());
}
return ticket;
}

function generateField() {
let field = [];
let ranges = [
{min: 1, max: 15},
{min: 16, max: 30},
{min: 31, max: 45},
{min: 46, max: 60},
{min: 61, max: 75},
];

// Prepare empty 5x5 grid
for (let i = 0; i < 5; i++) {
field.push([]);
}

// Fill columns
for (let col = 0; col < 5; col++) {
let columnNumbers = getUniqueRandomNumbers(5, ranges[col].min, ranges[col].max);
for (let row = 0; row < 5; row++) {
field[row][col] = columnNumbers[row];
}
}

// Place two horseshoes in different rows
let horseshoeRows = getUniqueRandomNumbers(2, 0, 4);
for (let i = 0; i < horseshoeRows.length; i++) {
let row = horseshoeRows[i];
let col;
do {
col = Math.floor(Math.random() * 5);
} while (field[row][col] === '🔱');
field[row][col] = '🔱';
}

return field;
}

function getUniqueRandomNumbers(count, min, max) {
let numbers = [];
while (numbers.length < count) {
let num = Math.floor(Math.random() * (max - min + 1)) + min;
if (!numbers.includes(num)) {
numbers.push(num);
}
}
return numbers;
}

function displayTickets() {
let container = document.getElementById('ticketContainer');
container.innerHTML = '';

let startIndex = (currentPage - 1) * ticketsPerPage;
let endIndex = Math.min(startIndex + ticketsPerPage, tickets.length);

for (let index = startIndex; index < endIndex; index++) {
let ticketObj = tickets[index];
let ticket = ticketObj.fields;
let ticketDiv = document.createElement('div');
ticketDiv.classList.add('ticket');
ticketDiv.setAttribute('data-ticket-id', ticketObj.id);
let ticketHeader = document.createElement('h4');
ticketHeader.innerText = 'Білет №' + (ticketObj.id + 1);
ticketDiv.appendChild(ticketHeader);
ticket.forEach((field, fieldIndex) => {
let fieldDiv = document.createElement('div');
fieldDiv.classList.add('field');
fieldDiv.setAttribute('data-field-index', fieldIndex);
field.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
let cellDiv = document.createElement('div');
cellDiv.classList.add('cell');
cellDiv.setAttribute('data-row', rowIndex);
cellDiv.setAttribute('data-col', colIndex);
if (cell === '🔱') {
cellDiv.innerHTML = '<span class="horseshoe">🔱</span>';
} else {
cellDiv.innerText = cell;
cellDiv.setAttribute('data-number', cell);
if (drawnNumbers.includes(cell)) {
cellDiv.classList.add('marked');
}
}
if (ticketObj.completedLines && ticketObj.completedLines[fieldIndex] && ticketObj.completedLines[fieldIndex].includes(rowIndex)) {
cellDiv.classList.add('completed-line');
}
fieldDiv.appendChild(cellDiv);
});
});
ticketDiv.appendChild(fieldDiv);
});
container.appendChild(ticketDiv);
}
updatePaginationControls();
}

function updatePaginationControls() {
let totalPages = Math.ceil(tickets.length / ticketsPerPage);
document.getElementById('page-info').innerText = `Сторінка ${currentPage} з ${totalPages}`;

document.getElementById('prevPage').disabled = currentPage === 1;
document.getElementById('nextPage').disabled = currentPage === totalPages || totalPages === 0;
}

function prevPage() {
if (currentPage > 1) {
currentPage--;
displayTickets();
}
}

function nextPage() {
let totalPages = Math.ceil(tickets.length / ticketsPerPage);
if (currentPage < totalPages) {
currentPage++;
displayTickets();
}
}

function startNewDraw() {
if (drawnNumbers.length > 0) {
saveDrawHistory();
}
currentDrawNumber++;
document.getElementById('currentDraw').innerText = currentDrawNumber;
drawnNumbers = [];
tickets = [];
prizeFund = 0;
oneLineWinners.clear();
twoLineWinners.clear();
threeLineWinners.clear();
jackpotWinners.clear();
document.getElementById('ticketCount').innerText = tickets.length;
document.getElementById('prizeFund').innerText = prizeFund;
document.getElementById('numbers').innerText = '';
document.getElementById('ballContainer').innerHTML = '';
document.getElementById('drawnCount').innerText = '0';
document.getElementById('oneLine').innerText = oneLineWinners.size;
document.getElementById('twoLines').innerText = twoLineWinners.size;
document.getElementById('threeLines').innerText = threeLineWinners.size;
document.getElementById('jackpotWinners').innerText = jackpotWinners.size;
document.getElementById('oneLinePrize').innerText = '0';
document.getElementById('twoLinesPrize').innerText = '0';
document.getElementById('threeLinesPrize').innerText = '0';
document.getElementById('winningTickets').innerHTML = '';
drawEnded = false;
currentPage = 1;
updatePaginationControls();
displayTickets();
}

function drawNextBall() {
if (drawEnded) {
alert('Розіграш завершено. Почніть новий тираж.');
return;
}
if (drawnNumbers.length >= 75) {
alert('Усі номери вже витягнуті.');
return;
}
let number;
do {
number = Math.floor(Math.random() * 75) + 1;
} while (drawnNumbers.includes(number));
drawnNumbers.push(number);

let ballColor;
if (number <= 15) ballColor = 'white';
else if (number <= 30) ballColor = 'yellow';
else if (number <= 45) ballColor = 'green';
else if (number <= 60) ballColor = 'red';
else ballColor = 'blue';

document.getElementById('numbers').innerText = drawnNumbers.join(', ');
document.getElementById('drawnCount').innerText = drawnNumbers.length;
markTickets(number);
checkWinners();
updateBallDisplay(); // Обновление отображения шариков
}

function updateBallDisplay() {
    let colorGroups = {
        white: [],
        yellow: [],
        green: [],
        red: [],
        blue: []
    };

    // Группировка номеров по цветам
    drawnNumbers.forEach(number => {
        let color;
        if (number >= 1 && number <= 15) color = 'white';
        else if (number >= 16 && number <= 30) color = 'yellow';
        else if (number >= 31 && number <= 45) color = 'green';
        else if (number >= 46 && number <= 60) color = 'red';
        else if (number >= 61 && number <= 75) color = 'blue';
        colorGroups[color].push(number);
    });

    // Сортировка номеров внутри каждой группы
    Object.keys(colorGroups).forEach(color => {
        colorGroups[color].sort( (a,b) => a - b);
    });

    // Очистка контейнера
    let container = document.getElementById('ballContainer');
    container.innerHTML = '';

    // Перебор цветов в заданном порядке
    let colors = ['white', 'yellow', 'green', 'red', 'blue'];

    colors.forEach(color => {
        let numbers = colorGroups[color];

        // Создаем контейнер для цвета
        let colorContainer = document.createElement('div');
        colorContainer.className = 'color-container';

        // Создаем три колонки
        let columns = [[], [], []];

        // Распределяем шары по колонкам
        for (let i = 0; i < numbers.length; i++) {
            let number = numbers[i];
            let columnIndex = i % 3; // Индекс колонки от 0 до 2
            columns[columnIndex].push(number);
        }

        // Создаем элементы для каждой колонки
        for (let i = 0; i < 3; i++) {
            let columnDiv = document.createElement('div');
            columnDiv.className = 'column';

            // Ограничиваем количество шаров до 5 в каждой колонке
            let ballsInColumn = columns[i].slice(0, 5);

            ballsInColumn.forEach(number => {
                let ballElement = document.createElement('div');
                ballElement.className = `ball ${color}`; // Исправлено: добавлены обратные кавычки
                ballElement.textContent = number;
                ballElement.style.opacity = '1';
                columnDiv.appendChild(ballElement);
            });

            colorContainer.appendChild(columnDiv);
        }

        container.appendChild(colorContainer);
    });
}

function markTickets(number) {
tickets.forEach((ticketObj) => {
ticketObj.fields.forEach((field, fieldIndex) => {
field.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
if (cell === number) {
if (isTicketOnCurrentPage(ticketObj.id)) {
let ticketDiv = document.querySelector(`.ticket[data-ticket-id="${ticketObj.id}"]`); // Исправлено: добавлены обратные кавычки
if (ticketDiv) {
let fieldDiv = ticketDiv.querySelectorAll('.field')[fieldIndex];
let cellDivs = fieldDiv.querySelectorAll('.cell');
let cellDivIndex = rowIndex * 5 + colIndex;
let cellDiv = cellDivs[cellDivIndex];
cellDiv.classList.add('marked');
}
}
}
});
});
});
});
}

function isTicketOnCurrentPage(ticketId) {
let startIndex = (currentPage - 1) * ticketsPerPage;
let endIndex = Math.min(startIndex + ticketsPerPage, tickets.length);
return ticketId >= startIndex && ticketId < endIndex;
}

function checkWinners() {
oneLineWinners.clear();
twoLineWinners.clear();
threeLineWinners.clear();
jackpotWinners.clear();

tickets.forEach((ticketObj) => {
let ticketId = ticketObj.id;
let maxLinesCompleted = 0;
let hasJackpot = false;

ticketObj.fields.forEach((field, fieldIndex) => {
let linesCompleted = checkFieldLines(field, ticketObj, fieldIndex);

if (linesCompleted > maxLinesCompleted) {
maxLinesCompleted = linesCompleted;
}

if (isJackpot(field) && linesCompleted === 3) {
hasJackpot = true;
}
});

if (hasJackpot) {
jackpotWinners.add(ticketId);
addWinningTicket(ticketId + 1, 'Джекпот');
drawEnded = true;
} else if (maxLinesCompleted === 3) {
threeLineWinners.add(ticketId);
addWinningTicket(ticketId + 1, '3 лінії');
drawEnded = true;
} else if (maxLinesCompleted === 2) {
twoLineWinners.add(ticketId);
} else if (maxLinesCompleted === 1) {
oneLineWinners.add(ticketId);
}
});

updatePrizes();
updateResults();

displayTickets();

if (drawEnded) {
alert('Розіграш завершено! Перевірте результати.');
}
}

function checkFieldLines(field, ticketObj, fieldIndex) {
let lines = 0;

for (let i = 0; i < 5; i++) {
let rowMarked = 0;
for (let j = 0; j < 5; j++) {
let cellValue = field[i][j];
if (cellValue === '🔱') {
rowMarked++;
} else if (isNumberMarked(cellValue)) {
rowMarked++;
}
}
if (rowMarked === 5) {
lines++;
if (!ticketObj.completedLines[fieldIndex].includes(i)) {
ticketObj.completedLines[fieldIndex].push(i);
}
}
}
return lines;
}

function isNumberMarked(number) {
return drawnNumbers.includes(number);
}

function isJackpot(field) {
let allMarked = true;
let hasHorseshoe = false;
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
let cellValue = field[i][j];
if (cellValue === '🔱') {
hasHorseshoe = true;
continue;
} else if (!isNumberMarked(cellValue)) {
allMarked = false;
break;
}
}
if (!allMarked) break;
}
return allMarked && !hasHorseshoe;
}

function updatePrizes() {
let oneLinePrize = 1;
document.getElementById('oneLinePrize').innerText = oneLinePrize;

let totalTwoLinePrize = Math.max(prizeFund * 0.05, 5 * twoLineWinners.size);
let twoLinePrizePerWinner = twoLineWinners.size > 0 ? (totalTwoLinePrize / twoLineWinners.size).toFixed(2) : 0;
document.getElementById('twoLinesPrize').innerText = twoLinePrizePerWinner;

let totalThreeLinePrize = prizeFund * 0.1;
let threeLinePrizePerWinner = threeLineWinners.size > 0 ? (totalThreeLinePrize / threeLineWinners.size).toFixed(2) : 0;
document.getElementById('threeLinesPrize').innerText = threeLinePrizePerWinner;
}

function updateResults() {
document.getElementById('oneLine').innerText = oneLineWinners.size;
document.getElementById('twoLines').innerText = twoLineWinners.size;
document.getElementById('threeLines').innerText = threeLineWinners.size;
document.getElementById('jackpotWinners').innerText = jackpotWinners.size;
}

function addWinningTicket(ticketNumber, prize) {
let winningTicketsDiv = document.getElementById('winningTickets');
let ticketInfo = document.createElement('p');
ticketInfo.innerText = `Білет №${ticketNumber} виграв ${prize}`; // Исправлено: добавлены обратные кавычки
winningTicketsDiv.appendChild(ticketInfo);
}

function saveDrawHistory() {
let drawResult = {
drawNumber: currentDrawNumber,
drawnNumbers: drawnNumbers,
oneLineWinners: oneLineWinners.size,
twoLineWinners: twoLineWinners.size,
threeLineWinners: threeLineWinners.size,
jackpotWinners: jackpotWinners.size
};
drawHistory.unshift(drawResult);
updateDrawHistory();
}

function updateDrawHistory() {
let historyList = document.getElementById('drawHistory');
historyList.innerHTML = '';
drawHistory.forEach((draw, index) => {
if (index < 10) { // Показывать только последние 10 розыгрышей
let listItem = document.createElement('li');
listItem.innerHTML = `
                    <strong>Тираж №${draw.drawNumber}</strong><br>
                    Витягнуті номери: ${draw.drawnNumbers.join(', ')}<br>
                    Переможці: 1 лінія - ${draw.oneLineWinners}, 2 лінії - ${draw.twoLineWinners}, 
                    3 лінії - ${draw.threeLineWinners}, Джекпот - ${draw.jackpotWinners}
                `; // Исправлено: добавлены обратные кавычки
historyList.appendChild(listItem);
}
});
}

function searchTicket() {
let searchInput = document.getElementById('search-input');
let ticketNumber = parseInt(searchInput.value);
if (isNaN(ticketNumber) || ticketNumber < 1 || ticketNumber > tickets.length) {
alert('Введіть коректний номер білета.');
return;
}

let ticketIndex = ticketNumber - 1;
let pageNumber = Math.floor(ticketIndex / ticketsPerPage) + 1;
currentPage = pageNumber;
displayTickets();

let ticketElement = document.querySelector(`.ticket[data-ticket-id="${ticketIndex}"]`); // Исправлено: добавлены обратные кавычки
if (ticketElement) {
ticketElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
ticketElement.style.border = '3px solid red';
setTimeout(() => {
ticketElement.style.border = '';
}, 3000);
}
}

// Инициализация
updatePaginationControls();
</script>
</body>
</html>