我试图制作一个显示一系列图像的游戏,具体取决于用户放入输入框的数量。我希望它能够显示来自我的图像数组的随机图像,无论用户多次将其设置为显示它。
这是我的JavaScript:
var numLeaves = 0;
var numSeq = ["1.jpg","2.png","3.jpg","4.jpg","5.png","6.jpg","7.jpg","8.jpg","9.jpg","0.jpg"];
function startGame() {
while (1 < 10) {
randomNum = Math.floor((Math.random() * numSeq.length));
if (randomNum === 0) {
numLeaves = 1;
} else if (randomNum == 1) {
numLeaves = 2;
} else if (randomNum == 2) {
numLeaves = 3;
} else if (randomNum == 3) {
numLeaves = 4;
} else if (randomNum == 4) {
numLeaves = 5;
} else if (randomNum == 5) {
numLeaves = 6;
} else if (randomNum == 6) {
numLeaves = 7;
} else if (randomNum == 7) {
numLeaves = 8;
} else if (randomNum == 8) {
numLeaves = 9;
} else if (randomNum == 9) {
numLeaves = 0;
}
document.getElementById("picture").src = numSeq[randomNum];
setInterval(function(){document.getElementById("picture").src = ""}, 1500);
i++;
}
}
function submitInput() {
if (document.getElementById("leaveGuess").value == numLeaves) {
document.getElementById("result").innerHTML = "Correct!";
}
else
{
document.getElementById("result").innerHTML = "Incorrect... There were " + numLeaves + " leaves on the shamrock";
}
}
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="rep.css">
<script type="text/javascript" src="rep.js"></script>
</head>
<body>
<div id="test"></div>
<div id="content">
<div id="title" class="center">
<h1>Repetitive</h1>
<p>Created by Daniel Hancock</p>
<h2>Instructions:</h2>
<p>In under one second memorize the amount of leaves on the shamrock. <br> After one second, you will be asked to enter the number of leaves that you saw on the shamrock.</p>
<label for="numSequence"><strong>Length:</strong></label>
<input id="numSequence"> <br>
<button onclick="startGame()" id="startButton">New</button>
</div>
<div id="display" class="center">
<img src="" id="picture" width="215" height="215">
<div id="guessing" class="center">
<input id="leaveGuess">
<button onclick="submitInput()">Submit</button>
<p id="result"></p>
</div>
</div>
</div>
</body>
</html>
向我解释,就像我五岁。
答案 0 :(得分:0)
我不明白你的问题,但我在代码中发现了一些问题:
1)你没有将numLeaves声明为全局变量(也许)并且你在不使用他的情况下将他更新10次。
2)set var i = 0;在startGame函数的开头或更好的解决方案是使用而不是
3)为什么你做randomNum === 0而不是randomNum == 0?
提示: 你可以写 numLeaves =(randomNum + 1)%10; 而不是10 if命令
答案 1 :(得分:0)
我可以在这里看到一个主要问题 - 你还没有在任何地方声明i
。在while
循环中,您将条件设置为(1 < 10)
,这将始终为真。
我建议将其更改为使用这样的for循环:
for (int i=0; i<10; i++)
{
randomNum = Math.floor((Math.random() * numSeq.length));
if (randomNum == 9)
{
numLeaves = 0;
}
else
{
numLeaves = randomNum + 1;
}
document.getElementById("picture").src = numSeq[randomNum];
setInterval(function(){document.getElementById("picture").src = ""}, 1500);
}
希望这有帮助。