[2022.08.06] 리액트로 가위바위보 게임 만들기 (클래스 컴포넌트)

REASON·2022년 8월 6일
0

복습

목록 보기
9/12

제로초님 영상보고 따라 만든 가위바위보 게임

처음엔 영상보고 그대로 따라 만들고 두번째는 복습겸 배운 내용대로 만들려고 했는데 생각보다 어려웠다.ㅠㅠ

결국 혼자 해결 못해서 제로초님 강의 보고 따라 만든 코드 참고해서 버그 픽스하고 하다보니 혼자 짠 코드는 50%정도 되지 않을까......... 또르륵

훅스로 바꾸기 전에 다시 처음부터 혼자 만들어봐야겠다.
일단 결과물은 다음과 같다.

전체 코드

import React, { Component } from 'react';

const imgCoordinates = {
  rock: '0',
  paper: '-284px',
  scissors: '-142px',
};

const rspScore = {
  rock: 0,
  paper: 1,
  scissors: -1,
};

class BokseupRSP extends Component {
  state = {
    score: 0,
    result: '',
    imgLocation: '0',
  };

  interval;

  componentDidMount() {
    this.interval = setInterval(this.startGame, 100);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  startGame = () => {
    const { imgLocation } = this.state;
    if (imgLocation === imgCoordinates.rock) {
      this.setState({
        imgLocation: imgCoordinates.scissors,
      });
    } else if (imgLocation === imgCoordinates.scissors) {
      this.setState({
        imgLocation: imgCoordinates.paper,
      });
    } else if (imgLocation === imgCoordinates.paper) {
      this.setState({
        imgLocation: imgCoordinates.rock,
      });
    }
  };

  computerPick = (location) => {
    return Object.entries(imgCoordinates).find((v) => {
      return v[1] === location;
    })[0];
  };

  rspChoice = (userPick) => () => {
    clearInterval(this.interval);
    // 바위 0 가위 -1 보 1
    const { imgLocation } = this.state;
    const userScore = rspScore[userPick];
    const computerScore = rspScore[this.computerPick(imgLocation)];
    const diff = userScore - computerScore;

    console.log(diff);
    if (diff === 0) {
      this.setState({
        result: '무승부',
      });
    } else if (diff === -2 || diff === 1) {
      this.setState((prev) => {
        return {
          result: '승!',
          score: prev.score + 1,
        };
      });
    } else {
      this.setState((prev) => {
        return {
          result: '패ㅠㅠ!',
          score: prev.score - 1,
        };
      });
    }

    setTimeout(() => {
      clearInterval(this.interval);
      this.interval = setInterval(this.startGame, 100);
    }, 2000);
  };

  render() {
    const { result, imgLocation, score } = this.state;

    return (
      <>
        <div>
          <div id="computer" style={{ background: `url(https://en.pimg.jp/023/182/267/1/23182267.jpg) ${imgLocation} 0` }}></div>
          <button onClick={this.rspChoice('rock')}>바위</button>
          <button onClick={this.rspChoice('scissors')}>가위</button>
          <button onClick={this.rspChoice('paper')}></button>
          <p>{result}</p>
          <p>점수 : {score}</p>
        </div>
      </>
    );
  }
}

export default BokseupRSP;

하면서 제일 어려웠던 부분은 내가 선택한 가위/바위/보하고 컴퓨터의 가위/바위/보를 비교하는 부분이었다.


참고 자료
React 기본 강좌 5-3. 가위바위보 게임 만들기

0개의 댓글