formation-chess-web 0.2.0

Rules engine and text notation for Formation Chess (阵棋), a strategy board game where piece formations reshape nearby abilities
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import { renderBoard, getIntersection } from './board.js';
import { createPieceElement, PIECE_NAMES_RED, PIECE_NAMES_BLACK } from './pieces.js';
import { showMoveHints, showPlacementHints, clearHints, setSelected } from './hints.js';
import { postHints, getRules } from './api.js';

let gameState = null;
let selection = { type: null };
let onAction = null; /* callback to main: (action) => void */

export function init(actionCallback) {
    onAction = actionCallback;
    bindToolbar();
    bindBoard();
    bindPool();
    bindOverlay();
    bindGameOver();
}

function bindToolbar() {
    document.getElementById('btn-new').addEventListener('click', () => {
        if (onAction) onAction({ type: 'new_game', board: { width: 9, height: 10 } });
    });
    document.getElementById('btn-custom').addEventListener('click', openCustomPanel);
    document.getElementById('btn-rules').addEventListener('click', openRulesPanel);
    document.getElementById('btn-pass').addEventListener('click', () => {
        if (onAction) onAction({ type: 'pass' });
    });
    document.getElementById('btn-resign').addEventListener('click', () => {
        if (onAction) onAction({ type: 'resign' });
    });
    document.getElementById('white-indicator').addEventListener('click', onWhiteIndicator);
}

function bindBoard() {
    document.getElementById('board').addEventListener('click', (e) => {
        const intn = e.target.closest('.intersection');
        if (!intn) return;
        const x = Number(intn.dataset.x);
        const y = Number(intn.dataset.y);
        handleBoardClick(x, y);
    });
}

function bindPool() {
    document.getElementById('red-pool').addEventListener('click', (e) => {
        const pieceEl = e.target.closest('.piece');
        if (!pieceEl) return;
        handlePoolClick(pieceEl.dataset.pieceName, pieceEl.dataset.pieceColor);
    });
    document.getElementById('black-pool').addEventListener('click', (e) => {
        const pieceEl = e.target.closest('.piece');
        if (!pieceEl) return;
        handlePoolClick(pieceEl.dataset.pieceName, pieceEl.dataset.pieceColor);
    });
}

function bindOverlay() {
    document.getElementById('overlay').addEventListener('click', (e) => {
        if (e.target === e.currentTarget) closeAllPanels();
    });
    for (const btn of document.querySelectorAll('.panel-close')) {
        btn.addEventListener('click', closeAllPanels);
    }

    /* tabs */
    document.querySelector('.panel-tabs').addEventListener('click', (e) => {
        if (!e.target.classList.contains('tab')) return;
        const tabName = e.target.dataset.tab;
        for (const t of document.querySelectorAll('.panel-tabs .tab')) {
            t.classList.toggle('active', t === e.target);
        }
        for (const c of document.querySelectorAll('.panel .tab-content')) {
            c.classList.toggle('active', c.id === tabName);
        }
    });

    /* custom panel buttons */
    document.getElementById('btn-size-confirm').addEventListener('click', confirmSizeGame);
    document.getElementById('btn-random-confirm').addEventListener('click', confirmRandomGame);
    document.getElementById('btn-load-confirm').addEventListener('click', confirmLoadGame);

    /* popup */
    document.getElementById('popup-choose').addEventListener('click', (e) => {
        const btn = e.target.closest('button');
        if (!btn) return;
        handlePopupChoice(btn.dataset.choice);
    });
}

function bindGameOver() {
    document.getElementById('btn-game-over-new').addEventListener('click', () => {
        hideGameOver();
        if (onAction) onAction({ type: 'new_game', board: { width: 9, height: 10 } });
    });
    document.getElementById('btn-game-over-close').addEventListener('click', hideGameOver);
}

/* ======== State & Render ======== */

function phase() {
    if (!gameState) return 'placement';
    return (gameState.red_pool.length > 0 || gameState.black_pool.length > 0) ? 'placement' : 'movement';
}

