numberbaseball class component

This commit is contained in:
haerong22
2020-12-21 15:24:11 +09:00
parent 4043468a36
commit 9361fcabcb
2 changed files with 64 additions and 28 deletions

View File

@@ -3,7 +3,13 @@ import Try from './Try';
// 숫자 4개를 겹치지않고 랜덤하고 뽑는 함수
function getNumbers() {
const candidate = [1,2,3,4,5,6,7,8,9];
const array = [];
for (let i = 0; i < 4; i++) {
const chosen = candidate.splice(Math.floor(Math.random() * (9 - i)), 1)[0];
array.push(chosen);
}
return array;
}
class NumberBaseball extends Component {
@@ -11,15 +17,57 @@ class NumberBaseball extends Component {
result: '',
value: '',
answer: getNumbers(),
tries: [],
tries: [], // push 쓰면 안됨
};
onSubmitForm = () => {
onSubmitForm = (e) => {
const { value, tries, answer} = this.state;
e.preventDefault();
if(value === answer.join('')) { // 정답
this.setState({
result: '홈런!',
tries: [...tries, { try: value, result: '홈런!'}],
})
alert('게임을 다시 시작합니다.');
this.setState({
value: '',
answer: getNumbers(),
tries: [],
});
} else {
const answerArray = value.split('').map((v) => parseInt(v));
let strike = 0;
let ball = 0;
if(tries.length >= 9) { // 10번이상 틀렸을 때
this.setState( {
result: `실패! 답은 ${answer.join(',')} 였습니다!`,
});
alert('게임을 다시 시작합니다.');
this.setState({
value: '',
answer: getNumbers(),
tries: [],
});
} else {
for (let i = 0; i < 4; i++) {
if(answerArray[i] === answer[i]) {
strike++;
} else if (answer.includes(answerArray[i])) {
ball++;
}
}
this.setState( {
tries: [...tries, {try: value, result: `${strike} 스트라이크, ${ball} 볼 입니다.`}],
value: '',
})
}
}
}
onChangeInput = () => {
onChangeInput = (e) => {
this.setState( {
value: e.target.value,
})
}
input;
@@ -28,31 +76,21 @@ class NumberBaseball extends Component {
}
render() {
const { result, value, tries } = this.state;
return (
<>
<h1>{this.state.result}</h1>
<h1>{result}</h1>
<form onSubmit={this.onSubmitForm}>
<input ref={this.onRefInput} maxLength={4} value={this.state.value} onChange={this.onChangeInput}/>
<input ref={this.onRefInput} maxLength={4} value={value} onChange={this.onChangeInput}/>
<button>입력!</button>
</form>
<div>시도: {this.state.tries.length}</div>
<div>시도: {tries.length}</div>
<ul>
{[
{ fruit: '사과', description: '빨개'},
{ fruit: '바나나', description: '길어'},
{ fruit: '포도', description: '맛있다'},
{ fruit: '귤', description: '시다'},
{ fruit: '수박', description: '달다'},
].map((v, i) => {
{tries.map((v, i) => {
return (
<Try key={v.fruit} value={v} index={i} />
<Try key={`${i + 1}차 시도 :`} tryInfo={v} index={i} />
)
})}
{/* <li><b>사과</b> - 빨개</li>
<li><b>바나나</b> - 길어</li>
<li><b>포도</b> - 맛있다</li>
<li><b>귤</b> - 시다</li>
<li><b>수박</b> - 달다</li> */}
</ul>
</>
)

View File

@@ -2,13 +2,11 @@ import React, { Component } from 'react';
class Try extends Component {
render() {
const { tryInfo } = this.props;
return (
<li>
<b>{this.props.value.fruit}</b> - {this.props.value.description}
<div>컨텐츠</div>
<div>컨텐츠1</div>
<div>컨텐츠2</div>
<div>컨텐츠3</div>
<div>{tryInfo.try}</div>
<div>{tryInfo.result}</div>
</li>
)
}