Javascript颜色游戏

时间:2016-07-14 18:29:18

标签: javascript

我在互联网上寻找解决方案,但我不确定为什么这不会出现在浏览器中。它适用于javascript的repl,但由于某种原因它无法在我的谷歌浏览器中打开。

mvn versions:update-parent scm:check-local-modification -DallowSnapshots=false -DgenerateBackupPoms=false

4 个答案:

答案 0 :(得分:1)

您所写的内容无效HTML。

您的<script>代码必须放在HTML文档的<body><head>中,而不是在文档类型之前的最开始。

答案 1 :(得分:1)

没有关闭括号来匹配线上的那个:

while (!thenumber) {

使用适当的缩进和格式化会使这样的错误更容易找到。

答案 2 :(得分:0)

此HTML文件存在很多问题。我已经纠正了这些问题,但即使修复了它,它仍然编码很糟糕。但是,这是......

<!DOCTYPE html>
<html>
<head>
<script>
'use strict';
function numbergame() {
    var colors = ["Red", "Green", "Blue", "Orange", "Yellow", "Indigo", "Violet", "Gray", "Black", "White"];
    var random_color = colors[Math.round(Math.random()*colors.length)];
    var guesses = 0;
    var thecolor = false;
    var playerguess;
    var thenumber = false;
    while (!thenumber) {
        playerguess = prompt("I am thinking of a number color from this list:\n" + colors + "\nCan you guess which one it is?");
        guesses += 1;
        thenumber = checkguess(colors, playerguess, random_color, guesses);
    }
};

function checkguess(colors, playerguess, random_color, guesses) {
        if (!colors.includes(playerguess)) {
            alert("Please enter a valid color"); return false
        }

        if (playerguess < random_color) {
            alert("Hint: the answer is lower alphabetically.");
            return false;
        }

        if (playerguess > random_color) {
            alert("Hint: the answer is higher alphabetically.");
            return false;
        } else {
            alert("You've guessed the color! It was " + random_color + " and it took you " + guesses + " tries.");
            var myBody = document.getElementsByTagName("body")[0];
            myBody.style.background = random_color;
            return true;
        }
}
</script>
</head>
<body onload="numbergame()">
<h1>Color Game</h1>
</body>
</html>

这些问题是未声明的变量,缺少花括号,范围问题,错误位置的<script>标签等等。您最好自己从头开始编码,说实话。

我在Firefox 47.0.1上测试了这个。您可能会遇到其他浏览器兼容性问题,但我相信您可以从这里自行解决这些问题:)

答案 3 :(得分:-1)

numbergame函数中的while循环应如下所示:

while (!thenumber) {
    playerguess = prompt("I am thinking of a number color from this list:\n" +color +"\nCan you guess which one it is?");
    guesses+=1;
    thenumber = checkguess();
} // <-- this curly brace was missing