React - 가위 바위 보

김가오리·2022년 11월 2일
0

React

목록 보기
7/14

App.jsx

import React, {useState} from 'react'; //상태를 관리함.
import './App.css';
import Box from './components/Box';

function App() {
  const [userSelect, setUserSelect] = useState(null);
  const [computerSelect, setComputerSelect] = useState(null);
  const [result, setResult] = useState("");
  
  const choice = {
    scissors : {
      name : 'Scissors',
      img : 'scissors.png'
    },
    
    rock : {
      name : 'Rock',
      img : 'rock.png'
    },
    
    paper : {
      name : 'Paper',
      img : 'paper.png'
    }
  }
  const play = (userChoice) => {
    setUserSelect(choice[userChoice]);
    let computerChoice = randomChoice();
    setComputerSelect(computerChoice);
    setResult(judgement(choice[userChoice], computerChoice));
  }

  const judgement = (uc, cc) => {
  console.log(' ', uc, cc)
  
    if(uc.name == cc.name){
      return 'TIE';
    }else if(uc.name == "Rock"){
      return cc.name == "Scissors" ? "WIN" : "LOSE";
    }else if(uc.name == "Scissors"){
      return cc.name == "Paper" ? "WIN" : "LOSE";
    }else{
      return cc.name == "Rock" ? "WIN" : "LOSE";
    }
  }
    const randomChoice = () => {
      let itemArray = Object.keys(choice);
      let randomItem = Math.floor(Math.random()*itemArray.length);
      
      let final = itemArray[randomItem];
      
      return choice[final];

    }
  
  return (
    <>
      <div className='main'>
        <Box title = "USER" item={userSelect} result={result}/>
        <Box title = "COMPUTER"item = {computerSelect} result={result}/>
      </div>
      <div className='main'>
        <button onClick = {() => play('scissors')}>SCISSORS</button>
        <button onClick = {() => play('rock')}>ROCK</button>
        <button onClick = {() => play('paper')}>PAPAER</button>
      </div>
      <p className='main resultP'>{result}</p>
    </>
  );
}

export default App;
Box.jsx
import React from 'react'

const Box = (props) => {
    let r_result;
        if(props.title == "COMPUTER" && props.result !== "TIE" && props.result !== "" ){
            r_result = props.result == "WIN" ? "LOSE" : "WIN";
        }else{
            r_result = props.result;
        }
    return (
        <div className={`box ${r_result}`}>
            <h1>{props.title}</h1>
            <img src = {props.item && props.item.img} alt="" className='item-img'/>
            <h2>{r_result}</h2>
        </div>
    )
}

export default Box

Object.keys(obj)

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.keys() : 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환

출처 : Object.keys()

profile
가보자고

0개의 댓글