我正在尝试用JavaScript构建一个Rock Paper Scissors游戏,但也有计算机将图像输出到HTML文档的地方。我已经尝试了所有我知道的东西,但它不会起作用。这是HTML:
<!DOCTYPE html>
<html>
<head>
<script src="Rock Paper Scissors.js"></script>
</head>
<body>
<p>Your choice:<img id="myImage" onafterprint="userImgDisplay()" src="blank.png" width="250px" height="250px"/>The computer's choice:<img id="myImage" onload="comImgDisplay()" src="blank.png" width="250px" height="250px"/>
</p>`
这是JavaScript:
var userChoice = prompt("Do you choose rock, paper or scissors?","Don't use articles (i.e. the, a, etc.)").toLowerCase();
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
function userImgDisplay() {
var image = document.getElementById('myImage');
if (userChoice = "rock") {
image.src = "rock.png";
}else if (userChoice = "paper") {
image.src = "paper.png";
}else if (userChoice = "scissors") {
image.src = "scissors.png";
}
}
function comImgDisplay() {
var image = document.getElementById('myImage');
if (computerChoice = "rock") {
image.src = "rock.png";
}else if (computerChoice = "paper") {
image.src = "paper.png";
}else if (computerChoice = "scissors") {
image.src = "scissors.png";
}
}
“rock.png”,“paper.png”和“scissors.png”基于各自的项目,“blank.png”只是一个透明的图像。这个程序将始终显示“rock.png”供我选择,而不是计算机的任何内容。我做错了什么?
答案 0 :(得分:1)
您的逻辑不正确,您使用=
应该是==
例如,查看我对此方法的更改,您在所有方法中都会出现类似问题。
function comImgDisplay() {
var image = document.getElementById('myImage');
if (computerChoice == "rock") {
image.src = "rock.png";
}else if (computerChoice == "paper") {
image.src = "paper.png";
}else if (computerChoice =="scissors") {
image.src = "scissors.png";
}
}
为简单起见,您可以这样做:
function comImgDisplay() {
var image = document.getElementById('myImage');
image.src = computerChoice + ".png";
}
答案 1 :(得分:-1)
如果你正在制作游戏,我推荐使用jQuery。
但如果你想这样做,那么这就是代码。我也修复了一些语法错误。
var userChoice = prompt("Do you choose rock, paper or scissors?",
"Don't use articles (i.e. the, a, etc.)").toLowerCase();
var computerChoice = Math.random();
if (computerChoice < 0.34) computerChoice = "rock";
else if (computerChoice <= 0.67) computerChoice = "paper";
else computerChoice = "scissors";
['userImgDisplay', 'comImgDisplay'].forEach(function(element) {
window[element] = function() {
var image = document.getElementById('myImage');
if (userChoice == "rock") image.setAttribute("src", "rock.png");
else if (userChoice == "paper") image.setAttribute("src", "paper.png");
else if (userChoice == "scissors") image.setAttribute("src", "scissors.png");
}
});