UNPKG

2.48 kBJavaScriptView Raw
1import * as gameActions from "@cardcore/game";
2import * as clientActions from "@cardcore/client";
3import queueReducer from "./queue-reducer";
4import { rando } from "@cardcore/util";
5
6// automatically find any reducer functions in the actions file and call them
7const gameReducers = Object.keys(gameActions)
8 .filter(key => key.endsWith("Reducer"))
9 .map(key => gameActions[key]);
10
11const secret = function(state = {}, action) {
12 if (action.type === clientActions.CLIENT_GENERATE_KEY) {
13 return {
14 ...state,
15 [action.keys.id]: action.keys
16 };
17 }
18
19 if (action.type === clientActions.CLIENT_BOX) {
20 return {
21 ...state,
22 [action.id]: {
23 ...state[action.id],
24 contents: action.contents
25 }
26 };
27 }
28
29 return state;
30};
31
32const DEFAULT_STATE = { game: {} };
33
34export default function rootReducer(state = DEFAULT_STATE, action) {
35 let startRandoSeed = state.game && state.game.randoSeed;
36 if (state.game && state.game.randoSeed) {
37 rando.setSeed(startRandoSeed);
38 }
39 const reducers = { client: clientActions.clientReducer, secret };
40 // temporary hacky game init logic
41 if (action.type === clientActions.CLIENT_LOAD_STATE_START) {
42 state = {
43 ...state,
44 game: action.gameState
45 };
46 }
47 // special logic to clean out the queue if we're executing a queued action
48 if (
49 state &&
50 state.game &&
51 state.game.nextActions &&
52 state.game.nextActions[0] &&
53 (action._sender === state.game.nextActions[0].playerId ||
54 action._sender !== state.game.nextActions[0].notPlayerId) && // omfg hack
55 action.type === state.game.nextActions[0].action.type
56 ) {
57 state = {
58 ...state,
59 game: {
60 ...state.game,
61 nextActions: state.game.nextActions.slice(1)
62 }
63 };
64 }
65
66 for (const [name, reducer] of Object.entries(reducers)) {
67 const newState = reducer(state[name], action);
68 if (state[name] !== newState) {
69 state = {
70 ...state,
71 [name]: newState
72 };
73 }
74 }
75 for (const reducer of gameReducers) {
76 state = reducer(state, action);
77 if (!state) {
78 throw new Error(`${reducer.name} returned undefined`);
79 }
80 }
81
82 if (state.game && rando.seed && state.game.randoSeed !== rando.seed) {
83 state = {
84 ...state,
85 game: {
86 ...state.game,
87 randoSeed: rando.seed
88 }
89 };
90 }
91 if (gameActions[action.type]) {
92 state = queueReducer(state, action);
93 }
94 rando.clearSeed();
95 return state;
96}