我正在制作一个石头剪刀游戏,我想要警报来确定谁选择了什么以及谁赢了,但警报不会弹出。我发现有多个错误回过头来修复它们,仔细检查了一切,甚至进行了三重检查,但警报仍然没有弹出?
这是三个功能中的一个(它们都相似):
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
}
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
答案 0 :(得分:0)
您无法返回提醒。警报是一种方法调用。删除警报前面的返回,警报将打开:
if(computerChoice === "rock"){
alert("Link and Computer both chose Rock! It's a Tie!");
}
答案 1 :(得分:0)
您不需要退货。所以,改变这个:
if(computerChoice === "rock"){
return alert("Link and Computer both chose Rock! It's a Tie!");
}
到此:
if(computerChoice === "rock"){
alert("Link and Computer both chose Rock! It's a Tie!");
}
答案 2 :(得分:0)
我认为问题出在所示的界线上:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
} // <-- I don't think you want this closing brace here
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
我指出的结束括号结束了rock()
功能。就目前而言,rock()
功能实际上并没有做任何事情;它随机地为一个局部变量赋值"rock"
,"paper"
或"scissors"
,但该函数在没有使用变量的情况下结束,因此该值将丢失。
当JavaScript首次加载到浏览器中时,其余代码将运行一次。此时,computerChoice
将为undefined
,因此您将收到JavaScript错误。
如果我们删除错误的大括号并重新格式化代码,我们会得到以下结果:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
我多次运行此功能。每次它随机警告三条消息中的一条。
答案 3 :(得分:0)
这种方法很有用,并且使用较少的弯路来实现目标:)
function rock() {
var replies = new Array(
'Link and Computer both chose Rock! It\'s a Tie!',
'Link chose Rock and Computer chose Scissors! Computer took a heart of damage!',
'Link chose Rock and Computer chose Paper! Link took a heart of damage!');
alert(replies[Math.floor(replies.length * Math.random())]);
}
澄清:
Math.random()返回[0..1&gt;
范围内的浮点数
replies.length * Math.random()返回范围为[0..3&gt;
的浮点数
Math.floor(replies.length * Math.random())返回0,1或2.