我使用JavaScript创建了一个Rock Paper剪刀游戏,我希望展示最终获胜的元素图像。
例如:
如果摇滚获胜:显示岩石的图像/ jpg
如果纸张获胜:显示纸张的图像/ jpg
以下是代码:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
}
else if (computerChoice <= 0.67) {
computerChoice = "paper";
}
else {
computerChoice = "scissors";
}
//console.log("Computer chooses: " + computerChoice);
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!" + " " + "Lets play again.";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins" + "<br>" + "You beat the computer, nice job!";
}
else {
return "paper wins" + "<br>" + "Your really smart computer beat you.";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins" + "<br>" + "You beat the computer, nice job!";
}
else {
return "scissors wins" + "<br>" + "Your really smart computer beat you.";
}
}
else if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins" + "<br>" + "Your really smart computer beat you.";
}
else {
return "scissors win" + "<br>" + "You beat the computer, nice job!";
}
}
} //closes compare function
document.write("Computer chose: " + computerChoice + "<br>");
document.write(compare(userChoice, computerChoice));
答案 0 :(得分:0)
基本上你可以使用以下选择器/方法来改变HTML img标签的src图像:
document.getElementById(“your-img”)。src ='rock.jpg';
当然,您必须相应地设置图像路径和ID。
答案 1 :(得分:0)
而不是使用
computerChoice = Math.random()
使用math.floor()
computerChoice = Math.floor((Math.random() * 3) + 1)
现在用它来说明计算机的含义:
if(computerChoice == '1') { computerChoice = 'stone' };
if(computerChoice == '2') { computerChoice = 'paper' };
if(computerChoice == '3') { computerChoice = 'scissors' };