메인코드
시간제한 15초를 세야하기 때문에 setInterval로 초 세면서 조건마다 dispatch해준다
useEffect(() => {
const countdown = setInterval(() => {
if (time > 0) {
dispatch({ type: "TIMEPASS" });
} else {
alert("GAME OVER!\n 스테이지:" + stage + ", 점수:" + score);
dispatch({ type: "RESET" });
}
}, 1000);
return () => clearInterval(countdown);
}, [time, stage, score]);
useEffect로 stage랑 card갯수 바뀔때마다 박스들 다시 불러온다
useEffect(() => {
setBoxwidth(360 / Math.sqrt(cards) - 4);
setAns(Math.floor(Math.random() * cards));
}, [stage, cards]);
박스 onClick시 BoxClicked로 눌린게 답인지 아닌지 확인한다
상황에 따라 dispatch
const boxClicked = (index: number, ans: number) => {
index === ans
? dispatch({ type: "CORRECT" })
: dispatch({ type: "WRONGANSWER" });
};
박스들을 보여주는 코드이다
props를 Box컴포넌트로 넘겨준다
<div className="main-box">
{[...Array(cards)].map((n, index) => {
return (
<Box
colordiff={colordiff}
colors={color}
width={boxWidth}
diffrentBox={ans}
currentBox={index}
onClick={() => boxClicked(index, ans)}
></Box>
);
})}
</div>
남은시간, 점수, 스테이지, 카드갯수, 색상과 색상차이(colordiff) 관리
action은 네가지이다
type Action =
| { type: "TIMEPASS" } // 시간이 흐르거나
| { type: "WRONGANSWER" } //오답이거나
| { type: "RESET" } //새로고침해야하거나
| { type: "CORRECT" }; //맞았거나
카드의 갯수도 여기서 정해준다
const setCards = (state: number) => {
return Math.pow(Math.round((state + 1 + 0.5) / 2) + 1, 2);
};
박스 컴포넌트
박스 색상이랑 넓이를 styled component로 설정해준다
색상은 채도만 조절 가능한 hsl로 설정
stage가 올라갈수록 정답과 오답의 색상 차이가 비슷해져야 하기 때문에
reducer에서 받아오는 colordiff값이 stage가 올라감에 따라 증가하도록 했다
정답 박스와 오답박스의 채도가 점점 비슷해진다.
background: ${(props) =>
props.currentBox === props.diffrentBox
? "hsl(" + props.colors.toString() + ", 100%, 70%)"
: "hsl(" +
props.colors.toString() +
", 100%, " +
props.colordiff.toString() +
"%)"};
styled component
Box컴포넌트에서 색상과 넓이를 props로 받아와서 변경해주기 좋을것 같아서 사용하였다.