Color Guessing Game
Home
Snippets
Color Guessing Game
HTML
CSS
JS
<div class="game"> <h2>Guess the Color</h2> <div id="colorBox"></div> <div class="options" id="options"></div> <p id="result"></p> </div>
body { font-family: Arial, sans-serif; background: #f5f5f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .game { background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); text-align: center; } #colorBox { width: 140px; height: 80px; margin: 20px auto; border-radius: 10px; box-shadow: 0 3px 8px rgba(0,0,0,0.3); } .options { display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; } button { border: none; padding: 10px 18px; border-radius: 6px; cursor: pointer; font-size: 14px; background: #eee; transition: 0.3s; } button:hover { background: #ddd; } #result { margin-top: 15px; font-weight: bold; }
const colors = ["red", "blue", "green", "yellow", "orange", "purple", "pink"]; const colorBox = document.getElementById("colorBox"); const optionsDiv = document.getElementById("options"); const result = document.getElementById("result"); let correctColor; function newGame() { correctColor = colors[Math.floor(Math.random() * colors.length)]; colorBox.style.background = correctColor; optionsDiv.innerHTML = ""; result.textContent = ""; const shuffled = [...colors].sort(() => 0.5 - Math.random()); const options = shuffled.slice(0, 3); if (!options.includes(correctColor)) options[0] = correctColor; options.sort(() => 0.5 - Math.random()); options.forEach(c => { const btn = document.createElement("button"); btn.textContent = c; btn.onclick = () => checkAnswer(c); optionsDiv.appendChild(btn); }); } function checkAnswer(color) { if (color === correctColor) { result.textContent = "Correct!"; result.style.color = "green"; } else { result.textContent = "Try Again!"; result.style.color = "red"; } setTimeout(newGame, 1000); } newGame();
Ad #1
Ad #2
Scroll to Top