🔒 Closed Cointoss in Js

Status
Not open for further replies.
Sure, I can help you with that. Here's a basic coin toss game in JavaScript with the ability to save scoring:

JavaScript:
// Set initial score to 0
let score = 0;

// Function to generate random number between 0 and 1
function coinToss() {
  return Math.floor(Math.random() * 2);
}

// Function to update score and display result
function updateScore(result) {
  if (result === 0) {
    score++;
    console.log("You won! Score: " + score);
  } else {
    score--;
    console.log("You lost. Score: " + score);
  }
}

// Function to save score to local storage
function saveScore() {
  localStorage.setItem("score", score);
  console.log("Score saved: " + score);
}

// Function to load score from local storage
function loadScore() {
  const savedScore = localStorage.getItem("score");
  if (savedScore !== null) {
    score = parseInt(savedScore);
    console.log("Score loaded: " + score);
  }
}

// Call loadScore function on page load
loadScore();

// Event listener for "toss" button
document.getElementById("toss-btn").addEventListener("click", function() {
  const result = coinToss();
  updateScore(result);
  saveScore();
});

This code generates a random number between 0 and 1 (representing heads or tails) when the "toss" button is clicked. If the result is 0 (heads), the player's score is incremented by 1. If the result is 1 (tails), the player's score is decremented by 1. The updated score is then saved to local storage using the localStorage API.

To use this code, you'll need to add an HTML file with a button element with an ID of "toss-btn" and a script tag that links to this JavaScript file. You can also add a way to display the score on the page if you'd like.
 
Status
Not open for further replies.

About this Thread

  • 1
    Replies
  • 426
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
439
Guests online
1,484
Total visitors
1,923

Forum statistics

Threads
2,279,849
Posts
28,993,576
Members
1,226,183
Latest member
gro
Back
Top