in this javascript create a function so that if the variable total <= 0 then you go straight to the //display game score function. Don't play any more rounds. - var map = L.map("map").setView([39.2291886,-98.0563728], 4);

L.tileLayer(
 "https://api.mapbox.com/styles/v1/gmapsmania/clqgjez3l00fw01qy2gl91sty/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiZ21hcHNtYW5pYSIsImEiOiJOYnlnSFpvIn0.5f62d0cnrWCA1KioxzXtqg",
 {
  attribution:
   '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
 }
).addTo(map);

var NewYork = L.latLng(40.7495267, -73.9480953);
var SanFrancisco = L.latLng(37.7749295, -122.4194155);
var Chicago = L.latLng(41.8781136, -87.6297982);

const station = document.getElementById("station");
const myDiv = document.getElementById("my-div");

const userMarkers = []; // Array to store user-added markers

const nextButton = document.createElement("button");
nextButton.innerText = "Next City";
nextButton.id = "buttonsdiv";
nextButton.disabled = true;
nextButton.className = "my-button";

const submitButton = document.createElement("subbutton");
submitButton.innerText = "Submit";
submitButton.id = "buttonsdiv";
submitButton.disabled = true;
submitButton.className = "my-button";

let totalDistance = 0; // Keep track of accumulated distance
let roundDistances = []; // Array to store distance for each round
let total = 1000; // Create the total variable with initial value of 1000


// Custom station marker icon
const LeafIcon = L.Icon.extend({
 options: {
  iconSize: [25, 41],
  iconAnchor: [12, 40],
 },
});

const greenIcon = new LeafIcon({
 iconUrl:
  "https://cdn.glitch.global/f4cb3da3-e38f-4c57-8538-cd16160b85b3/marker-icon-green.png?v=1704485394304",
});

