2017-03-09 45 views
0

你能帮我解决这个问题吗? 我想创建猜谜游戏,用户应该在提示中输入正确的颜色。我想创建猜谜游戏,用户应该在提示中输入正确的颜色

计算机猜测 - 一种颜色,用户应该给出正确答案 - 哪种颜色是正确的。我尝试为它创建正确的代码,但无法正常工作。 也许与变量或用的indexOf,否则不便的问题.... 谢谢你在先进

var target; 
    var guess_input; 
    var finished = false; 
    var colors; 
    var presentOrNot; 

    colors = ["aqua", "black", "white"]; 

    function do_game() { 
     var random_color = colors[Math.floor(Math.random() * colors.length)]; 
     target = random_color; 
     alert (target); 

     while (!finished) { 
      guess_input = prompt("I am thinking of one of these colors:\n\n" + colors + "\n\n What color am I thinking of?"); 
      guesses += 1; 
      finished = check_guess(); 
     } 
    } 
    function check_guess() { 
     presentOrNot = colors.indexOf(guess_input); 
     if (presentOrNot == target) { 
      alert ("It is my random color"); 
      return true; 
     } 
     else { 
      alert("It isn't my random color"); 
      return false; 
     } 
    } 
+3

是什么_ “不正常” _是什么意思? –

回答

1

indexOf返回指数(0,1,2 ......),但target是实际的颜色(aqua,black,..)。试试这个

function check_guess() { 
    if (guess_input.toLowerCase() === target) { 
     alert ("It is my random color"); 
     return true; 
    } 
    else { 
     alert("It isn't my random color"); 
     return false; 
    } 
} 

或者,这应该工作太

function check_guess() { 
    presentOrNot = colors.indexOf(guess_input); 
    if (presentOrNot === colors.indexOf(target)) { 
     alert ("It is my random color"); 
     return true; 
    } 
    else { 
     alert("It isn't my random color"); 
     return false; 
    } 
} 

我改变=====这是在JavaScript usually what you want

0

prompt命令返回string值。

在您的while循环中,如果您声明guess_input,请将所有prompt放入​​函数中。

0

我编辑并更正了您的代码。试试这个

var target; 
 
    var guess_input; 
 
    var finished = false; 
 
    var colors; 
 
    var presentOrNot; 
 
    var guesses = 0; /*initialized variable*/ 
 

 
    colors = ["aqua", "black", "white"]; 
 

 
    function do_game() { 
 
     var random_color = colors[Math.floor(Math.random() * colors.length)]; 
 
     target = random_color; 
 
     alert (target); 
 

 
     while (!finished) { 
 
      guess_input = prompt("I am thinking of one of these colors:\n\n" + colors + "\n\n What color am I thinking of?"); 
 
      guesses += 1; 
 
      finished = check_guess(); 
 
      
 
      if(guesses === 3) { 
 
      \t break; 
 
      } 
 
     } 
 
     
 
    } 
 
    function check_guess() { 
 
     presentOrNot = colors.indexOf(guess_input); 
 
     if (colors[presentOrNot] === target) { 
 
      alert ("It is my random color"); 
 
      return true; 
 
     } 
 
     else { 
 
      alert("It isn't my random color"); 
 
      return false; 
 
     } 
 
    } 
 
    //start the game--- 
 
    do_game();