File size: 8,602 Bytes
466436b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502af73
466436b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502af73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466436b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502af73
 
 
 
 
466436b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15f353f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466436b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import { defineStore } from "pinia";
import { TrigoGameFrontend } from "../utils/TrigoGameFrontend";
import type {
	Stone,
	BoardShape,
	Player,
	Move,
	Position,
	GameConfig,
	TerritoryResult
} from "../../../inc/trigo";

/**
 * Game Store State
 *
 * Refactored to use TrigoGameFrontend as the single source of truth
 */
export interface GameState {
	game: TrigoGameFrontend;
	config: GameConfig;
}

/**
 * Pinia store for game state management
 *
 * Now delegates all game logic to TrigoGameFrontend
 */
export const useGameStore = defineStore("game", {
	state: (): GameState => ({
		game: new TrigoGameFrontend({ x: 5, y: 5, z: 5 }),
		config: {
			boardShape: { x: 5, y: 5, z: 5 },
			allowUndo: true
		}
	}),

	getters: {
		// Board state
		board: (state): Stone[][][] => state.game.getBoard(),
		boardShape: (state): BoardShape => state.game.getShape(),

		// Current player
		currentPlayer: (state): Player => state.game.getCurrentPlayerString(),
		currentPlayerColor: (state): Player => state.game.getCurrentPlayerString(),
		opponentPlayer: (state): Player => state.game.getOpponentPlayer(),

		// Move history
		moveHistory: (state): Move[] => state.game.getMoveHistory(),
		moveCount: (state): number => state.game.getMoveCount(),
		currentMoveIndex: (state): number => state.game.getCurrentMoveIndex(),
		currentMoves: (state): Move[] => {
			const history = state.game.getMoveHistory();
			const currentIndex = state.game.getCurrentMoveIndex();
			return history.slice(0, currentIndex);
		},

		// Game status
		gameStatus: (state) => state.game.getStatus(),
		gameResult: (state) => state.game.getResult(),
		isGameActive: (state): boolean => state.game.isGameActive(),

		// Captured stones
		capturedStones: (state): { black: number; white: number } => {
			const counts = state.game.getCapturedCounts();
			return {
				black: counts.white, // Black captured white stones
				white: counts.black // White captured black stones
			};
		},

		// Pass tracking
		passCount: (state): number => state.game.getConsecutivePassCount(),

		// Undo/Redo capabilities
		canUndo: (state): boolean => {
			return state.config.allowUndo && state.game.canUndo();
		},
		canRedo: (state): boolean => {
			return state.config.allowUndo && state.game.canRedo();
		},

		// Position checks
		isValidPosition:
			(state) =>
			(x: number, y: number, z: number): boolean => {
				return state.game.isValidPosition(x, y, z);
			},
		isEmpty:
			(state) =>
			(x: number, y: number, z: number): boolean => {
				return state.game.isEmpty(x, y, z);
			},
		getStone:
			(state) =>
			(x: number, y: number, z: number): Stone => {
				return state.game.getStoneAt(x, y, z) as Stone;
			}
	},

	actions: {
		/**
		 * Initialize a new game
		 */
		initializeGame(boardShape: BoardShape = { x: 5, y: 5, z: 5 }): void {
			this.game = new TrigoGameFrontend(boardShape);
			this.config.boardShape = boardShape;
			this.saveToSessionStorage();
		},

		/**
		 * Start the game
		 */
		startGame(): void {
			this.game.startGame();
			this.saveToSessionStorage();
		},

		/**
		 * Make a move
		 */
		makeMove(
			x: number,
			y: number,
			z: number
		): { success: boolean; capturedPositions?: Position[] } {
			// Check if game is active
			if (!this.game.isGameActive()) {
				console.warn("Game is not active");
				return { success: false };
			}

			// Attempt to make the move
			const success = this.game.makeMove(x, y, z);

			if (success) {
				// Get captured positions from last step
				const lastStep = this.game.getLastStep();
				const capturedPositions = lastStep?.capturedPositions;

				// Save to storage
				this.saveToSessionStorage();

				return { success: true, capturedPositions };
			}

			return { success: false };
		},

		/**
		 * Pass turn
		 */
		pass(): boolean {
			if (!this.game.isGameActive()) {
				return false;
			}

			const success = this.game.pass();
			if (success) {
				this.saveToSessionStorage();
			}
			return success;
		},

		/**
		 * Resign/surrender
		 */
		resign(): boolean {
			if (!this.game.isGameActive()) {
				return false;
			}

			const success = this.game.surrender();
			if (success) {
				this.saveToSessionStorage();
			}
			return success;
		},

		/**
		 * Undo last move
		 */
		undoMove(): boolean {
			if (!this.canUndo) {
				return false;
			}

			const success = this.game.undoMove();
			if (success) {
				this.saveToSessionStorage();
			}
			return success;
		},

		/**
		 * Redo next move
		 */
		redoMove(): boolean {
			if (!this.canRedo) {
				return false;
			}

			const success = this.game.redoMove();
			if (success) {
				this.saveToSessionStorage();
			}
			return success;
		},

		/**
		 * Jump to specific move in history
		 */
		jumpToMove(index: number): boolean {
			const success = this.game.jumpToMove(index);
			if (success) {
				this.saveToSessionStorage();
			}
			return success;
		},

		/**
		 * Reset game to initial state
		 */
		resetGame(): void {
			this.game.reset();
			this.saveToSessionStorage();
		},

		/**
		 * Change board shape (only when game is idle)
		 */
		setBoardShape(shape: BoardShape): boolean {
			if (this.game.getStatus() !== "idle") {
				console.warn("Cannot change board shape while game is active");
				return false;
			}

			this.initializeGame(shape);
			return true;
		},

		/**
		 * Calculate territory
		 */
		computeTerritory(): TerritoryResult {
			return this.game.computeTerritory();
		},

		/**
		 * Get neighboring positions (6 directions in 3D)
		 */
		getNeighbors(x: number, y: number, z: number): Array<{ x: number; y: number; z: number }> {
			const neighbors = [
				{ x: x + 1, y, z },
				{ x: x - 1, y, z },
				{ x, y: y + 1, z },
				{ x, y: y - 1, z },
				{ x, y, z: z + 1 },
				{ x, y, z: z - 1 }
			];

			return neighbors.filter((pos) => this.isValidPosition(pos.x, pos.y, pos.z));
		},

		/**
		 * Save game state to session storage
		 */
		saveToSessionStorage(): void {
			try {
				this.game.saveToSessionStorage("trigoGameState");
			} catch (error) {
				console.error("Failed to save game state:", error);
			}
		},

		/**
		 * Load game state from session storage
		 */
		loadFromSessionStorage(): boolean {
			try {
				const success = this.game.loadFromSessionStorage("trigoGameState");
				if (success) {
					console.log("Game state restored from session storage");
				}
				return success;
			} catch (error) {
				console.error("Failed to load game state:", error);
				return false;
			}
		},

		/**
		 * Clear saved game state
		 */
		clearSessionStorage(): void {
			try {
				this.game.clearSessionStorage("trigoGameState");
			} catch (error) {
				console.error("Failed to clear session storage:", error);
			}
		},


		/**
		 * Set current player (for multiplayer sync)
		 */
		setCurrentPlayer(player: Player): void {
			// This is handled by the underlying game state
			// The current player is determined by the move history
			// For proper sync, use loadFromTGN instead
			console.log(`[gameStore] setCurrentPlayer called with: ${player}`);
		},


		/**
		 * Load game state from TGN string (for multiplayer sync)
		 */
		loadFromTGN(tgn: string): boolean {
			try {
				// Create a new game from TGN
				const { TrigoGame } = require("../../../inc/trigo/game");
				const newGame = TrigoGame.fromTGN(tgn);

				// Create new frontend game with same shape
				const shape = newGame.getShape();
				this.game = new TrigoGameFrontend(shape);

				// Replay all moves to sync state
				const history = newGame.getStepHistory();
				this.game.startGame();

				for (const step of history) {
					if (step.type === "drop" && step.position) {
						this.game.makeMove(step.position.x, step.position.y, step.position.z);
					} else if (step.type === "pass") {
						this.game.pass();
					}
				}

				this.saveToSessionStorage();
				return true;
			} catch (error) {
				console.error("[gameStore] Failed to load from TGN:", error);
				return false;
			}
		},


		/**
		 * Get all stones on the board (for viewport sync)
		 */
		getAllStones(): Array<{ x: number; y: number; z: number; color: Player }> {
			const stones: Array<{ x: number; y: number; z: number; color: Player }> = [];
			const board = this.game.getBoard();
			const shape = this.game.getShape();

			for (let x = 0; x < shape.x; x++) {
				for (let y = 0; y < shape.y; y++) {
					for (let z = 0; z < shape.z; z++) {
						const stone = board[x][y][z];
						if (stone === 1) {
							stones.push({ x, y, z, color: "black" });
						} else if (stone === 2) {
							stones.push({ x, y, z, color: "white" });
						}
					}
				}
			}

			return stones;
		}
	}
});