From 43d1ed7932bcf7e1cdbc9358d8fbc8819c1aee81 Mon Sep 17 00:00:00 2001 From: satr14 Date: Sat, 25 Jul 2026 17:10:41 +0700 Subject: [PATCH] board updating subscriber and listener --- src/lib/chess/types.ts | 3 +++ src/lib/chess/utils.ts | 17 +++++++++++++++-- src/routes/+page.svelte | 18 +++++++++--------- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/lib/chess/types.ts b/src/lib/chess/types.ts index 44e147d..dde6bce 100644 --- a/src/lib/chess/types.ts +++ b/src/lib/chess/types.ts @@ -1,3 +1,6 @@ +import { Game } from "./utils"; +export type GameListener = (board: Game) => void; + export enum Piece { EMPTY = 0, KING = 1, diff --git a/src/lib/chess/utils.ts b/src/lib/chess/utils.ts index 90acea8..e7eb6df 100644 --- a/src/lib/chess/utils.ts +++ b/src/lib/chess/utils.ts @@ -1,8 +1,8 @@ -import { CHAR_TO_PIECE, Piece } from "./types"; +import { CHAR_TO_PIECE, Piece, type GameListener } from "./types"; export const startFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0"; -export class Board { +export class Game { public board = new Int8Array(8 ** 2); public details = { whiteTurn: true, @@ -14,11 +14,22 @@ export class Board { halfMove: 0, fullMove: 0, }; + + private listeners = new Set(); constructor() { this.loadFEN(); } + private notify() { + for (const listener of this.listeners) listener(this); + } + + subscribe(listener: GameListener): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + loadFEN(fen = startFEN) { const [position, turn, castling, enPassant, halfMove, fullMove] = fen.split(" "); @@ -43,6 +54,8 @@ export class Board { this.details.halfMove = parseInt(halfMove); this.details.fullMove = parseInt(fullMove); + + this.notify(); } } diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 3ac01ec..33c31b5 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,20 +1,21 @@
- {#each boardView as square, index} + {#each board as square, index}
@@ -31,10 +32,9 @@ - +
\ No newline at end of file