我正在想放一段时间的循环,所以这样的比赛停止时,您或计算机必须小于或等于0的健康和之后显示一条消息,说有人赢了,但无论我如何尝试或我把他们放在哪里,我似乎无法得到一个while循环工作。如果您尝试使用在JavaScript中while循环这个程序就会陷在while循环永远请帮我:)希望把JavaScript代码在while循环,这样,当cphealth或球员的健康是<= 0时,游戏停止
$(document).ready(function() {
var health = 100;
var cphealth = 100;
var lightAttacks = -20;
var block = 10;
var Ties = 0;
function randomGen() {
var max = 3;
var min = 1;
var answer = Math.floor(Math.random() * (max - min + 1)) + min;
return answer;
//sets up the random number generator
}
var name = "";
var userChoice = "";
var compChoice = 99;
$("#lightAttack").click(function() {
userChoice = "lightAttack"
compChoice = randomGen();
whoWon(userChoice, compChoice);
});
$("#block").click(function() {
userChoice = "block"
compChoice = randomGen();
whoWon(userChoice, compChoice);
});
$("#heal").click(function() {
userChoice = "heal"
compChoice = randomGen();
whoWon(userChoice, compChoice);
//sets up the random number generator
});
function whoWon(user, comp) {
var winnerMessage = "ERROR";
if (user == 'lightAttack') {
if (comp == 1) { //developer says 1 = attack back
winnerMessage = "Computer attacked back";
(health = health + lightAttacks) && (cphealth = cphealth + lightAttacks)
} else if (comp == 2) { //developer says 2 = block next attack
winnerMessage = "Computer blocked your attack and reflected some damage";
health = health - 5
} else { //developer says 3 = heal and its just else 1 or 2 ot must be 3
winnerMessage = "Computer heals back part of your attack damage";
cphealth = cphealth - 10
}
}
if (user == 'block') {
if (comp == 1) { //developer says 1 = lightAttack
winnerMessage = "You blocked the computer attack and reflected some damage";
cphealth = cphealth - 5
} else if (comp == 2) { //developer says 2 = block
winnerMessage = "Nothing happened because you both blocked";
health = health + 0
} else { //developer says 3 = heal and if its not 1 or 2 ot must be 3
winnerMessage = "Computer heals 10 health";
cphealth = cphealth + 10
}
//sets up the results for if the user picks block
}
if (user == 'heal') {
if (comp == 1) { //developer says 1 = lightAttack
winnerMessage = "Computer attacked";
health = health - 10
} else if (comp == 2) { //developer says 2 = block
winnerMessage = "Computer blocked";
health = health + 10
} else { //developer says 3 = heal and if its not 1 or 2 ot must be 3
winnerMessage = "You both picked heal";
health = health + 10;
cphealth = cphealth + 10;
}
}
if (comphealth <= 0) {
alert("You Win!")
}
document.getElementById("result").innerHTML = winnerMessage;
document.getElementById("myhealth").innerHTML = health;
document.getElementById("comphealth").innerHTML = cphealth;
}
});
你在你的代码中没有while循环,它完美的作品,你并不需要添加一个。你有几个选择:(1)从按钮中删除所有的听众。这是最简单的。 (2)检查每个函数调用/事件侦听器之前是否赢得了 – MayorMonty