Створити оригінальну логічну гру, головоломку для браузера. Візуально привабливу,…
- User
Створити оригінальну логічну гру, головоломку для браузера. Візуально привабливу, функціональну, адаптивну
Assistant
Логічна гра "Кольорові Лабіринти"
Концепція гри
"Кольорові Лабіринти" - це оригінальна логічна головоломка, де гравцеві потрібно переміщувати кольорові кульки по лабіринту, щоб зібрати їх у правильному порядку. Гра поєднує елементи пазлів, стратегії та логічного мислення.
Технічна реалізація
HTML-структура
<!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Кольорові Лабіринти</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="game-container"> <header> <h1>Кольорові Лабіринти</h1> <div class="controls"> <button id="new-game">Нова гра</button> <button id="hint">Підказка</button> <div class="level-indicator">Рівень: <span id="level">1</span></div> </div> </header> <div class="game-board"> <div class="target-area" id="target-area"></div> <div class="maze" id="maze"></div> </div> <div class="color-palette"> <div class="color" data-color="red"></div> <div class="color" data-color="blue"></div> <div class="color" data-color="green"></div> <div class="color" data-color="yellow"></div> <div class="color" data-color="purple"></div> </div> <div class="game-info"> <div class="moves">Ходи: <span id="moves">0</span></div> <div class="timer">Час: <span id="timer">00:00</span></div> </div> </div> <div class="modal" id="win-modal"> <div class="modal-content"> <h2>Вітаємо!</h2> <p>Ви пройшли рівень!</p> <button id="next-level">Наступний рівень</button> </div> </div> <script src="script.js"></script> </body> </html>CSS-стилі
:root { --primary-color: #4a6fa5; --secondary-color: #166088; --accent-color: #4fc3f7; --background-color: #f8f9fa; --text-color: #333; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(--background-color); color: var(--text-color); margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; } .game-container { width: 90%; max-width: 800px; background-color: white; border-radius: 15px; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); padding: 20px; text-align: center; } header { margin-bottom: 20px; } h1 { color: var(--primary-color); margin: 0; font-size: 2.5rem; } .controls { display: flex; justify-content: center; gap: 15px; margin-top: 15px; } button { background-color: var(--primary-color); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-size: 1rem; transition: background-color 0.3s; } button:hover { background-color: var(--secondary-color); } .game-board { display: flex; flex-direction: column; gap: 20px; margin: 20px 0; } .maze { display: grid; grid-template-columns: repeat(5, 1fr); gap: 5px; background-color: #e9ecef; padding: 10px; border-radius: 10px; } .cell { width: 60px; height: 60px; background-color: white; border-radius: 5px; display: flex; justify-content: center; align-items: center; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; } .cell:hover { transform: scale(1.05); box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); } .ball { width: 40px; height: 40px; border-radius: 50%; transition: transform 0.3s; } .target-area { display: flex; justify-content: center; gap: 10px; padding: 15px; background-color: #e9ecef; border-radius: 10px; min-height: 80px; } .target-slot { width: 50px; height: 50px; border: 2px dashed #ccc; border-radius: 5px; display: flex; justify-content: center; align-items: center; } .color-palette { display: flex; justify-content: center; gap: 15px; margin: 20px 0; } .color { width: 30px; height: 30px; border-radius: 50%; cursor: pointer; border: 2px solid white; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); } .color[data-color="red"] { background-color: #ff5252; } .color[data-color="blue"] { background-color: #4285f4; } .color[data-color="green"] { background-color: #0f9d58; } .color[data-color="yellow"] { background-color: #ffeb3b; } .color[data-color="purple"] { background-color: #9c27b0; } .game-info { display: flex; justify-content: space-between; margin-top: 15px; font-size: 1.1rem; } .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); justify-content: center; align-items: center; z-index: 100; } .modal-content { background-color: white; padding: 30px; border-radius: 10px; text-align: center; max-width: 400px; width: 90%; } .modal-content h2 { color: var(--primary-color); margin-top: 0; } @media (max-width: 600px) { .game-container { width: 95%; padding: 15px; } h1 { font-size: 2rem; } .maze { grid-template-columns: repeat(4, 1fr); } .cell { width: 45px; height: 45px; } .ball { width: 30px; height: 30px; } .target-slot { width: 40px; height: 40px; } }JavaScript-логіка
document.addEventListener('DOMContentLoaded', () => { // DOM elements const maze = document.getElementById('maze'); const targetArea = document.getElementById('target-area'); const newGameBtn = document.getElementById('new-game'); const hintBtn = document.getElementById('hint'); const levelIndicator = document.getElementById('level'); const movesCounter = document.getElementById('moves'); const timerDisplay = document.getElementById('timer'); const winModal = document.getElementById('win-modal'); const nextLevelBtn = document.getElementById('next-level'); // Game state let gameState = { level: 1, moves: 0, time: 0, timer: null, selectedColor: null, balls: [], targetSequence: [], isGameActive: false }; // Colors const colors = ['red', 'blue', 'green', 'yellow', 'purple']; // Initialize the game function initGame() { clearInterval(gameState.timer); gameState = { level: parseInt(levelIndicator.textContent), moves: 0, time: 0, timer: null, selectedColor: null, balls: [], targetSequence: [], isGameActive: true }; movesCounter.textContent = '0'; timerDisplay.textContent = '00:00'; maze.innerHTML = ''; targetArea.innerHTML = ''; generateLevel(); startTimer(); } // Generate a new level function generateLevel() { const size = 5 + Math.min(gameState.level, 5); // Increase size with level maze.style.gridTemplateColumns = `repeat(${size}, 1fr)`; // Create maze cells for (let i = 0; i < size * size; i++) { const cell = document.createElement('div'); cell.className = 'cell'; cell.dataset.index = i; maze.appendChild(cell); } // Generate target sequence const sequenceLength = 3 + Math.min(gameState.level, 7); gameState.targetSequence = []; for (let i = 0; i < sequenceLength; i++) { const color = colors[Math.floor(Math.random() * colors.length)]; gameState.targetSequence.push(color); const slot = document.createElement('div'); slot.className = 'target-slot'; slot.dataset.color = color; targetArea.appendChild(slot); } // Place balls in the maze const ballCount = sequenceLength + Math.floor(gameState.level / 2); const cells = document.querySelectorAll('.cell'); const availableColors = [...colors]; for (let i = 0; i < ballCount; i++) { const randomIndex = Math.floor(Math.random() * cells.length); const randomColorIndex = Math.floor(Math.random() * availableColors.length); const color = availableColors[randomColorIndex]; if (cells[randomIndex].querySelector('.ball')) continue; const ball = document.createElement('div'); ball.className = 'ball'; ball.dataset.color = color; ball.style.backgroundColor = getColorValue(color); cells[randomIndex].appendChild(ball); gameState.balls.push({ element: ball, cellIndex: randomIndex, color: color }); } // Add color selection event listeners document.querySelectorAll('.color').forEach(color => { color.addEventListener('click', () => { gameState.selectedColor = color.dataset.color; document.querySelectorAll('.color').forEach(c => { c.style.border = c.dataset.color === gameState.selectedColor ? `3px solid ${getColorValue(gameState.selectedColor)}` : '2px solid white'; }); }); }); // Add cell click event listeners cells.forEach(cell => { cell.addEventListener('click', () => handleCellClick(cell)); }); } // Handle cell click function handleCellClick(cell) { if (!gameState.isGameActive || !gameState.selectedColor) return; const cellIndex = parseInt(cell.dataset.index); const ball = cell.querySelector('.ball'); if (ball) { // Move the ball const ballData = gameState.balls.find(b => b.cellIndex === cellIndex); if (ballData.color === gameState.selectedColor) { moveBall(ballData); } } else { // Place a new ball if allowed if (gameState.balls.length < gameState.targetSequence.length + 2) { const newBall = document.createElement('div'); newBall.className = 'ball'; newBall.dataset.color = gameState.selectedColor; newBall.style.backgroundColor = getColorValue(gameState.selectedColor); cell.appendChild(newBall); gameState.balls.push({ element: newBall, cellIndex: cellIndex, color: gameState.selectedColor }); gameState.moves++; movesCounter.textContent = gameState.moves; checkWinCondition(); } } } // Move ball in the selected direction function moveBall(ballData) { const currentCell = document.querySelector(`.cell[data-index="${ballData.cellIndex}"]`); const cells = document.querySelectorAll('.cell'); const size = Math.sqrt(cells.length); // Find possible moves (up, down, left, right) const possibleMoves = []; // Up if (ballData.cellIndex >= size) { const newIndex = ballData.cellIndex - size; if (!cells[newIndex].querySelector('.ball')) { possibleMoves.push(newIndex); } } // Down if (ballData.cellIndex < size * (size - 1)) { const newIndex = ballData.cellIndex + size; if (!cells[newIndex].querySelector('.ball')) { possibleMoves.push(newIndex); } } // Left if (ballData.cellIndex % size !== 0) { const newIndex = ballData.cellIndex - 1; if (!cells[newIndex].querySelector('.ball')) { possibleMoves.push(newIndex); } } // Right if ((ballData.cellIndex + 1) % size !== 0) { const newIndex = ballData.cellIndex + 1; if (!cells[newIndex].querySelector('.ball')) { possibleMoves.push(newIndex); } } if (possibleMoves.length === 0) return; // Choose a random move (could be modified for player control) const randomIndex = Math.floor(Math.random() * possibleMoves.length); const newIndex = possibleMoves[randomIndex]; // Move the ball currentCell.removeChild(ballData.element); cells[newIndex].appendChild(ballData.element); // Update ball data ballData.cellIndex = newIndex; gameState.moves++; movesCounter.textContent = gameState.moves; checkWinCondition(); } // Check if player has won function checkWinCondition() { const targetSlots = document.querySelectorAll('.target-slot'); const collectedBalls = []; // Check if balls are in the correct slots targetSlots.forEach(slot => { const ball = slot.querySelector('.ball'); if (ball && ball.dataset.color === slot.dataset.color) { collectedBalls.push(ball.dataset.color); } }); // Check if all target colors are collected in order if (collectedBalls.length === gameState.targetSequence.length) { let isCorrect = true; for (let i = 0; i < gameState.targetSequence.length; i++) { if (collectedBalls[i] !== gameState.targetSequence[i]) { isCorrect = false; break; } } if (isCorrect) { gameState.isGameActive = false; clearInterval(gameState.timer); showWinModal(); } } } // Start the game timer function startTimer() { gameState.timer = setInterval(() => { gameState.time++; const minutes = Math.floor(gameState.time / 60); const seconds = gameState.time % 60; timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; }, 1000); } // Show win modal function showWinModal() { winModal.style.display = 'flex'; } // Helper function to get color value function getColorValue(color) { const colorMap = { 'red': '#ff5252', 'blue': '#4285f4', 'green': '#0f9d58', 'yellow': '#ffeb3b', 'purple': '#9c27b0' }; return colorMap[color] || '#ccc'; } // Event listeners newGameBtn.addEventListener('click', initGame); hintBtn.addEventListener('click', () => { alert(`Підказка: Спробуйте зібрати кульки в такому порядку: ${gameState.targetSequence.join(', ')}`); }); nextLevelBtn.addEventListener('click', () => { winModal.style.display = 'none'; gameState.level++; levelIndicator.textContent = gameState.level; initGame(); }); // Initialize the game on first load initGame(); });Особливості гри
-
Адаптивний дизайн: Гра автоматично підлаштовується під різні розміри екранів.
-
Прогресивна складність: Кожен новий рівень стає складнішим - збільшується розмір лабіринту та кількість кульок.
-
Візуальна привабливість:
- Яскраві кольори
- Плавні анімації
- Чіткий інтерфейс
-
Ігрова механіка:
- Вибір кольору кульки
- Переміщення кульок по лабіринту
- Збір кульок у правильному порядку
-
Додаткові функції:
- Лічильник ходів
- Таймер
- Підказки
- Система рівнів
Як грати
- Виберіть колір кульки з палітри внизу екрану.
- Клацніть на порожню клітинку лабіринту, щоб помістити туди кульку обраного кольору.
- Клацніть на кульку, щоб перемістити її в сусідню порожню клітинку.
- Збирайте кульки в цільовій зоні у правильному порядку, який вказаний кольорами рамок.
- Пройдіть всі рівні, кожен наступний рівень складніший за попередній.
Гра поєднує в собі елементи стратегії, логіки та пам'яті, що робить її цікавою для гравців різного віку.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.