0

다음은 필자가 여러 가지 힌트와 4 회전 후에 종료하는 카운터 기능으로 추측 게임을해야한다는 교육용 운동에 대한 나의 코드이다. 나는 그처럼 광범위하게 수색했고 도움을 찾지 못했습니다. 나는 교과서를 검토하지 않았다. 이 코드는 내가 현재 가지고있는 지식으로 할 수있는 한 최선입니다 (수업은 1 주일 동안 진행되었으므로 너무나도 익숙하지 않습니다). 어떤 도움이라도 대단히 감사하겠습니다!카운터 기능으로 Javascript에서 연령 추측 게임 만들기를 시도합니다. 지금까지는 작동하지 않았다

if (answerSix != myAge) { 
      while (guesses <= 4) { 
       if (answerSix > myAge) 
        {alert('Too old!')}; 
        guesses++; 
       else if (answerSix < myAge) 
        {alert('Too young!')}; 
        guesses++; 
       } 
       else if (guesses >= 4) { 
        {alert('You have guessed too many times! Game over!')}; 
        {break}; 
       } 
       } 
      } 
     else if (answerSix === myAge) { 
       {alert('Got it like the \'79 SuperSonics!')}; 
       {break} 
      } 
      else {alert('Answer is invalid!')} 
+0

이것은 클래스에 대한 것이므로 나는 대답을 찾고 있지는 않지만 다시 시도해 보라고 제안 할 것이다. 선생님에게 잘못된 대답을하면 더 많은 것을 배울 수 있습니다. –

+0

hhhh. @CarlMarkham이 맞습니다 –

+0

변수는 모두 어디에 정의되어 있습니까? 값은 어디에서 오며 함수는 어떻게 호출됩니까? 어떤 오류가 발생합니까? – j08691

답변

0

선생님이 답을주고, 우리는 그가 당신을 :) 평가하는 방법을 알려

const MAX_GUESSES= 4; 
 
class Game extends React.Component{ 
 
    
 
    state = {started: false, end: false, guesses: 0}; 
 
    
 
    onStart(event) { 
 
    event.preventDefault(); 
 
    if (!this.refs.myAge.value.length) 
 
     alert('Give a valid age before starting'); 
 
    else { 
 
     this.setState({started: true, end: false, age: Number(this.refs.myAge.value) }); 
 
    } 
 
    } 
 

 
    onGuess(event) { 
 
    event.preventDefault(); 
 
    const guessed= Number(this.refs.answer.value); 
 
    if (this.state.guesses >= MAX_GUESSES) { 
 
     this.setState({end: true, message: 'Failed! you reach max attempts'}); 
 
     return ; 
 
    } 
 
    if (!guessed) 
 
     alert('Please, put valid answer!') 
 
    else { 
 
     if(guessed < this.state.age) { 
 
      alert('too young!'); 
 
      this.setState({guesses: this.state.guesses+1}) 
 
     } 
 

 
     else if(guessed > this.state.age) { 
 
     alert('too old!'); 
 
     this.setState({guesses: this.state.guesses+1})  
 
     } 
 

 
     else { 
 
     this.setState({ 
 
      end: true, message: `You win in ${this.state.guesses+1} attempt(s)` 
 
     }); 
 
     return; 
 
     } 
 
      
 
    } 
 
    } 
 

 
    renderBeforeStart() { 
 
    if (this.state.started || this.state.end) return null; 
 
    return (
 
     <div> 
 
     <input ref="myAge" type="number" placeholder="give your age before starting" /> years old <br /> 
 
     <button onClick={this.onStart.bind(this)}>Start Game </button> 
 
     </div> 
 
    ) 
 
    } 
 
    
 
    renderAfterStart() { 
 
    if (!this.state.started || this.state.end) return null; 
 
    
 
    return(
 
     <div> 
 
      <input ref="answer" type="number" placeholder="guess the age"/> <br /> 
 
      <button onClick={this.onGuess.bind(this)}> Guess ></button> 
 
      
 
     </div> 
 
    ) 
 
    } 
 
    
 
