2017-04-06 8 views
1

プレイヤーがどの色が保存されているのかを推測しなければならない小さなゲームを作ります。 最終的な結果は、プレーヤーが正しく推測するとメッセージが表示され、背景色が変わることです。しかし、私の背景色は、ダイアログボックスを閉じた後にのみ変化します。背景色の変更が予期しないほど遅くなる

ここにコードがあります。問題の部分が最後です。

<!DOCTYPE HTML> 
<html> 
<body onload="do_game()"> 

<script> 
var colors = ["blue","red","yellow","green","brown", 
      "magenta","purple","aqua","coral", 
      "violet","pink","grey","cyan","black","white"]; 
var target; 
var guess_count = 0; 
var guess_input; 
var game_end; false; 

function do_game(){ //Start of function do_game // 
     colors.sort(); 
     target = Math.floor(Math.random() * colors.length); 
     alert(colors[target]); 

     do { 
     guess_input = prompt(
     "I am thinking of one of these colors \n\n" + 
     colors +"\n\nWhat color am I thinking of?") 

     guess_count ++; 

     } 
     while (check_guess()); 
     } //end of function do_game // 

function check_guess(){ //start of function check_guess// 
     var color_guess = colors.indexOf(guess_input); 
     if (color_guess < 0) 
      alert("I don't recognise that color!\n\n" 
       + "Please try again"); 
     else if (color_guess < target) 
      alert("Sorry your guess is not correct!\n\n" 
       + "Hint: Your guess is aphebetically lower\n\n" 
       + "Please try again!"); 
     else if (color_guess > target) 
      alert("Sorry your guess is not correct!\n\n" 
       + "Hint: Your guess is aphebetically higher\n\n" 
       + "Please try again!"); 
     else { 
      document.body.style.background = colors[target]; 
      alert("Congratulations!\n\n" + "You guessed " + colors[target] 
       + "\n\nThis is correct!\n\n" 
       + "It took you " + guess_count + " guesses"); 
      return false; 
     } 
      return true; 
     } 
</script> 
</body> 
</html> 
+0

あなたが応答するまで、Javascriptの実行を停止するアラートボックスを使用しています。ユーザーに連絡するには、通知の 'div'(またはそのようなもの)を使用する必要があります。 – Sablefoste

答えて

0

問題は、アラートボックスが応答するまで、JavaScriptのフローを停止するという問題です。警告ボックスが呼び出される前に、setTimeout機能を使用して、1ミリ秒の遅延を設定することでこれを回避することができます

else { 
    document.body.style.background = colors[target]; 
    setTimeout(makeTimeoutFunc(), 1); // 1 millsecond 
    return false; 
} 

...

function makeTimeoutFunc() { 
    return function() { 
     alert("Congratulations!\n\n" + "You guessed " + colors[target] + "\n\nThis is correct!\n\n" + "It took you " + guess_count + " guesses"); 
    } 
} 

を私はこれを展示JSFiddleを作成しましたhere

希望すると便利です。 :)

+0

恐ろしい!新しいことを学び、私の問題を解決しました。乾杯:) – ConorHalpin