유튜브 강의
제로초 리액트 강의 5.2 가위바위보 만들기
2021bong
2021. 11. 16. 16:38
// class
import React, { Component } from 'react';
const rspCoords = {
바위: '0',
가위: '-142px',
보: '-284px',
}
const scores = {
바위: 0,
가위: 1,
보: -1,
}
const computerChoice = (imgCoord) => {
return Object.entries(rspCoords).find(function (v) {
return v[1] === imgCoord;
})[0];
};
class RSP extends Component {
state = {
result: '',
imgCoord: '0',
score: 0,
}
interval;
componentDidMount() { // 컴포넌트가 첫 렌더링 후
this.interval = setInterval(this.changeHand, 100);
}
componentWillUnmount() {
clearInterval(this.interval);
}
changeHand = () => {
const { imgCoord } = this.state;
if (imgCoord === rspCoords.바위) {
this.setState(
{ imgCoord: rspCoords.가위, }
);
} else if (imgCoord === rspCoords.가위) {
this.setState(
{ imgCoord: rspCoords.보, }
);
} else if (imgCoord === rspCoords.보) {
this.setState(
{ imgCoord: rspCoords.바위, }
);
}
}
onClickBtn = (choice) => {
const { imgCoord } = this.state;
clearInterval(this.interval);
const myScore = scores[choice];
const comScore = scores[computerChoice(imgCoord)];
const diff = myScore - comScore;
if (diff === 0) {
this.setState({
result: '비겼습니다.',
});
} else if ([-1, 2].includes(diff)) {
this.setState((prevState) => {
return ({
result: '이겼습니다.',
score: prevState.score + 1,
});
});
} else {
this.setState((prevState) => {
return ({
result: '졌습니다.',
score: prevState.score - 1,
});
});
}
setTimeout(() => {
this.interval = setInterval(this.changeHand, 100);
}, 2000);
}
render() {
const { result, score, imgCoord } = this.state;
return (
<>
<div id="computer" style={{ background: `url(https://en.pimg.jp/023/182/267/1/23182267.jpg) ${imgCoord} 0` }}></div>
<div>
<button id="rock" className="btn" onClick={() => { this.onClickBtn('바위') }}>바위</button>
<button id="scissor" className="btn" onClick={() => { this.onClickBtn('가위') }}>가위</button>
<button id="paper" className="btn" onClick={() => { this.onClickBtn('보') }}>보</button>
</div>
<div>{result}</div>
<div>현재 {score}점</div>
</>
);
}
}
export default RSP;
state와 연관이 없는 값을 밖에다가 빼둬도 됨
class로 너무 많은 것을 묶으려하지 말 것
+
나는 실행이 안되서 this.state.imgCoord를 문자열로 했음...
728x90