我正在尝试制作一个游戏,它根据用户在输入框中输入的数字显示一系列图像。我想让它从我的图像数组中显示一个随机图像,无论用户设置多少次来显示它。
这是我的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>把它解释给我,就像我是个五岁的孩子。
发布于 2015-03-13 00:26:22
我不理解你的问题,但我在代码中发现了一些问题:
1)您没有将numLeaves声明为全局变量(可能),并且您在没有使用他的情况下更新了他10次。
2)在startGame函数的开头设置var i= 0;或者使用更好的解决方案代替while
3)为什么使用randomNum === 0而不是randomNum == 0?
提示:您可以编写numLeaves = (randomNum + 1) % 10;而不是10个if命令
发布于 2015-03-13 01:12:49
我可以在这里看到一个主要问题--您还没有声明i anywhere。在您的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);
}希望这能有所帮助。
https://stackoverflow.com/questions/29014562
复制相似问题