Player Headshot Health Reduction System Using While Loop

Player Headshot Health Reduction System Using While Loop

Player Headshot Health Reduction System Using While Loop

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Health Bar Example</title>

  <style>

    body {

      font-family: Arial, sans-serif;

      text-align: center;

      margin-top: 50px;

    }


    .health-container {

      width: 300px;

      height: 30px;

      border: 2px solid #333;

      margin: 20px auto;

      border-radius: 8px;

      overflow: hidden;

    }


    .health-bar {

      height: 100%;

      width: 100%;

      background: green;

      transition: width 0.3s ease;

    }


    #log {

      margin-top: 20px;

      font-size: 18px;

    }


    button {

      padding: 10px 20px;

      margin-top: 20px;

      font-size: 16px;

      cursor: pointer;

    }

  </style>

</head>

<body>

  <h1>🎮 Player Health Bar</h1>


  <div class="health-container">

    <div class="health-bar" id="healthBar"></div>

  </div>


  <div id="log">Player Health: 100</div>

  <button onclick="startBattle()">Start Battle</button>


  <script>

    function startBattle() {

      let playerHealth = 100;

      const healthBar = document.getElementById("healthBar");

      const log = document.getElementById("log");


      // Loop until health is 0

      while (playerHealth > 0) {

        // Random damage between 10 and 30

        let damage = Math.floor(Math.random() * 21) + 10;

        playerHealth -= damage;


        if (playerHealth < 0) playerHealth = 0;


        // Update health bar visually

        healthBar.style.width = playerHealth + "%";


        // Update text log

        log.innerText = "Player Health: " + playerHealth;


        // This delay is needed to see the health drop step by step

        // (but while loop runs instantly, so let's break it using setTimeout)

      }


      // Fix: add Game Over message after loop ends

      if (playerHealth <= 0) {

        log.innerText = "💀 Game Over! Player defeated.";

        healthBar.style.background = "red";

      }

    }

  </script>

</body>

</html>


Health Bar Example

🎮 Player Health Bar

Player Health: 100

Comments