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;
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
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
출처 : Object.keys()