Skip to content

Commit a95cf20

Browse files
committed
compute optimistic states
1 parent 1818530 commit a95cf20

2 files changed

Lines changed: 84 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import type { Fetcher } from "react-router";
2+
import { sortTehai } from "~/lib/hai/types";
3+
import type { GameState } from "~/lib/types";
4+
import { TOTAL_TSUMO_PER_KYOKU } from "./constants";
5+
6+
export function computeOptimisticGameState(
7+
loaderData: GameState,
8+
discardFetcher: Fetcher<GameState>,
9+
) {
10+
const fetcherGameState =
11+
discardFetcher.data && "tehai" in discardFetcher.data
12+
? discardFetcher.data
13+
: null;
14+
15+
const currentGameState =
16+
fetcherGameState?.kyoku === loaderData.kyoku
17+
? fetcherGameState
18+
: loaderData;
19+
20+
const {
21+
sutehai,
22+
tsumohai,
23+
nextTsumohai,
24+
junme,
25+
kyoku,
26+
tehai,
27+
remainTsumo,
28+
score,
29+
} = currentGameState;
30+
31+
const baseSortedTehai = sortTehai(tehai);
32+
33+
let optimisticSutehai = sutehai;
34+
let optimisticTehai = baseSortedTehai;
35+
let optimisticTsumohai = tsumohai;
36+
let optimisticJunme = junme;
37+
let optimisticRemainTsumo = remainTsumo;
38+
39+
if (
40+
discardFetcher.state !== "idle" &&
41+
discardFetcher.formData &&
42+
tsumohai !== null
43+
) {
44+
const nextRemainTsumo = Math.max(0, remainTsumo - 1);
45+
46+
if (discardFetcher.formAction?.endsWith("/api/tedashi")) {
47+
const index = Number(discardFetcher.formData.get("index"));
48+
if (
49+
Number.isInteger(index) &&
50+
index >= 0 &&
51+
index < baseSortedTehai.length
52+
) {
53+
const discardHai = baseSortedTehai[index];
54+
const remainingTehai = baseSortedTehai.filter((_, i) => i !== index);
55+
optimisticSutehai = [...sutehai, discardHai];
56+
optimisticTehai = sortTehai([...remainingTehai, tsumohai]);
57+
optimisticTsumohai = nextTsumohai;
58+
optimisticJunme = junme + 1;
59+
optimisticRemainTsumo = nextRemainTsumo;
60+
}
61+
} else if (discardFetcher.formAction?.endsWith("/api/tsumogii")) {
62+
optimisticSutehai = [...sutehai, tsumohai];
63+
optimisticTsumohai = nextTsumohai;
64+
optimisticJunme = junme + 1;
65+
optimisticRemainTsumo = nextRemainTsumo;
66+
}
67+
}
68+
const tsumoProgressValue = Math.max(
69+
0,
70+
TOTAL_TSUMO_PER_KYOKU - optimisticRemainTsumo,
71+
);
72+
return {
73+
currentGameState,
74+
kyoku,
75+
score,
76+
optimisticTehai,
77+
optimisticTsumohai,
78+
optimisticSutehai,
79+
optimisticJunme,
80+
optimisticRemainTsumo,
81+
tsumoProgressValue,
82+
};
83+
}

app/routes/play/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const TOTAL_TSUMO_PER_KYOKU = 18;

0 commit comments

Comments
 (0)