export function render(state) {
    gameState = state;
    clearSelection();
    renderBoard(state);
    renderPools(state);
    renderToolbar(state);

    const p = phase();
    const playing = state.result === 'Unfinished' && p === 'movement';
    document.getElementById('btn-pass').style.display = playing ? '' : 'none';
    document.getElementById('btn-resign').style.display = playing ? '' : 'none';
    document.getElementById('white-indicator').classList.toggle('no-white', state.white_pool === 0 || !playing);

    if (state.result !== 'Unfinished') {
        setStatus(resultLabel(state.result));
        showGameOver(state.result);
    } else if (p === 'placement') {
        hideGameOver();
        setStatus(`${playerLabel(state.player)}`);
    } else {
        hideGameOver();
        setStatus(`${playerLabel(state.player)}`);
    }
}

function renderPools(state) {
    const redItems = document.getElementById('red-pool').querySelector('.pool-items');
    const blackItems = document.getElementById('black-pool').querySelector('.pool-items');

    redItems.innerHTML = '';
    blackItems.innerHTML = '';

    const rank = Object.fromEntries(PIECE_NAMES_RED.map((n, i) => [n, i]));
    const sortPool = (pieces) => [...pieces].sort((a, b) => (rank[a.name] ?? 99) - (rank[b.name] ?? 99));

    for (const piece of sortPool(state.red_pool)) {
        redItems.appendChild(createPieceElement(piece, true));
    }
    for (const piece of sortPool(state.black_pool)) {
        blackItems.appendChild(createPieceElement(piece, true));
    }
}

function playerLabel(player) {
    return player === 'Red' ? '' : '';
}

function resultLabel(result) {
    switch (result) {
        case 'RedWin': return '红胜';
        case 'BlackWin': return '黑胜';
        case 'Draw': return '和棋';
        default: return '';
    }
}

function renderToolbar(state) {
    document.getElementById('player-indicator').textContent = `${playerLabel(state.player)}`;
    document.getElementById('white-indicator').textContent = `×${state.white_pool}`;
}

let statusTimeout = null;
export function setStatus(msg, error = false) {
    clearTimeout(statusTimeout);
    const el = document.getElementById('status');
    el.textContent = msg;
    el.classList.toggle('error', error);
    if (!error && msg) {
        statusTimeout = setTimeout(() => { el.textContent = ''; }, 4000);
    }
}

function clearSelection() {
    selection = { type: null };
    clearHints();
    for (const el of document.querySelectorAll('.intersection.selected')) {
        el.classList.remove('selected');
    }
    for (const el of document.querySelectorAll('.pool-piece-selected')) {
        el.classList.remove('pool-piece-selected');
    }
}

/* ======== Board Click Handling ======== */

async function handleBoardClick(x, y) {
    const p = phase();
    const intn = getIntersection(x, y);
    const hasPiece = intn && intn.querySelector('.piece');
    const hintType = intn ? (intn.dataset.hintType || '') : '';
    const hintTypes = intn ? (intn.dataset.hintTypes || '') : '';

    /* Phase: movement — clicking a white placement target */
    if (p === 'movement' && hintType === 'place_white') {
        if (onAction) onAction({ type: 'place', piece: { name: '', color: 'White' }, to: [x, y] });
        return;
    }

    /* Phase: movement — clicking a move/capture/push target */
    if (p === 'movement' && (hintType === 'move' || hintType === 'capture' || hintType === 'push' || hintTypes)) {
        if (hintTypes) {
            showPopup(x, y, hintTypes.split(','));
        } else {
            executeHintAction(hintType, x, y);
        }
        return;
    }

    /* Phase: placement — clicking own half */
    if (p === 'placement' && selection.type === 'pool_piece' && !hasPiece) {
        if (isOwnHalf(x, y, selection.piece.color)) {
            if (onAction) onAction({ type: 'place', piece: { name: selection.piece.name, color: selection.piece.color }, to: [x, y] });
            return;
        }
        setStatus('只能放在己方半区', true);
        return;
    }

    /* Phase: movement — clicking own piece to query hints */
    if (p === 'movement' && hasPiece && !hintType && !hintTypes) {
        clearSelection();
        setSelected(x, y);
        try {
            const hints = await postHints({ x, y });
            showMoveHints(hints.moves);
            if (hints.moves && hints.moves.length === 0) {
                setStatus('该棋子无可行动作', true);
            }
        } catch (e) {
            setStatus(e.message, true);
        }
        return;
    }

    /* anything else: clear selection */
    clearSelection();
}

