board updating subscriber and listener

This commit is contained in:
Satria 2026-07-25 17:10:41 +07:00
commit 43d1ed7932
3 changed files with 27 additions and 11 deletions

View file

@ -1,3 +1,6 @@
import { Game } from "./utils";
export type GameListener = (board: Game) => void;
export enum Piece {
EMPTY = 0,
KING = 1,

View file

@ -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,
@ -15,10 +15,21 @@ export class Board {
fullMove: 0,
};
private listeners = new Set<GameListener>();
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();
}
}

View file

@ -1,20 +1,21 @@
<script lang="ts">
import { PIECE_TO_CHAR } from "$lib/chess/types";
import { Board, startFEN } from "$lib/chess/utils";
import { Game, startFEN } from "$lib/chess/utils";
const board = new Board();
let boardView = $state(Array.from(board.board));
let showIndex = $state(false);
let fen = $state(startFEN);
const game = new Game();
let board = $state(Array.from(game.board));
game.subscribe(updateView);
function updateView() {
boardView = Array.from(board.board);
board = Array.from(game.board);
}
</script>
<div class="grid grid-cols-8 gap-0 border-2">
{#each boardView as square, index}
{#each board as square, index}
<div class="h-20 aspect-square relative flex justify-center items-center
{index % 2 === Math.floor(index / 8) % 2 ? 'bg-orange-200 text-stone-800' : 'bg-amber-800 text-stone-200'}
">
@ -31,10 +32,9 @@
<label class="block">
fen (enter to set):
<input type="text" onkeypress={(e) => e.key === 'Enter' && (() => {
board.loadFEN(fen)
updateView()
game.loadFEN(fen);
})()} bind:value={fen} />
</label>
<button onclick={updateView}>update view</button>
<button onclick={() => console.log(board)}>dump game to console</button>
<button onclick={() => console.log(game)}>dump game to console</button>
</div>