    renderEnd() { 
 
    if (!this.state.end) return ; 
 
    
 
    return (<p>{this.state.message}</p>) 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
      {this.renderBeforeStart()} 
 
      {this.renderAfterStart()} 
 
      {this.renderEnd()} 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(<Game />, document.querySelector('section'))
div div input { 
 
    font-size:20px; 
 
    padding-left:10px; 
 
    padding-right:10px; 
 
} 
 

 
div div button { 
 
font-size : 22px; 
 
margin-top:10px; 
 
margin-left:10px; 
 
cursor: progress; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<section />

+1

권. 그는 100 % 잡힐 것입니다. – Lex

+0

나는 이것을 downvote할지 여부를 모르겠다. P –

+0

초보자 일지라도, 나는이 대답이 너무 많은 라인을 필요로한다는 것을 알 수 있었다. 나는 다음 동료만큼 좋은 농담을 고맙게 생각하지만, 진심 어린 도움을 주시면 감사하겠습니다! 어쨌든 그룹 근무일에 해결책을 찾을 수있었습니다. –

-1

이 이그제큐티브 소프트웨어의 디스 키퍼 다운 문법과 논리입니다,하지만 난에 원 이해할 수있게하십시오.

//correct age 
var age = 6; 
//number of times guessed 
var counter = 0; 
//maximum guesses 
var maxCount = 4; 

//function that takes a guess as a parameter 
function guess(guess){ 
    /*if counter, (number of times guessed), 
    is equal to or greater than maxCount, (maximum guesses), 
    alert: 'You have guessed too many times! Game over!'*/ 
    if(counter >= maxCount){ 
     alert('You have guessed too many times! Game over!'); 
    /*else (the number of times guessed is less than maximum guesses))*/ 
    } else { 
     /*if the type of the parameter 'guess' is not a number, 
     alert: 'Answer is invalid!'*/ 
     if(typeof guess !== 'number'){ 
      alert('Answer is invalid!'); 
     /*else (the type of parameter 'guess' is a number)*/ 
     } else { 
      /*if the guess parameter doesn't equal the correct age*/ 
      if(guess !== age){ 
       /*if the guess is less than the correct age, 
       alert: 'Too young!'*/ 
       if(guess < age){ 
        alert('Too young!'); 
       /*else, (the guess must be greater than the correct age), 
       alert: 'Too young!'*/ 
       } else { 
        alert('Too old!'); 
       } 
      /*else, (the guess parameter must equal the correct age), 
      alert: 'Got it like the \'79 SuperSonics!'*/ 
      } else { 
       alert('Got it like the \'79 SuperSonics!'); 
      } 
     } 
     /*increment the count of valid guesses by 1*/ 
     counter++; 
    } 
} 

guess(4) 
//Alerts: 'Too young!' 
guess(8) 
//Alerts: 'Too old!' 
guess(6) 
//Alerts: 'Got it like the \'79 SuperSonics!' 
guess('hi') 
//Alerts: 'Answer is invalid!' 

//if guess count > 4 
//Alerts: 'You have guessed too many times! Game over!' 
+0

Downvote는 코드를 제공했기 때문에 작동 방식을 설명하지 않았기 때문에 수행했습니다. –

+0

그는 이미 부울, 비교 연산자 및 if else 문을 알고 있습니다. '유형'이 무엇을 설명하는지 OP의 지능에 모욕 일 것입니다. 어떤 것들은 설명의 가치가 있지만, 다른 것들은 그렇지 않습니다. 예를 들어 프로그래밍 수업의 첫 번째 수업에서 배운 것들을들 수 있습니다. (자명하다.) – Lex

+0

나는 프로그래밍 수업을 듣지 않았으므로 그 문제에 대한 나의 무지를 변명한다. 그럼에도 OP가 자신이 작성한 것을 알고 있다고 생각할 수는 없습니다. OP 코멘트 "무엇을 의미합니까?"보다 코드의 각 라인을 주석 처리하는 것이 더 좋습니다. –

0

도움을 주신 모든 분들께 감사드립니다. 나는 결국 내가 후손을 위해 공유하고 싶은 해결책을 찾을 수 있었다 :

var myAge = 29; 
     var counterSix = 0; 
     while (counterSix < 4) { 
      counterSix++; 
      var answerSix = parseInt(prompt('What\s my age?')); 
      if (counterSix === 4) { 
       alert('Let\'s move on'); 
      } else if (answerSix === myAge) { 
       alert('Got it like the \'79 SuperSonics!'); 
       break; 
      } else if (answerSix < myAge) { 
       alert ('Too young!') 
      } else if (answerSix > myAge) { 
       alert('Too old!'); questionCounter++ 
      } 
     }