🎮 Player Health Bar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animated Health Bar</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.5s 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");
const battle = setInterval(() => {
// 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 + "%";
// Change bar color based on health
if (playerHealth > 50) {
healthBar.style.background = "green";
} else if (playerHealth > 20) {
healthBar.style.background = "orange";
} else {
healthBar.style.background = "red";
}
// Update text log
log.innerText = "Player Health: " + playerHealth;
// Stop battle when health is 0
if (playerHealth <= 0) {
clearInterval(battle);
log.innerText = "💀 Game Over! Player defeated.";
}
}, 1000); // 1000ms = 1 second between hits
}
</script>
</body>
</html>
Comments