-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (42 loc) · 1.77 KB
/
script.js
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
// Initialize counters with the stored values or default to 0
let headsCounter = parseInt(localStorage.getItem('headsCounter')) || 0;
let tailsCounter = parseInt(localStorage.getItem('tailsCounter')) || 0;
// Update the counter elements with initial values
document.getElementById("counterHeads").innerText = `Heads Button Clicked: ${headsCounter}`;
document.getElementById("counterTails").innerText = `Tails Button Clicked: ${tailsCounter}`;
document.getElementById("headsBtn").addEventListener("click", function() {
flipCoin("Heads");
updateCounter("heads");
});
document.getElementById("tailsBtn").addEventListener("click", function() {
flipCoin("Tails");
updateCounter("tails");
});
function flipCoin(userChoice) {
// Randomly generate Heads or Tails
const randomNumber = Math.random();
let result;
if (randomNumber < 0.5) {
result = "Heads";
} else {
result = "Tails";
}
// Display the result
document.getElementById("result").innerText = `You chose ${userChoice}. The result is ${result}.`;
if (userChoice === result) {
document.getElementById("result").innerText += " Congratulations! You win!";
} else {
document.getElementById("result").innerText += " Sorry! You lose!";
}
}
function updateCounter(choice) {
if (choice === "heads") {
headsCounter++;
document.getElementById("counterHeads").innerText = `Heads Button Clicked: ${headsCounter}`;
localStorage.setItem('headsCounter', headsCounter);
} else if (choice === "tails") {
tailsCounter++;
document.getElementById("counterTails").innerText = `Tails Button Clicked: ${tailsCounter}`;
localStorage.setItem('tailsCounter', tailsCounter);
}
}