用Javascript简单猜我的数字游戏

用Javascript简单猜我的数字游戏,javascript,Javascript,我正在开发一个javascript程序,它是一个简单的猜测游戏。它会产生一个介于1和10之间的随机数,并提供一个输入字段和一个按钮供用户猜测。该程序在每次猜测之后都会告诉用户猜测的是过高还是过低,并且它会跟踪用户获得正确答案所需的猜测次数,当用户猜对时,它会显示一条祝贺消息 我很难让它正常工作。页面显示正确,但当我输入猜测并单击提交按钮时,什么也没有发生 这是我的密码: <html> <head> <title>Guess My Num

我正在开发一个javascript程序,它是一个简单的猜测游戏。它会产生一个介于1和10之间的随机数,并提供一个输入字段和一个按钮供用户猜测。该程序在每次猜测之后都会告诉用户猜测的是过高还是过低,并且它会跟踪用户获得正确答案所需的猜测次数,当用户猜对时,它会显示一条祝贺消息

我很难让它正常工作。页面显示正确,但当我输入猜测并单击提交按钮时,什么也没有发生

这是我的密码:

<html>
    <head>
        <title>Guess My Number</title>

        <script type="text/javascript">
            var game = {
                num : 0,
                turns : 1,
                reset : function() {
                    this.turns = 1;
                    this.newNum();
                },
                newNum() : function() {
                    this.num = parseInt(Math.random() * 10) +1;
                },
                checkNum() : function(guess) {
                    try {
                        guess = parseInt(guess);
                    }
                    catch(e) {
                        alert("Enter a guess!");
                        this.turns++;
                        return false;
                    }

                    if (guess == this.num) {
                        alert("Correct! It took you " + this.turns + "turns to guess my number.");
                        return true;
                    }
                    else if(guess > this.num) {
                        alert("Your guess is too high. Try again.");
                        this.turns++;
                        return false;
                    }
                    else (guess < this.num) {
                        alert("Your guess is too low. Try again.");
                        this.turns++;
                        return false;
                    }
                }
            };

            function guessNumber() {
                var guess = document.getElementById("guess").value;
                game.checkGuess(guess);
            }

            function resetGame() {
                game.reset();
            }

            resetGame();
        </script>
    </head>

    <body>
        <h1>Would You Like To Play A Game?</h1>
        <h2>Thank you for checking out my game. Good luck!</h2>
        <h3>Created by Beth Tanner</h3>
        <h2>Directions:</h2>
        <p>
            The game is very simple. I am thinking of a number between 1
            and 10. It is your job to guess that number. If you do not guess
            correctly on your first attempt, don't worry, you can keep guessing 
            until you guess the correct number.
        </p>
        <p>
        Your Guess: <input type="text" id="guess" size="10" />
        <br />
        <input type="button" value="Sumbit Guess" onclick="guessNumber()" />
        <input type="button" value="Reset Game" onclick="resetGame()" />
        </p>
    </body>
</html>
我以前从未真正使用过Javascript,所以我知道这可能是我忽略的一件非常基本的事情。有没有办法解释为什么不能正常工作?

您的变量猜测没有定义

只需使用以下命令初始化它:

var guess = 0;
但是要小心,num有可能初始化为0。因此,用户没有做任何事情就立即猜测

var num = Math.random() *10 + 1;

BR

首先应该调用函数,可以做的一件事是:

<input type = "button" value = "Submit Guess" onclick="guessNumber()">
然后在java脚本中将变量guess初始化为:

这应该可以做到

编辑:
还要确保Math.random返回一个整数,正如其他人建议使用Math.ceil

您的代码有几个问题:

Math.random*10将返回类似于8.523525235的内容,因此您很难将其与任何猜测相匹配。相反,使用Math.ceilMath.random*10。这将生成一个随机数,然后向上舍入到最接近的整数

在JavaScript代码中,您在最后一行调用guessNumber,这将在浏览器到达该行时立即执行该函数。这将意味着在用户进行任何猜测之前执行函数。相反,您需要将事件侦听器附加到按钮,以便在单击按钮时调用guessNumber。比如:

document.getElementById'button'。addEventListener'click',guessNumber

现在,您没有以任何方式设置变量guess。您需要获取文本框的值并将其指定给guess。比如: guess=document.getElementById'textbox'。值

在这里使用while循环并不合适,因为用户每次都使用文本框和按钮提交猜测。使用while循环有很多方法可以做到这一点,但是让我们继续使用当前的设置。 您需要类似于以下内容的内容:

HTML:

JS:


这是一个例子。我添加了一些重置功能。

其他几个答案指出了测试代码中的一些问题:

type=提交,但不包含标记。 拼写错误的变量名turns而不是turns。 while循环的使用 按钮和JavaScript之间没有事件连接 这是一个简单的代码示例,在JavaScript中有很多方法可以解决这个问题。这是我的方法

当创建一个简单的游戏板时,页面不需要重新加载,我喜欢创建一个游戏对象。在JavaScript中,可以通过多种方式创建对象。但最简单的一点是:

var game = {};
这将创建一个没有属性或方法的空对象。要创建两个属性,请执行以下操作:

var game = {
    num: 0,
    turns: -1
};
这些属性中的每一个都可以像var x=game.num;一样全局引用;。要使用函数创建对象,请执行以下操作:

