Numble 챌린지 다른색깔 찾기 게임

박종화·2022년 2월 12일
0

주요 로직

코드가 길어보이지만 interval timer를 생성하는 부분으로
status state의 time 값을 하나씩 빼주며 로직의 흐름이 시작됩니다

  const [ status, setStatus ] = useState<StatusType>({ stage: 1, grade: 0, time: 15 });
  const interval = useRef<ReturnType<typeof setInterval>>();
  useEffect(() => {
    interval.current = setInterval(() => {
      setStatus((status) => ({ ...status, time : status.time - 1}));
    }, 1000);
    return () => {
      if(interval.current) clearInterval(interval.current);
    };
  }, []);

각 박스마다 아래와 같은 type들을 props로 받게 되며 color 값으로 색상을 표시하고
클릭시 container에서 받은 함수를 실행시키며 자신의 index와 targetIndex를 보내 확인합니다.

interface BoxType {
  targetIndex: Number
  baseColor: String,
  pointColor: String,
}

정답일 경우 : next stage, 점수 반영, timer 초기화
오답일 경우 : 현재 남은 time - 3

정답을 맞춰 점수가 바뀔때마다 색상과 target을 랜덤으로 추출하여 box array값을 갱신합니다.

  useEffect(() => {
    const newBoxes:BoxesType = [];
    const total = Math.pow(Math.round((status.stage + 0.5) / 2) + 1, 2); //박스 개수
    const targetIndex = Math.floor(Math.random() * total); //정답일 index
    const { baseColor, pointColor } = getColorData(status.stage); //랜덤 색상
    for(let i = 0; i < total; i++){
      newBoxes.push({
        targetIndex,
        baseColor,
        pointColor,
      });
    }
    setBoxes(newBoxes);
  }, [status.stage]);

게임의 끝은 state의 time값을 감시하며 값을 비교해 게임 End를 체크합니다.

  useEffect(() => {
    if(status.time <= 0) {
      setStatus({
        stage: 1,
        grade: 0,
        time: 15,
      });
      window.alert(`Game Over! \nGrade : ${status.grade}`);
    }    
  }, [status.time, status.grade]);

고민됬던점

1. 화면에 보이는 박스 배치를 어떤식으로 해야할까

처음 봤을땐 2차원 배열을 만들어 화면에 표시 할까 생각해보았지만
배열 핸들링이 까다로워지고 배열을 만들기위한 2중 for문이 마음에 들지 않았습니다.

결론은 : css display:grid 처리
box를 감싸는 태그를 css display:grid로 감싸고 gridTemplateColumns의 값을 넣어 처리하였습니다.

2. 단계별로 정답과 오답의 차이를 줄여 난이도 올리기

결국 stage가 높아질수록 정답과 오답의 색상 코드 값을 비슷하게 뽑아내는 코드가 필요했습니다
그래서 생각했던게 1차 RGB 각각의 수치값을 조금씩 변경 해보자

색상을 바꿀때 R,G,B중 어느색을 바꿔야 되는지 정확히 몰랐고 랜덤으로 추출된 색에 따라 너무 티나거나 거의 차이없거나, 왔다갔다 하길래 오히려 이전 단계가 더 쉬운 케이스도 나왔습니다.

결론은 : RGBA로 alpha값을 조정하자
단계가 올라갈수록 1(max:1)에 가까워지는 alpha값을 구하여 적용하였더니 비슷한 색이면서 적당히 어려워지는 결과를보았습니다.

profile
너구리개구리다

0개의 댓글