gpt4 book ai didi

javascript - 如何让剪刀石头布游戏中的图像发生变化?

转载 作者:行者123 更新时间:2023-11-28 03:11:46 26 4
gpt4 key购买 nike

我正在尝试用 JavaScript 构建剪刀石头布游戏,但也有计算机将图像输出到 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”以供我选择,而计算机不会显示任何内容。我做错了什么?

最佳答案

你的逻辑不对,你在应该是==的地方使用了=

例如看我对这个方法的修改,你所有的方法都有这样的问题。

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";
}

关于javascript - 如何让剪刀石头布游戏中的图像发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30179489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com