function isOwnHalf(x, y, color) {
    if (!gameState) return false;
    const h = gameState.board.height;
    if (color === 'Red') return y >= Math.ceil(h / 2);
    return y < Math.floor(h / 2);
}

function executeHintAction(hintType, x, y) {
    if (hintType === 'move') {
        if (onAction) onAction({ type: 'move', from: getSelectedBoardPos(), to: [x, y] });
    } else if (hintType === 'capture') {
        if (onAction) onAction({ type: 'capture', from: getSelectedBoardPos(), to: [x, y] });
    } else if (hintType === 'push') {
        if (onAction) onAction({ type: 'push', from: getSelectedBoardPos(), to: [x, y] });
    }
}

function getSelectedBoardPos() {
    const sel = document.querySelector('.intersection.selected');
    if (sel) return [Number(sel.dataset.x), Number(sel.dataset.y)];
    return [0, 0];
}

/* ======== Pool Click Handling ======== */

function handlePoolClick(name, color) {
    if (phase() !== 'placement') return;
    if (gameState && color !== gameState.player) return;

    clearSelection();
    selection = { type: 'pool_piece', piece: { name, color } };

    const el = document.querySelector(`.pool .piece[data-piece-name="${name}"][data-piece-color="${color}"]`);
    if (el && el.parentElement) el.parentElement.classList.add('pool-piece-selected');
}

/* ======== White Indicator ======== */

async function onWhiteIndicator() {
    if (phase() !== 'movement' || !gameState || gameState.white_pool === 0) return;

    clearSelection();
    selection = { type: 'white_placement' };
    try {
        const hints = await postHints({ white: true });
        showPlacementHints(hints.placements);
        if (hints.placements && hints.placements.length === 0) {
            setStatus('无可放置白子的位置', true);
        }
    } catch (e) {
        setStatus(e.message, true);
    }
}

/* ======== Popup (capture / push choice) ======== */

function showPopup(x, y, types) {
    const popup = document.getElementById('popup-choose');
    popup.innerHTML = '';
    for (const t of types) {
        const btn = document.createElement('button');
        btn.dataset.choice = t;
        btn.dataset.tx = x;
        btn.dataset.ty = y;
        btn.textContent = t === 'capture' ? '吃子' : '推子';
        btn.className = t === 'capture' ? 'capture-opt' : 'push-opt';
        popup.appendChild(btn);
    }

    const intn = getIntersection(x, y);
    if (intn) {
        const rect = intn.getBoundingClientRect();
        popup.style.left = `${rect.right + 4}px`;
        popup.style.top = `${rect.top}px`;
    }

    popup.classList.remove('hidden');
}

function handlePopupChoice(actionType) {
    const popup = document.getElementById('popup-choose');
    const btn = popup.querySelector(`button[data-choice="${actionType}"]`);
    const x = Number(btn.dataset.tx);
    const y = Number(btn.dataset.ty);
    popup.classList.add('hidden');

    if (onAction) onAction({ type: actionType, from: getSelectedBoardPos(), to: [x, y] });
}

export function hidePopup() {
    document.getElementById('popup-choose').classList.add('hidden');
}

/* ======== Custom Panel ======== */

function openCustomPanel() {
    document.getElementById('overlay').classList.remove('hidden');
    document.getElementById('panel-custom').classList.remove('hidden');
    document.getElementById('panel-rules').classList.add('hidden');
}

