|
| 1 | +import { create } from "zustand"; |
| 2 | +import type { Hai } from "./hai"; |
| 3 | +import { sortTehai } from "./hai"; |
| 4 | + |
| 5 | +interface GameState { |
| 6 | + kyoku: number; |
| 7 | + junme: number; |
| 8 | + haiyama: Hai[]; |
| 9 | + sutehai: Hai[]; |
| 10 | + // Hai * 13 |
| 11 | + tehai: Hai[]; |
| 12 | + // null as an initial value |
| 13 | + tsumohai: Hai | null; |
| 14 | +} |
| 15 | + |
| 16 | +interface PlayerAction { |
| 17 | + // tsumo just after tedashi or tsumogiri |
| 18 | + tedashi: (index: number) => void; |
| 19 | + tsumogiri: () => void; |
| 20 | +} |
| 21 | + |
| 22 | +const useGameStore = create<GameState & PlayerAction>()((set, get) => ({ |
| 23 | + kyoku: 1, |
| 24 | + junme: 1, |
| 25 | + haiyama: [], |
| 26 | + sutehai: [], |
| 27 | + tehai: [], |
| 28 | + tsumohai: null, |
| 29 | + |
| 30 | + tedashi: (index) => { |
| 31 | + const state = get(); |
| 32 | + if (!state.tsumohai) { |
| 33 | + throw new Error("syohai"); |
| 34 | + } |
| 35 | + const tsumohai = state.tsumohai; |
| 36 | + |
| 37 | + if (index < 0 || 12 < index) { |
| 38 | + throw new Error("index out of tehai length"); |
| 39 | + } |
| 40 | + const deletedTehai = state.tehai.filter((_, i) => i !== index); |
| 41 | + const discardedHai = state.tehai[index]; |
| 42 | + set(() => ({ |
| 43 | + kyoku: state.kyoku + 1, |
| 44 | + junme: state.junme + 1, |
| 45 | + haiyama: state.haiyama.slice(1), |
| 46 | + sutehai: [...state.sutehai, discardedHai], |
| 47 | + tehai: sortTehai([...deletedTehai, tsumohai]), |
| 48 | + tsumohai: state.haiyama[0], |
| 49 | + })); |
| 50 | + }, |
| 51 | + tsumogiri: () => { |
| 52 | + const state = get(); |
| 53 | + if (!state.tsumohai) { |
| 54 | + throw new Error("syohai"); |
| 55 | + } |
| 56 | + const tsumohai = state.tsumohai; |
| 57 | + set(() => ({ |
| 58 | + kyoku: state.kyoku + 1, |
| 59 | + junme: state.junme + 1, |
| 60 | + haiyama: state.haiyama.slice(1), |
| 61 | + sutehai: [...state.sutehai, tsumohai], |
| 62 | + tsumohai: state.haiyama[0], |
| 63 | + })); |
| 64 | + }, |
| 65 | +})); |
0 commit comments