import React, { useEffect, useState } from 'react'
const Ex15 = () => {
let pos = [ '왼쪽', '정면','오른쪽']
const [myChoice,setMyChoice] = useState('왼쪽')
const [comChoice,setComChoice] = useState('왼쪽')
const [result,setResult]= useState('무승부')
const [randomItem, setRandomItem] = useState(null);
const [round,setRound]=useState(0);
const getRandomItem = () => {
const randomIndex = Math.floor(Math.random() * 3);
return randomIndex
};
const btnCk = (e) =>{
setRound(round+1);
console.log("button click", e.target.innerText);
setMyChoice(e.target.innerText);
setComChoice(pos[getRandomItem()])
}
useEffect(()=>{
console.log('round겂 변경');
if(round>0){
comChoice === myChoice
? setResult('승리')
: setResult('실패')
}
},[round])
return (
<div>
<h1>참참참 게임</h1>
<p>나의 공격: {myChoice}</p>
<p>상대방 수비: {comChoice}</p>
<p>결과: {result}</p>
<hr></hr>
{pos.map(item =><button onClick={btnCk} key = {item}>{item}</button>)}
</div>
)
}
export default Ex15