var game = {
    num: 0,
    turns: 0,
    reset: function() {
        this.turns = 0;
        //get a random integer between 1 and 10
        this.num = parseInt(Math.random() * 10) + 1;
        //Note: "this" lets you refer to the current object context. "game" in this case.
        //There are a couple of ways to force the value to an Int, I chose parseInt
    }
};
游戏现在有一个Game.reset函数,可以将Game.tures设置为0并获得一个新的Game.num。下面是我的示例的完整javascript代码,与上面的示例略有不同:

<script type="text/javascript">
    //Create an object to hold the game info
    var game = {
        num : 0,
        turns : 0,
        reset : function() {
            //function to reset 
            this.turns = 0;
            this.newNum();
        },
        newNum : function() {
            //get a random integer between 1 and 10
            this.num = parseInt(Math.random() * 10) + 1;
        },
        checkGuess : function(guess) {
            //try to convert the guess into a integer
            try {
                guess = parseInt(guess);
            } catch(e) {
                alert("Enter a guess!");
                this.turns++;
                return false;
            }

            //perform strict check of equality
            if (guess === this.num) {
                alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
                return true;
            } else if (guess > this.num) {
                alert("Your guess is too high. Try again.");
                this.turns++;
                return false;
            } else {
                alert("Your guess is too low. Try again.");
                this.turns++;
                return false;
            }
        }
    };


    function guessNumber() {
        var guess = document.getElementById("guess").value;
        game.checkGuess(guess);
    }

    function resetGame() {
        game.reset();
    }

    resetGame();
</script>
这里有一个例子,我相信,你希望它的运作方式

更新
正如我刚才所说,有很多方法可以做到这一点

var-tunrs=0;应为var匝数=0;正如@Musa提到的,修复并初始化为某个值,它不会在任何if条件下运行。您在哪里设置猜测?您的脚本中没有任何内容要求在单击“提交”按钮时运行函数。您的说明表明您考虑的是非十进制数字。但是Math.random*10将返回一个带分数的数字。你在哪里去掉分数?我认为让玩家猜所有的小数位数是不公平的这是我想知道的@Barmar的事情之一,我不知道怎么做。谢谢你指出我的拼写错误,我想我已经习惯了自动拼写检查。这很有帮助,但是,当我点击“猜测”按钮时,什么也没发生。@BethTanner这很奇怪,小提琴对我很有用。你用的是什么浏览器?小提琴对我来说也很管用,但当我在自己的代码中尝试它时,按钮仍然不起作用。我想我一定是打错了什么东西,但我甚至试着把它复制粘贴到记事本上,结果都是一样的。我正在使用Firefox,但也在Chrome和Internet Explorer上试用过。@Bethtaner确保所有id名称都是正确的。另外,您是否将此代码放在任何其他函数或类似的函数中?出于某种原因
n我在自己的代码中实现了这一点,但按钮仍然不能正常工作。我可以单击任意一个按钮,但什么也没有发生。请仔细检查按钮上的onclick属性,并检查示例中的JavaScript函数。在游戏目标代码下面有几个函数。我更新了我最新的代码。当我查看它时,我没有看到任何错误,但我肯定遗漏了一些东西。您检查过控制台以查看是否存在任何JavaScript错误吗?我得到以下错误:SyntaxError:missing:after property id project2.html:13但是:存在,所以不确定发生了什么,未声明HTML文档的字符编码。如果文档包含US-ASCII范围之外的字符,则在某些浏览器配置中,文档将呈现乱码文本。页面的字符编码必须在文档或传输协议中声明,并且ReferenceError:guessNumber未定义
var game = {};
var game = {
    num: 0,
    turns: -1
};
var game = {
    num: 0,
    turns: 0,
    reset: function() {
        this.turns = 0;
        //get a random integer between 1 and 10
        this.num = parseInt(Math.random() * 10) + 1;
        //Note: "this" lets you refer to the current object context. "game" in this case.
        //There are a couple of ways to force the value to an Int, I chose parseInt
    }
};
<script type="text/javascript">
    //Create an object to hold the game info
    var game = {
        num : 0,
        turns : 0,
        reset : function() {
            //function to reset 
            this.turns = 0;
            this.newNum();
        },
        newNum : function() {
            //get a random integer between 1 and 10
            this.num = parseInt(Math.random() * 10) + 1;
        },
        checkGuess : function(guess) {
            //try to convert the guess into a integer
            try {
                guess = parseInt(guess);
            } catch(e) {
                alert("Enter a guess!");
                this.turns++;
                return false;
            }

            //perform strict check of equality
            if (guess === this.num) {
                alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
                return true;
            } else if (guess > this.num) {
                alert("Your guess is too high. Try again.");
                this.turns++;
                return false;
            } else {
                alert("Your guess is too low. Try again.");
                this.turns++;
                return false;
            }
        }
    };


    function guessNumber() {
        var guess = document.getElementById("guess").value;
        game.checkGuess(guess);
    }

    function resetGame() {
        game.reset();
    }

    resetGame();
</script>
<h1>Would You Like To Play A Game?</h2>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Instructions</h2>
<p>
    The game is very simple, I am thinking of a non-decimal number between 1 and 10
    and it is your job to guess what that number is. If you do not guess my number 
    correctly on your first attempt, that's ok, you can keep guessing until you are correct.
</p>
<p>
    Your guess:<input type="text" id="guess" size = "10" />
    <br />
    <input type="button" value = "Submit Guess" onclick="guessNumber()" />
    <input type="button" value = "Reset Game" onclick="resetGame()" />
</p>