느려도 한걸음씩

Pokemon Card Flip - 12. 점수기능 제작 본문

토이프로젝트/Pokemon Card Flip

Pokemon Card Flip - 12. 점수기능 제작

hoj0806 2025. 3. 30. 21:45

우선 난이도 선택 컴포넌트에서 버튼 클릭이 선택한 난이도를 string 타입으로 리덕스에 저장한다

 

const initialState: ModeType = { mode: "main", 
// 선택 난이도 데이터
difficulty: "easy" };

 

const modeSlice = createSlice({
  name: "modeSlice",
  initialState,
  reducers: {
    // 난이도 선택 리듀서
    setDifficulty: (
      state,
      action: PayloadAction<"easy" | "normal" | "hard">
    ) => {
      state.difficulty = action.payload;
    },
  },
});



난이도 선택 컴포넌트에서 리듀서를 통해 easy, normal,hard를 리덕스에 저장한다

 

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../store";
import { ScoreType } from "../types/types";

const initialState: ScoreType = {
  score: 0,
  combo: 0,
  highScore: {
    easy: 0,
    normal: 0,
    hard: 0,
  },
};

const scoreSlice = createSlice({
  name: "scoreSlice",
  initialState,
  reducers: {
    increaseByCombo: (state, action: PayloadAction<number>) => {
      state.score += action.payload + 1;
    },
    resetScore: (state) => {
      state.score = 0;
    },
    increaseCombo: (state) => {
      state.combo += 1;
    },
    resetCombo: (state) => {
      state.combo = 0;
    },
    updateHighScore: {
      prepare(difficulty, score) {
        return {
          payload: {
            difficulty,
            score,
          },
        };
      },
      reducer(
        state,
        action: PayloadAction<{
          difficulty: "easy" | "normal" | "hard";
          score: number;
        }>
      ) {
        const { difficulty, score } = action.payload;
        state.highScore[difficulty] = score;
      },
    },
  },
});

export default scoreSlice;
export const {
  increaseByCombo,
  resetScore,
  increaseCombo,
  resetCombo,
  updateHighScore,
} = scoreSlice.actions;
export const currentScore = (state: RootState) => state.scoreSlice.score;
export const combo = (state: RootState) => state.scoreSlice.combo;
export const highScore = (state: RootState) => state.scoreSlice.highScore;


스코어 기능을 제작하기 위해 scoreSlice를 만든다 현재 점수를 표시하는 score , 하이스코를 표시하는 highScore, 현재 콤보를 나타내는 combo 데이터가있다

increaseByCombo를 통해 카드를 맞출시 (현재 콤보 + 1 점)을 점현재 수에 더해주고 콤보를 1점 더해준다

만약 카드를 맞추지 못했을시에는 resetCombo를 통해 콤보를 초기화 해준다

updateHighScore를 통해 현재 선택한 난이도의 최고점수를 설정한다 (easy, normal ,high 난이별로 따로 하이스코어 저장)