Home / Widgets / Debt
Duplicate Snippet

Embed Snippet on Your Site

Debt

Code Preview
html
<!-- Loan Mechanic Section -->
<div class="container">
  <h2 style="text-align: center;">Loan Mechanic</h2>
  <!-- Give a Loan Section -->
  <div class="wp-block-jetpack-contact-form" style="margin-top: 20px;">
    <h3 style="text-align: center;">Give a Loan</h3>
    <div class="wp-block-jetpack-field-number">
      <label for="loanAmount">Loan Amount (1 - Your Cash Balance):</label>
      <input type="number" id="loanAmount" min="1" step="1" required>
    </div>
    <div class="wp-block-jetpack-field-number">
      <label for="interestRate">Interest Rate (%):</label>
      <input type="number" id="interestRate" min="0" step="0.1" required>
    </div>
    <div class="wp-block-jetpack-field-select">
      <label for="loanRecipient">Select the Country to Give the Loan to:</label>
      <select id="loanRecipient">
        <option value="Eldoria">Eldoria</option>
        <option value="Avalora">Avalora</option>
        <option value="Zephyria">Zephyria</option>
        <option value="Novaria">Novaria</option>
        <option value="Solara">Solara</option>
        <option value="Frostara">Frostara</option>
        <option value="Verdania">Verdania</option>
        <option value="Ignisia">Ignisia</option>
        <option value="Aquarion">Aquarion</option>
        <option value="Lunaria">Lunaria</option>
        <option value="Terranox">Terranox</option>
        <option value="Cryostar">Cryostar</option>
        <option value="Pyronis">Pyronis</option>
        <option value="Aetheris">Aetheris</option>
        <option value="Nimbara">Nimbara</option>
      </select>
    </div>
    <div class="wp-block-jetpack-button">
      <button id="giveLoanButton" class="wp-block-button__link wp-element-button">Give Loan</button>
    </div>
  </div>
  <!-- Loan Notifications Section -->
  <div id="loanNotifications" style="margin-top: 20px;">
    <h3 style="text-align: center;">Loan Notifications</h3>
    <ul id="loanNotificationsList" style="list-style-type: none; padding: 0;">
      <!-- Loan notifications will be dynamically inserted here -->
    </ul>
  </div>
</div>
<script>
  const SAVE_KEY = "game_save";
  // Load game state from localStorage
  function loadGameState() {
    const savedGame = localStorage.getItem(SAVE_KEY);
    if (savedGame) {
      return JSON.parse(savedGame);
    }
    return null;
  }
  // Save game state to localStorage
  function saveGameState(gameState) {
    localStorage.setItem(SAVE_KEY, JSON.stringify(gameState));
  }
  // Calculate amortizing loan payments
  function calculateAmortizingLoan(amount, interestRate, paybackPeriod) {
    const monthlyInterestRate = interestRate / 100 / 12;
    const numberOfPayments = paybackPeriod;
    const numerator = monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments);
    const denominator = Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1;
    const monthlyPayment = amount * (numerator / denominator);
    return monthlyPayment;
  }
  // Handle giving a loan
  function handleGiveLoan() {
    const gameState = loadGameState();
    if (!gameState) {
      alert("Game state not found!");
      return;
    }
    const loanAmount = parseFloat(document.getElementById("loanAmount").value);
    const interestRate = parseFloat(document.getElementById("interestRate").value);
    const loanRecipient = document.getElementById("loanRecipient").value;
    // Validate loan amount
    const lenderNation = gameState.nations["Zephyria"]; // Assuming Zephyria is the lender
    if (loanAmount < 1 || loanAmount > lenderNation.cash) {
      alert("Invalid loan amount. Please enter a value between 1 and your cash balance.");
      return;
    }
    // Validate interest rate
    if (interestRate < 0) {
      alert("Invalid interest rate. Please enter a non-negative value.");
      return;
    }
    // Calculate payback period
    const paybackPeriod = 10 - gameState.round;
    if (paybackPeriod <= 0) {
      alert("Cannot give a loan in the final round or after.");
      return;
    }
    // Calculate monthly payment
    const monthlyPayment = calculateAmortizingLoan(loanAmount, interestRate, paybackPeriod);
    // Deduct loan amount from the lender's cash
    lenderNation.cash -= loanAmount;
    // Notify the recipient
    const recipientNation = gameState.nations[loanRecipient];
    if (recipientNation) {
      const acceptLoan = confirm(
        `Zephyria has offered you a loan of ${loanAmount.toLocaleString()} at ${interestRate}% interest. Do you accept?`
      );
      if (acceptLoan) {
        // Add loan to recipient's debt schedule
        for (let i = 0; i < paybackPeriod; i++) {
          recipientNation.debtSchedule.push({
            round: gameState.round + i + 1,
            debtAmount: monthlyPayment,
            debtCoverage: monthlyPayment,
          });
        }
        // Add loan amount to recipient's cash
        recipientNation.cash += loanAmount;
        // Save updated game state
        saveGameState(gameState);
        alert("Loan accepted! The debt schedule has been updated.");
      } else {
        // Refund the loan amount to the lender
        lenderNation.cash += loanAmount;
        alert("Loan rejected. The loan amount has been refunded.");
      }
    } else {
      alert("Invalid recipient selected.");
    }
  }
  // Display loan notifications
  function displayLoanNotifications(gameState) {
    const loanNotificationsList = document.getElementById("loanNotificationsList");
    loanNotificationsList.innerHTML = ""; // Clear previous notifications
    Object.entries(gameState.nations).forEach(([nationName, nation]) => {
      if (nationName !== "Zephyria" && nation.debtSchedule.length > 0) {
        const notificationItem = document.createElement("li");
        notificationItem.textContent = `${nationName} has an active loan.`;
        loanNotificationsList.appendChild(notificationItem);
      }
    });
  }
  // Initialize page
  document.addEventListener("DOMContentLoaded", () => {
    const gameState = loadGameState();
    if (gameState) {
      displayLoanNotifications(gameState);
    } else {
      alert("Game state not loaded. Please start or load a game first.");
    }
    // Attach event listener for giving a loan
    document.getElementById("giveLoanButton").addEventListener("click", handleGiveLoan);
  });
</script>

Comments

Add a Comment