帮我用JS+CSS+html设计出一个战斗界面要求如下:两个方框AB初始满血100背景绿色。两个方框战斗A打B一下随机扣血每一次扣血都会头部都会显示扣血数量并且会抖动一下。当血量剩余20以下的时候背景变红。同理B打A也是一样。谁的血量达到0就消失。剩下的提示获胜。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Battle Interface</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="battle-container">
<div id="boxA" class="box">
<span id="healthA" class="health">100</span>
</div>
<div id="boxB" class="box">
<span id="healthB" class="health">100</span>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (style.css):
.battle-container {
display: flex;
justify-content: space-between;
margin-top: 100px;
}
.box {
width: 200px;
height: 200px;
background-color: #00ff00;
border: 1px solid black;
position: relative;
}
.health {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
}
.box.shake {
animation: shake 0.5s;
}
@keyframes shake {
0% { transform: translateX(0); }
25% { transform: translateX(-10px); }
50% { transform: translateX(10px); }
75% { transform: translateX(-10px); }
100% { transform: translateX(0); }
}
.box.low-health {
background-color: #ff0000;
}
JS (script.js):
const boxA = document.getElementById("boxA");
const boxB = document.getElementById("boxB");
const healthA = document.getElementById("healthA");
const healthB = document.getElementById("healthB");
let healthValueA = 100;
let healthValueB = 100;
function updateHealth() {
healthA.innerText = healthValueA;
healthB.innerText = healthValueB;
if (healthValueA <= 20) {
boxA.classList.add("low-health");
} else {
boxA.classList.remove("low-health");
}
if (healthValueB <= 20) {
boxB.classList.add("low-health");
} else {
boxB.classList.remove("low-health");
}
}
function shakeBox(box) {
box.classList.add("shake");
setTimeout(() => {
box.classList.remove("shake");
}, 500);
}
function attackBox(attacker, defender) {
const damage = Math.floor(Math.random() * 10) + 1;
defender -= damage;
shakeBox(defender === boxA ? boxA : boxB);
updateHealth();
if (defender <= 0) {
defender.style.display = "none";
alert(`${attacker.id} wins!`);
}
}
boxA.addEventListener("click", () => {
attackBox(boxA, boxB);
});
boxB.addEventListener("click", () => {
attackBox(boxB, boxA);
});
这个代码会创建一个战斗界面,其中有两个方块AB,初始血量为100,背景为绿色。点击A方块或B方块时,会随机扣除对方一定的血量,并在头部显示扣血数量,并且方块会抖动一下。当血量低于等于20时,方块背景会变为红色。当血量为0时,方块会消失,并弹出提示谁获胜
原文地址: http://www.cveoy.top/t/topic/iSg7 著作权归作者所有。请勿转载和采集!