What's new

Help Cointoss in Js

PHC - JANG

Forum Guru
Elite
Joined
May 14, 2020
Posts
1,346
Solutions
14
Reaction
9,520
Points
1,683
Age
18
please make a Code pair coinToss game in js with save scoring

Hope bot can help me
 
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.
 
Back
Top