function confirmSizeGame() {
    const w = clampSize(Number(document.getElementById('custom-width').value), 1, 16);
    const h = clampSize(Number(document.getElementById('custom-height').value), 1, 16);
    closeAllPanels();
    if (onAction) onAction({ type: 'new_game', board: { width: w, height: h } });
}

function confirmRandomGame() {
    const w = clampSize(Number(document.getElementById('rand-width').value), 1, 16);
    const h = clampSize(Number(document.getElementById('rand-height').value), 2, 16);

    const redSlots = w * (h - Math.ceil(h / 2));
    const blackSlots = w * Math.floor(h / 2);
    if (redSlots < 16 || blackSlots < 16) {
        setStatus(` 16  ${redSlots} /  ${blackSlots}`, true);
        return;
    }

    closeAllPanels();

    if (onAction) {
        const randomConfig = buildRandomConfig(w, h);
        onAction({ type: 'new_game', ...randomConfig });
    }
}

function confirmLoadGame() {
    const text = document.getElementById('load-text').value.trim();
    if (!text) return;
    closeAllPanels();

    if (onAction) {
        onAction({ type: 'new_game', notation: text });
    }
}

function closeAllPanels() {
    document.getElementById('overlay').classList.add('hidden');
    document.getElementById('panel-custom').classList.add('hidden');
    document.getElementById('panel-rules').classList.add('hidden');
}

function clampSize(v, min, max) {
    return Math.max(min, Math.min(max, Number.isFinite(v) ? v : min));
}

/* ======== Random Layout ======== */

function buildRandomConfig(width, height) {
    const half = Math.floor(height / 2);
    const midpoint = Math.ceil(height / 2);

    const redPositions = [];
    const blackPositions = [];
    for (let x = 0; x < width; x++) {
        for (let y = midpoint; y < height; y++) redPositions.push([x, y]);
        for (let y = 0; y < half; y++) blackPositions.push([x, y]);
    }

    shuffle(redPositions);
    shuffle(blackPositions);

    const cells = Array.from({ length: height }, () => Array.from({ length: width }, () => null));

    for (let i = 0; i < PIECE_NAMES_RED.length; i++) {
        const [rx, ry] = redPositions[i];
        cells[ry][rx] = { name: PIECE_NAMES_RED[i], color: 'Red' };
    }
    for (let i = 0; i < PIECE_NAMES_BLACK.length; i++) {
        const [bx, by] = blackPositions[i];
        cells[by][bx] = { name: PIECE_NAMES_BLACK[i], color: 'Black' };
    }

    return {
        board: { width, height, cells },
        red_pool: [],
        black_pool: [],
        white_pool: 0,
        player: 'Red',
    };
}

function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

/* ======== Rules Panel ======== */

async function openRulesPanel() {
    document.getElementById('overlay').classList.remove('hidden');
    document.getElementById('panel-rules').classList.remove('hidden');
    document.getElementById('panel-custom').classList.add('hidden');

    const content = document.getElementById('panel-rules').querySelector('.rules-content');
    if (content.dataset.loaded === '1') return;
    content.dataset.loaded = '1';

    try {
        const data = await getRules();
        content.textContent = data.text || '';
    } catch (e) {
        content.textContent = '无法加载规则';
    }
}

/* ======== Game Over Overlay ======== */

function showGameOver(result) {
    const overlay = document.getElementById('game-over');
    const title = overlay.querySelector('.game-over-title');
    title.textContent = resultLabel(result);
    title.className = 'game-over-title';
    switch (result) {
        case 'RedWin': title.classList.add('red'); break;
        case 'BlackWin': title.classList.add('black'); break;
        case 'Draw': title.classList.add('draw'); break;
    }
    overlay.classList.remove('hidden');
}

function hideGameOver() {
    document.getElementById('game-over').classList.add('hidden');
}

/* ======== Export for main.js ======== */

export function isPlacementPhase() {
    return phase() === 'placement';
}