|
<!DOCTYPE html> |
|
<html lang="en"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>Guess the Color Game</title> |
|
<link rel="stylesheet" href="styles.css"> |
|
</head> |
|
<body> |
|
<div class="game-container"> |
|
<h1>Guess the Color Game</h1> |
|
<p>Try to guess the background color!</p> |
|
<div class="color-options"> |
|
<div class="color-box" id="color1"></div> |
|
<div class="color-box" id="color2"></div> |
|
<div class="color-box" id="color3"></div> |
|
<div class="color-box" id="color4"></div> |
|
</div> |
|
<p id="result"></p> |
|
<button onclick="resetGame()">Play Again</button> |
|
</div> |
|
|
|
<script> |
|
const colors = ["red", "blue", "green", "yellow"]; |
|
let selectedColor; |
|
|
|
function randomizeColors() { |
|
selectedColor = colors[Math.floor(Math.random() * colors.length)]; |
|
document.body.style.backgroundColor = selectedColor; |
|
|
|
|
|
const shuffledColors = [...colors].sort(() => Math.random() - 0.5); |
|
document.getElementById("color1").style.backgroundColor = shuffledColors[0]; |
|
document.getElementById("color2").style.backgroundColor = shuffledColors[1]; |
|
document.getElementById("color3").style.backgroundColor = shuffledColors[2]; |
|
document.getElementById("color4").style.backgroundColor = shuffledColors[3]; |
|
} |
|
|
|
function checkGuess(selected) { |
|
const result = document.getElementById("result"); |
|
if (selected === selectedColor) { |
|
result.textContent = "Correct! You guessed the color!"; |
|
result.style.color = "green"; |
|
} else { |
|
result.textContent = "Wrong guess! Try again."; |
|
result.style.color = "red"; |
|
} |
|
} |
|
|
|
function resetGame() { |
|
document.getElementById("result").textContent = ""; |
|
randomizeColors(); |
|
} |
|
|
|
|
|
document.getElementById("color1").onclick = () => checkGuess(document.getElementById("color1").style.backgroundColor); |
|
document.getElementById("color2").onclick = () => checkGuess(document.getElementById("color2").style.backgroundColor); |
|
document.getElementById("color3").onclick = () => checkGuess(document.getElementById("color3").style.backgroundColor); |
|
document.getElementById("color4").onclick = () => checkGuess(document.getElementById("color4").style.backgroundColor); |
|
|
|
|
|
randomizeColors(); |
|
</script> |
|
</body> |
|
</html> |