단어게임 수정 1(중복 제거된 답안 적용)

개발공부·2023년 1월 3일
0

* 결과(이전 글)

* 문제점

  • 체크박스에서 고른 단어들 중 답 이외의 3개의 답이 필요함
  • 문제는 그 과정에서 계속 답안에서 중복 발생

// 원하던 결과
result = [ //이런 형식으로 10개
{question: "생일", answer: 4, choices: [
"chill", "coffee", "javascript", "brithday"
]},
{question: "post", answer: 2, choices: [
"money", "post", "game", "smile"
]},
{question: "좋아요", answer: 3, choices: [
"luck", "javascript", "good", "smile"
]}
]

// 계속 출력되는 값
result = [ //이런 형식으로 10개
{question: "생일", answer: 4, choices: [
"brithday", "coffee", "javascript", "brithday" //중복된 값이 나옴
]},
{question: "post", answer: 2, choices: [
"money", "post", "game", "smile"
]},
{question: "좋아요", answer: 3, choices: [
"good", "javascript", "good", "smile" //중복된 값이 나옴
]}
]

- Set 함수 이용하기

▶ choices만 따로 new Set을 진행할 것
set 함수 : 자료형에 관계 없이 원시 값과 객체 참조 모두 유일한 값 저장 가능
Set 함수에 대한 다른 예시(stackoverflow)

var yourSetAsArray = Array.from(new Set([1, 2, 2, 3, 3, 4, 4]));
// returns [1, 2, 3, 4]

* 코드

[components/game/StartModal.js]

import {
  loadWordsRequest,
  loadCheckedRequest,
  changeStatusWordAllRequest,
} from "../../redux/feature/wordSlice";
import { startGameRequest } from "../../redux/feature/gameSlice";

const StartModal = () => {
 const { wordLists, checkedWordList } = useSelector((state) => state.word);
  const checkedData = [...checkedWordList];
  const allData = [...wordLists];
  const answer = [1, 2, 3, 4];
  const result = [];
 
 const onStartGame = useCallback(() => {
    if (checkedWordList.length < 10) {
      setAlert(true);
      setGameStart(false);
      setOpen(true);
    } else {
      const shuffleArray = (array) => {
        for (let i = array.length - 1; i > 0; i--) {
          // 무작위로 index 값 생성 (0 이상 i 미만)
          let j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
        }
      };
      shuffleArray(allData);
      shuffleArray(checkedData);
      checkedData.splice(10, checkedData.length); //10개만 남기기

      checkedData.map((data, i) => {
        shuffleArray(answer);
        if (answer[0] === 1 && i < 10) {
          result.push({
            question: data.korean,
            answer: 1,
            choices: Array.from( //new Set 적용
              new Set([
                data.english,
                allData[i].english,
                i < allData.length - 2 && allData[i + 1].english,
                i < allData.length - 2 && allData[i + 2].english,
              ])
            ),
          });
        } else if (answer[0] === 2 && i < 10) {
          result.push({
            question: data.korean,
            answer: 2,
            choices: Array.from(
              new Set([
                allData[i].english,
                data.english,
                i < allData.length - 2 && allData[i + 1].english,
                i < allData.length - 2 && allData[i + 2].english,
              ])
            ),
          });
        } else if (answer[0] === 3 && i < 10) {
          result.push({
            question: data.korean,
            answer: 3,
            choices: Array.from(
              new Set([
                allData[i].english,
                i < allData.length - 2 && allData[i + 1].english,
                data.english,
                i < allData.length - 2 && allData[i + 2].english,
              ])
            ),
          });
        } else if (answer[0] === 4 && i < 10) {
          result.push({
            question: data.korean,
            answer: 4,
            choices: Array.from(
              new Set([
                allData[i].english,
                i < allData.length - 2 && allData[i + 1].english,
                i < allData.length - 2 && allData[i + 2].english,
                data.english,
              ])
            ),
          });
        }
      });
      dispatch(startGameRequest(result));
      setGameStart(true);
      setOpen(false);
    }
  }, [result]);
  
  return (
  
     <button type="button"
     className="inline-flex w-full justify-center rounded-md border border-transparent bg-light-orange px-4 py-2 text-base font-medium text-black shadow-sm hover:bg-dark-green hover:text-white  sm:ml-3 sm:w-auto sm:text-sm"
                      onClick={onStartGame}
                    >
                      시작!
                    </button>
  
  )
}

 

[sagas/ganeSaga.js]

function* startGame(action) {
  try {
    const data = action.payload;
    yield put(startGameSuccess(data));
  } catch (error) {
    yield put(startGameError(error));
    console.log(error);
  }
}

[gameSlice.js] - redux-toolkit

  startGameSuccess: (state, action) => {
      const data = action.payload;
      state.startGameLoading = false;
      state.startGameComplete = true;
      state.gameWordLists = state.gameWordLists.concat(data);
    },
profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글