2017-03-09 36 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();