2012-03-02 5 views
-3

사용자가 올바른 번호를 추측하면 사용자가 다시 게임을 할 것인지 물어볼 필요가 있습니다. 루프가 그대로 반복 될 것이지만 내가 원하는 것은 다시 연주하고 싶으면 묻는 프롬프트 상자입니다. 사용자가 예라고 대답하면 대답이 추측 될 때까지 루프가 다시 시작됩니다.자바 스크립트 초보자 : 루프를 다시 시작하는 방법

<HTML>  
    <HEAD>  
    </HEAD>  
    <BODY 
     <FORM NAME="testform"> 
      <BR> 
      <BR> 
      <BR> 
     </FORM> 

     <INPUT id="attempts" TYPE="text" NAME="inputbox" VALUE="" /> 
     <INPUT id="zero" TYPE="button" NAME="resetbox" VALUE="Reset " onclick="reset()" /> 

     <SCRIPT type="text/javascript"> 
      varattempts = 0; 
      x = Math.round((Math.random()*19))+1; 
      var tip; 

      tip=prompt("Do you want to play a game?") 

      while(tip.charAt(0).toLowerCase() == "y")  
      {  
       var Guess; 
       document.getElementById('attempts').value = 0; 
       do 
       {  
        Guess = prompt("Pick a number between 1 and 20","") 
        if (Guess === null) break; 
        document.getElementById('attempts').value = parseInt(document.getElementById('attempts').value)+1 
       } while (Guess!=x); 

       if (Guess == x)  
       {    
        alert("You guessed right!")     
       } 
      }    
      function reset()     
      { 
       varattempts=0; 
       document.getElementById('attempts').value = 'Attempts: 0'; 
      } 
     </SCRIPT> 
    </BODY>  
</HTML> 
+3

나는 책에서이 장을 다시 읽을 것입니다. – Loktar

+0

이 숙제가 있습니까? – icktoofay

+0

'varattempts = 0;'은 오타처럼 보입니다. –

답변

4

루프를 다른 루프에 넣습니다. Loopedy loop doe doop.

0

반복 실행 기능을 만드는 것이 가장 쉽습니다. 반복이 끝나면 함수가 반환되고 다시 재생할 것인지 묻습니다. 그렇다면 함수를 다시 호출합니다.

play()라는 이름의 함수에서 다른 모든 코드를 넣어 :

function play() { 
    // all your other code here 
} 

// Then call that function in a loop, return true from play() if the user is done 
// and doesn't wish to be asked if they want to play again 
var done; 
do { 
    done = play(); 
} while (!done || window.confirm("Do you want to play again?")); 
0

당신이 함수의 주요 비트를 넣을 수있는, 다음의 시간을 재설정 할 때, false를 반환하고 프롬프트 상자에 따라 기능을 리콜 . 그저 네가 아무 일도하지 않거나 어쩌면 다른 텍스트를 표시하지 않는다면 그것을 부르는가?

varattempts = 0; 

은 IMO에서 간단하게 뭔가를 쓰는 엉망 방법과 같은 실수처럼 보인다.

관련 문제