Javascript色彩猜谜游戏

时间:2015-10-25 23:04:40

标签: javascript html

我正在练习我的javascript编码,通过编写一个颜色猜谜游戏,其中有一组颜色,一个将随机选择作为目标颜色。然后将提示用户选择颜色。选择通过一些标准,如果正确,页面的背景颜色会更改以匹配正确的颜色。这些是游戏的基础知识。我甚至无法获得要运行的代码的警报。我不知道这个问题。谢谢。

这是我的代码。

<!doctype html>
<html>
    <body onload="do_game()">
        <script> 
            alert("ok");
            var colors = ["coral", "olive", "khaki", "lime", "red", "maroon", "yellow", "green", "orchid"];
            var alpha_colors = colors.sort();
            return alpha_colors;
            var finished = false;
            var guesses = 0;

            function do_game(){
                alert("ok so far");
                var num_colors = colors.length-1;
                var target = colors[math.floor.random()*num_colors]
                do{
                    var color_guess=prompt("I am thinking of these colors \n\n"+alpha_colors+"What color am I thinking of?");
                    guesses += 1;
                    finished=checkguess();
                } while(finished=false);
            }

            function checkguess(){
                if(colors.indexOf(color_guess)=-1) {
                    alert("Sorry.  I don't recognize your color. \n\n Please try again. ");
                    return false;
                }
                if(color_guess<target) {
                    alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically lower than mine");
                    return false;
                }
                if(color_guess>target) {
                    alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically higher than mine");
                    return false;
                }
                alert("Congratulations! You have guessed the color! \n\n It took you "+guesses+"guesses to finish the game! \n\n You can see the color in the background");                     
                return true;
            }
            style.background-color=target
        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

你犯了一些初学者的错误。

  1. 使用&#34;返回&#34;你结束当前范围内的一切。所以 当您在第4行返回alpha_colors时,您的代码将在该行之后返回 永远不会跑。
  2. 这不是你按字母顺序比较字符串的方式。
  3. math.floor.random()不是你如何制作一个随机数。下次 尝试Math.floor(Math.random()* maxNumber);
  4. 当你比较两件事时,使用==或===。永远不会&#34; =&#34;! &#34; =&#34;在编程中不同于&#34; =&#34;在数学。使用&#34; =&#34;当你想将值设置为变量并使用&#34; ==&#34;当你想比较两件事。
  5. &#13;
    &#13;
    <!doctype html>
    <html>
    
    <head>
    </head>
    
    <body onload="do_game()">
      <script src="script.js"></script>
    </body>
    
    </html>
    &#13;
    {{1}}
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

脚本标记的第4行有一个return语句:

return alpha_colors;

返回语句只能在函数内部。此外,您正在引用函数&#34; do_game&#34;在你真正定义它之前。

相关问题