我已经创建了一个摇滚,纸张,剪刀游戏来学习JS和jQuery。我想弄清楚的是如何在按钮点击时调用相同的功能,这样数字就会改变,从而给游戏带来不同的结果。
我已经为此制作了一个jsFiddle演示:
https://jsfiddle.net/iKaleb/v1kbxg2g/3/
基本上,在小提琴示例中,我想点击蓝色框,计算机选择每次都会改变。 compChoice()
是随机数生成器,但是当我通过单击按钮再次调用它时,它不会更改计算机选择。
非常感谢任何帮助!
var player = "Rock";
var computer = compChoice();
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function vsChoice() {
if (player === "Rock") {
if (computer === "Scissors") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Paper") {
if (computer === "Rock") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Scissors") {
if (computer === "Paper") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
}
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
答案 0 :(得分:2)
我刚编辑了你的js,它正在为我工作
{{1}}
答案 1 :(得分:1)
您需要调用生成选择的函数,而不是每次都显示相同的值:
$('#box').on('click', function() {
computer = compChoice();
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
请注意,最好将选项作为参数传递给vsChoice
函数,而不是使用全局变量。
答案 2 :(得分:1)
您正在打印初始计算值。
试试这个
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + compChoice());
vsChoice();
});
OR
刷新计算机值var
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
debugger;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
computer = pick;
return pick;
}