Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
68 lines (58 loc) · 1.81 KB
/
Copy pathscript.js
File metadata and controls
68 lines (58 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const colorBox = document.querySelector('[data-testid="colorBox"]');
const gameStatus = document.querySelector('[data-testid="gameStatus"]');
const scoreDisplay = document.querySelector('[data-testid="score"]');
const newGameButton = document.querySelector('[data-testid="newGameButton"]');
const colorOptions = document.getElementById('color-options');
let score = 0;
let targetColor;
const colors = [
'red', 'blue', 'green', 'yellow', 'magenta', 'purple',
];
// Select a random color as the target color
function getRandomColor() {
return colors[Math.floor(Math.random() * colors.length)];
}
// Function to start a new game
function startNewGame() {
targetColor = getRandomColor();
colorBox.style.backgroundColor = targetColor;
gameStatus.textContent = "";
renderColorOptions();
}
// Function to render color options
function renderColorOptions() {
var colorOptions = document.getElementById('color-options');
colorOptions.innerHTML = "";
const options = [
targetColor,
...Array(5)
.fill()
.map(() => getRandomColor()),
];
options.sort(() => Math.random() - 0.5);
options.forEach((color) => {
const button = document.createElement("button");
button.style.backgroundColor = color;
button.addEventListener("click", () => handleGuess(color));
colorOptions.appendChild(button);
});
}
// Function to handle user's guess
function handleGuess(guess) {
if (guess === targetColor) {
gameStatus.textContent = "Correct!";
score++;
scoreDisplay.textContent = score;
startNewGame();
} else {
gameStatus.textContent = "Wrong! Try again.";
}
}
// Event listener for the new game button
newGameButton.addEventListener('click', () => {
score = 0; // Reset score
scoreDisplay.textContent = score;
startNewGame()
});
// Start the first game
startNewGame();