尝试通过不断减去随机数来使hp栏从200下降到0,但我只能设法存储新值一次。然后,如果我单击调用该函数的按钮,它将再次从200减去而不是先前存储的值。我该如何解决?在这里生气
这是我的javascript:
window.onload = function() {
document.getElementById("hpLeft1").innerHTML= "200/200";
document.getElementById("hpLeft2").innerHTML = "200/200";
};
var myHit = Math.floor(Math.random() * 40 + 1);
var dragonHit = Math.floor(Math.random() * 40 + 1);
var playerHitpoints, dragonHitpoints = 200;
function play() {
var myHit = Math.floor(Math.random() * 40 + 1);
var dragonHit = Math.floor(Math.random() * 40 + 1);
dragonHitpoints -= dragonHit;
playerHitpoints -= myHit;
document.getElementById("DragonHit").innerHTML = dragonHit;
document.getElementById("MyHit").innerHTML = myHit;
document.getElementById("hpLeft1").innerHTML = dragonHitpoints + "/200";
document.getElementById("hpLeft2").innerHTML = playerHitpoints + "/200";
}
答案 0 :(得分:1)
您想要更新dragonHitpoints
和playerHitpoints
的值。
function play() {
var myHit = Math.floor(Math.random() * 40 + 1);
var dragonHit = Math.floor(Math.random() * 40 + 1);
// Update the dragon's HP
dragonHitpoints -= dragonHit;
// Update the player's HP
playerHitpoints -= myHit;
document.getElementById("DragonHit").innerHTML = dragonHit;
document.getElementById("MyHit").innerHTML = myHit;
document.getElementById("hpLeft1").innerHTML = dragonHitpoints + "/200";
document.getElementById("hpLeft2").innerHTML = playerHitpoints + "/200";
}
答案 1 :(得分:0)
您的代码中存在问题。您正在声明局部变量,它们会覆盖外部变量:
function play() {
var myHit = Math.floor(Math.random() * 40 + 1);
var dragonHit = Math.floor(Math.random() * 40 + 1);
这应该是
function play() {
myHit = Math.floor(Math.random() * 40 + 1);
dragonHit = Math.floor(Math.random() * 40 + 1);
重用外部变量。