Skip to content

Commit 9b21a08

Browse files
committed
define global state
1 parent 87101e1 commit 9b21a08

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

rr/app/lib/store.ts

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,65 @@
11
import { create } from "zustand";
2-
import { persist } from "zustand/middleware";
32
import type { Hai } from "./hai";
3+
import { sortTehai } from "./hai";
44

55
interface GameState {
66
kyoku: number;
77
junme: number;
88
haiyama: Hai[];
99
sutehai: Hai[];
10+
// Hai * 13
1011
tehai: Hai[];
12+
// null as an initial value
13+
tsumohai: Hai | null;
1114
}
1215

13-
const useGameState = create<GameState>()((set) => ({
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) => ({
1423
kyoku: 1,
1524
junme: 1,
1625
haiyama: [],
1726
sutehai: [],
1827
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+
},
1965
}));

0 commit comments

Comments
 (0)