// Function to run the game with remaining reference points
function generateAndPlay(remainingPoints) {
 if (remainingPoints.length === 0) {
  // Fit the map to the user-added markers
  const bounds = new L.LatLngBounds();
  //fitmapbounds ro userMarker
  userMarkers.forEach(function (markerLatLng) {
   bounds.extend(markerLatLng);
  });
  map.fitBounds(bounds);
  //remove round 5 picture
  ghostinfo.innerHTML = "";

  // Add the "Play Again" button
  const playAgainButton = document.createElement("button");
  playAgainButton.id = "playAgain";
  playAgainButton.innerText = "Play Again";
  playAgainButton.className = "my-button";

  // Add click event listener to the button
  playAgainButton.addEventListener("click", function () {
   //cheating by reloading the browser. Instead this function should reset all variables and remove markers from map
   location.reload();
  });

  document.getElementById("ghostinfo").appendChild(playAgainButton);

  //display game score
  station.innerHTML = `Well done!<br><br> You've found all the cities! <br><br>
${roundDistances
 .map((distance, index) => `Round ${index + 1}: ${distance.toFixed(2)} miles`)
 .join("<br>")}<br>
<br>Total distance: ${totalDistance.toFixed(2)} miles.`;
   
  // Retrieve the previously saved personal best, or set it to 0 if not found
const savedPersonalBest = localStorage.getItem("personalBest") || 0;

// Check if the current totalDistance is a new personal best
if (totalDistance < savedPersonalBest) {
 // Update the personal best in local storage
 localStorage.setItem("personalBest", totalDistance);

 // Add the personal best statement to the innerHTML
 station.innerHTML += `<br><br>Personal Best: ${totalDistance.toFixed(2)} miles`;
} else {
 // If not a new personal best, display the saved personal best
 station.innerHTML += `<br><br>Personal Best: ${savedPersonalBest.toFixed(2)} miles`;
}

  document.getElementById("buttonsdiv").removeChild(submitButton);
  document
   .getElementById("station")
   .animate(
    [
     { transform: "rotate(-10deg)" },
     { transform: "rotate(10deg)" },
     { transform: "rotate(-10deg)" },
     { transform: "rotate(10deg)" },
     { transform: "rotate(-10deg)" },
     { transform: "rotate(10deg)" },
    ],
    {
     duration: 1000,
     iterations: 1,
    }
   );

  return;
 }

 const randomIndex = Math.floor(Math.random() * remainingPoints.length);
 const referencePoint = remainingPoints[randomIndex];

 const roundNumber = Math.ceil(5 - remainingPoints.length + 1); // Calculate round number

 station.innerHTML = `Round ${roundNumber}: Drop a marker on the location of ${locationNames[referencePoint]}.<br>`;
 ghostinfo.innerHTML = `${locationNames[referencePoint]}<br>`;

 map.off("click"); // Remove previous click event listener
  
 // Function to create the midpoint variable
function createMidpoint(markerLatLng, referencePointLatLng) {
 const markerLat = markerLatLng.lat;
 const markerLng = markerLatLng.lng;
 const referencePointLat = referencePointLatLng.lat;
 const referencePointLng = referencePointLatLng.lng;

 // Calculate the midpoint's latitude and longitude
 const midpointLat = (markerLat + referencePointLat) / 2;
 const midpointLng = (markerLng + referencePointLng) / 2;

 // Create the midpoint L.latLng object
 const midpoint = L.latLng(midpointLat, midpointLng);

 return midpoint;
}

 map.on("click", function (e) {
  // Add user marker to the array
  var userMarker = L.marker(e.latlng).addTo(map);
  userMarkers.push(userMarker.getLatLng());
   
  //add submitbutton
  document.getElementById("buttonsdiv").appendChild(submitButton);

  submitButton.onclick = function () {
   const marker = L.marker(e.latlng).addTo(map);
   const distance = L.latLng(e.latlng).distanceTo(referencePoint);
   // Calculate distanceInMiles before using it
   map.off("click");
    
   // Create a bounds object encompassing both markers
  const bounds = L.latLngBounds([e.latlng, referencePoint]);
    

  // Zoom the map to fit those bounds
  map.fitBounds(bounds);
    
   //remove submit button and add next painting button
  document.getElementById("buttonsdiv").appendChild(nextButton);
  document.getElementById("buttonsdiv").removeChild(submitButton);
    
   const distanceInMiles = distance * 0.000621371;

   // Update total
   total = total - distanceInMiles;
  
   
  // Update myDiv with the total value
 myDiv.innerHTML = `You clicked ${distanceInMiles.toFixed(2)} miles from ${
  locationNames[referencePoint]
 }. You have ${total.toFixed(2)} miles left.`;
    
     // Create the midpoint variable and display message
  const midpoint = createMidpoint(e.latlng, referencePoint);
   const popup = L.popup()
 .setLatLng(midpoint)
 .setContent(
  distanceInMiles < 0.5
   ? 'Perfect'
   : distanceInMiles < 2
    ? 'Very Good'
    : distanceInMiles < 10
     ? 'At least you got the right city'
     : 'Oh well, better luck next time!' // Default message for distances 10 miles or more
 )
 .openOn(map);

   
   // Update total distance with clicked marker's distance
   totalDistance += distanceInMiles;
   roundDistances.push(distanceInMiles); // Add distance to the roundDistances array
   // connect user marker to correct location
   const polyline = L.polyline([e.latlng, referencePoint], {
    color: "black",
   }).addTo(map);

   // Put marker on correct location
   const stationMarker = L.marker(referencePoint, { icon: greenIcon }).addTo(
    map
   );

   // Remove the used reference point from the remaining pool
   remainingPoints.splice(randomIndex, 1);
  };
 });

 // Enable next button when a new game round starts
 nextButton.disabled = false;

 // Handle next button click
 nextButton.onclick = function () {
  //remove popup message
  map.closePopup();
    // Change button text to "Results" on the fifth question
 if (roundNumber === 4) {
  nextButton.innerText = "Results";
 }

   //remove next button and add submit painting button
  document.getElementById("buttonsdiv").removeChild(nextButton);
  map.setView([39.2291886,-98.0563728], 4);
  document
   .getElementById("station")
   .animate(
    [
     { transform: "translateX(-3px)" },
     { transform: "translateX(3px)" },
     { transform: "translateX(-3px)" },
     { transform: "translateX(3px)" },
     { transform: "translateX(-3px)" },
     { transform: "translateX(3px)" },
    ],
    {
     duration: 1000,
     iterations: 1,
    }
   );
   
  generateAndPlay(remainingPoints);
  myDiv.innerHTML = "";
 };
}

// Use map to determine location name according to the chosen reference point
const locationNames = {
 [NewYork]: "New York",
 [SanFrancisco]: "San Francisco",
 [Chicago]: "Chicago",
 };


// Start the game with all reference points


function toPlay() {
 playbutton.remove();
 const entries = [
  NewYork,
  SanFrancisco,
  Chicago,
 ];

 // Use entries directly, no need to shuffle or slice
 generateAndPlay(entries);
 myDiv.innerHTML = "";
}