gpt4 book ai didi

javascript - 如何在 HTML 5 和 javascript 中为简单的猜数字游戏随机设置生成的数字

转载 作者:行者123 更新时间:2023-11-28 04:00:32 25 4
gpt4 key购买 nike

我正在使用 JavaScript、CSS 和 HTML5 编写一个简单的游戏。

该游戏是一种简单的猜数字游戏,用户可以在其中调整从中猜数字的变量。

例如,在游戏中,用户可以设置要猜测的数字,即 0 - 5,当他猜测时,表单文本字段中会出现一个提示,显示他离正确随机生成的数字是更近还是更远.

如果用户猜对了,会出现提示。我遇到的问题是,当用户输入他的猜测值并按下猜测按钮时,每次都会出现提示,表明他猜对了,但事实并非如此。

此外,当用户猜测没有显示天气的提示时,他离正确的数字更近或更远,出现在猜测字段正上方的表单文本字段中。下面是我的游戏代码

var my_no, count;

function load() {
document.game.help.value = "Set range of numbers and press Start.";
}
function rnd(scale) {
var dd = new Date();
return
}
function range() {
var to = 1 + 1 * document.game.to.value;
count = 0;
my_no = rnd(to);
document.game.help.value = "Guess a number, enter it, and press Guess.";
}
function guess() {
var no = document.game.number.value;
count++;
if (no < my_no) document.game.help.value = "My number is greater than " + no + ".";
else if (no > my_no) document.game.help.value = "My number is less than " + no + ".";
else alert("It took you " + count + " attempts to unlock the key of the sphinx");
}
body {
background-image: url("egypt2.jpg");
}

* {
font-size: 100%;
font-family: Lithos Pro Regular;
font-size: 20px;
}

table {
border: 10px solid black;
margin: 0 auto;
}
<body onLoad="load()">


<Form name=game>
<Table>

<TD align=center colspan=8>Range of numbers</TD>
<TD align=center rowspan=8><input type=button value=" Start " onclick="range()"></TD>

<TR>
<TD align=center>From:<br><input type="number" name=from size=30></TD>
<TD align=center>To:<br><input type="number" name=to size=30></TD>
</TD>

<TR>
<TD align=center colspan=3><input type=text name=help size=45></TD>

<tr>
<td align=center colspan=3>

<input type="number" name=number size=30><input type=button value=" Guess " onclick="guess()"></TD>
</TR>
</table>
</form>
<p>
<center>
</center>
<p>
</body>

最佳答案

您的问题是变量“my_no”未定义,因为函数“rnd”不返回任何内容。假设您需要生成一个介于“From”和“To”(含)之间的数字,您应该像这样更改“rnd”函数:

function rnd(from, to) 
{
/* Returns a random number between from and to (inclusive) */

return Math.floor((Math.random() * (to - from + 1))) + from;
}

更改后,范围函数应如下所示:

function range() 
{
var to = parseInt(document.game.to.value);
var from = parseInt(document.game.from.value);

count = 0;

my_no = rnd(from, to);
document.game.help.value = "Guess a number, enter it, and press Guess.";
}

解锁狮身人面像很有趣 ;)

关于javascript - 如何在 HTML 5 和 javascript 中为简单的猜数字游戏随机设置生成的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43236795/

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