File size: 13,653 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Tiered, deterministic correctness verifier for the Reversi/Othello task.
// Drives window.__game and asserts exact state transitions. Prints PASS/FAIL per
// tier and a final `SCORE=<fraction>` used by test.sh as the (partial) reward.
const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');

function eq(a, b){ return require("node:util").isDeepStrictEqual(a,b); }
function assert(cond, msg){ if (!cond) throw new Error(msg); }

// ---------- reference Reversi engine (used to compute expected outcomes) ----------
const DIRS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];
function emptyBoard(){ return Array.from({length:8}, () => Array(8).fill(null)); }
function clone(b){ return b.map(r => r.slice()); }
function opp(t){ return t === 'B' ? 'W' : 'B'; }
function inB(r,c){ return r>=0 && r<8 && c>=0 && c<8; }
// flips that move (r,c) by `turn` would cause; [] if illegal / occupied.
function flipsFor(board, r, c, turn){
  if (!inB(r,c) || board[r][c] !== null) return [];
  const o = opp(turn);
  const all = [];
  for (const [dr,dc] of DIRS){
    const line = [];
    let nr = r+dr, nc = c+dc;
    while (inB(nr,nc) && board[nr][nc] === o){ line.push([nr,nc]); nr+=dr; nc+=dc; }
    if (line.length && inB(nr,nc) && board[nr][nc] === turn) all.push(...line);
  }
  return all;
}
function refLegalMoves(board, turn){
  const out = [];
  for (let r=0;r<8;r++) for (let c=0;c<8;c++) if (flipsFor(board,r,c,turn).length) out.push([r,c]);
  return out;
}
function counts(board){
  let B=0,W=0;
  for (const row of board) for (const v of row){ if (v==='B') B++; else if (v==='W') W++; }
  return { B, W };
}

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({ viewport: { width: 640, height: 760 } });
  const errs = [];
  page.on('pageerror', e => errs.push(e.message));
  await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' });
  await page.waitForTimeout(300);

  const hasApi = await page.evaluate(() => !!(window.__game
    && typeof window.__game.init === 'function'
    && typeof window.__game.getState === 'function'
    && typeof window.__game.legalMoves === 'function'
    && typeof window.__game.play === 'function'
    && typeof window.__game.setState === 'function'));

  const run = (fn, arg) => page.evaluate(fn, arg);
  const sortMoves = ms => ms.map(m => m.slice()).sort((a,b)=> a[0]-b[0] || a[1]-b[1]);

  // ---------- standard opening (for T1) ----------
  const opening = emptyBoard();
  opening[3][3]='W'; opening[3][4]='B'; opening[4][3]='B'; opening[4][4]='W';

  // ---------- T3 fixture: a Black move flipping in MULTIPLE directions ----------
  // Black plays at (4,4). It must bracket White in 3 distinct directions:
  //   up:        (3,4)=W flanked by (2,4)=B
  //   left:      (4,3)=W flanked by (4,2)=B
  //   down-right:(5,5)=W flanked by (6,6)=B
  const t3 = emptyBoard();
  t3[2][4]='B'; t3[3][4]='W';            // vertical up
  t3[4][2]='B'; t3[4][3]='W';            // horizontal left
  t3[6][6]='B'; t3[5][5]='W';            // diagonal down-right
  // give White a guaranteed reply (off every ray from (4,4)) so the turn must
  // genuinely switch to W (no auto-pass): W can play (0,2) flanking B at (0,1).
  t3[0][0]='W'; t3[0][1]='B';
  const t3move = [4,4];
  const t3flips = flipsFor(t3, t3move[0], t3move[1], 'B');
  const t3expected = clone(t3);
  t3expected[t3move[0]][t3move[1]] = 'B';
  for (const [fr,fc] of t3flips) t3expected[fr][fc] = 'B';

  // ---------- T5a fixture: current side (B) has NO legal move; W does -> pass ----------
  // Tiny corner cluster, rest empty. With only B and W discs and lots of empties,
  // we engineer it so legalMoves('B') is empty but legalMoves('W') is non-empty,
  // and after W plays, B still has no move and play passes back to W.
  // Layout (rows 0..2, cols 0..2):
  //   (0,0)=W (0,1)=B
  //   (1,0)=B
  // For B: needs to flank a W between B and B. (0,0)=W neighbours: (0,1)=B and (1,0)=B,
  //   but the cell on the far side of W from each B is off-board -> B has no move.
  // For W: e.g. play (0,2): left neighbour (0,1)=B, (0,0)=W flanks -> legal, flips (0,1).
  const t5a = emptyBoard();
  t5a[0][0]='W'; t5a[0][1]='B'; t5a[1][0]='B';
  const t5aLegalB = refLegalMoves(t5a, 'B');
  const t5aLegalW = refLegalMoves(t5a, 'W');

  // ---------- T5b fixtures: terminal boards, neither side can move ----------
  // (i) Full board, Black has more discs -> winner 'B'.
  const t5bWin = emptyBoard();
  for (let r=0;r<8;r++) for (let c=0;c<8;c++) t5bWin[r][c] = (r*8+c) < 40 ? 'B' : 'W'; // 40 B, 24 W
  const winCounts = counts(t5bWin);                 // {B:40, W:24}
  // (ii) Full board, exact tie -> winner 'draw'.
  const t5bDraw = emptyBoard();
  for (let r=0;r<8;r++) for (let c=0;c<8;c++) t5bDraw[r][c] = (r*8+c) < 32 ? 'B' : 'W'; // 32/32
  const drawCounts = counts(t5bDraw);
  // sanity: full board => no legal moves for either side
  assert(refLegalMoves(t5bWin,'B').length===0 && refLegalMoves(t5bWin,'W').length===0, 'fixture: win board not terminal');
  assert(refLegalMoves(t5bDraw,'B').length===0 && refLegalMoves(t5bDraw,'W').length===0, 'fixture: draw board not terminal');

  const tiers = [
    ['T1 API present + no errors + standard opening', async () => {
      assert(hasApi, 'window.__game with init/getState/legalMoves/play/setState is required');
      assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | '));
      const st = await run(() => window.__game.init());
      assert(Array.isArray(st.board) && st.board.length === 8 && st.board.every(r => Array.isArray(r) && r.length === 8), 'board must be 8x8');
      assert(eq(st.board, opening), 'init must produce the standard 4-disc opening, got ' + JSON.stringify(st.board));
      assert(st.turn === 'B', 'opening turn must be B, got ' + st.turn);
      assert(st.status === 'playing', 'opening status must be playing, got ' + st.status);
      assert(eq(st.counts, {B:2, W:2}), 'opening counts must be {B:2,W:2}, got ' + JSON.stringify(st.counts));
      assert(st.winner === null, 'opening winner must be null, got ' + JSON.stringify(st.winner));
      // Require visible opening pieces without imposing private CSS/DOM names.
      const view=page.locator('[data-testid="board"],#board').first();
      assert(await view.isVisible(),'visible playable board required');
      const openingPaint=await view.screenshot();
      await run(()=>window.__game.setState(Array.from({length:8},()=>Array(8).fill(null)),'B'));
      const emptyPaint=await view.screenshot();
      assert(!openingPaint.equals(emptyPaint),'opening discs must be visibly painted, independent of DOM tags, CSS names or canvas');
      await run(()=>window.__game.init({}));

    }],

    ['T2 legalMoves from opening for Black', async () => {
      const moves = await run(() => { window.__game.init(); return window.__game.legalMoves(); });
      const got = sortMoves(moves);
      const expected = sortMoves([[2,3],[3,2],[4,5],[5,4]]);
      assert(eq(got, expected), 'opening Black legal moves must be {[2,3],[3,2],[4,5],[5,4]}, got ' + JSON.stringify(got));
    }],

    ['T3 multi-direction flip', async () => {
      assert(t3flips.length >= 3, 'fixture sanity: expected >=3 flips, got ' + t3flips.length);
      const st = await run((args) => {
        window.__game.setState(args.board, 'B');
        return window.__game.play(args.move[0], args.move[1]);
      }, { board: t3, move: t3move });
      assert(eq(st.board, t3expected), 'after the multi-direction move, board must match expected (all bracketed discs flipped). got '
        + JSON.stringify(st.board) + ' expected ' + JSON.stringify(t3expected));
      assert(st.turn === 'W', 'turn must switch to W after a legal move, got ' + st.turn);
      assert(eq(st.counts, counts(t3expected)), 'counts must match flipped board, got ' + JSON.stringify(st.counts));
    }],

    ['T4 illegal play is a no-op', async () => {
      // (a) a cell that flips nothing -> no-op (board + turn unchanged)
      const a = await run((board) => {
        const before = window.__game.setState(board, 'B');
        const after = window.__game.play(0, 7); // empty corner, brackets nothing in this fixture
        return { before, after };
      }, t3);
      assert(eq(a.after.board, a.before.board), 'flips-nothing play must leave board unchanged');
      assert(a.after.turn === a.before.turn && a.after.turn === 'B', 'flips-nothing play must leave turn unchanged (B)');
      // (b) playing on an occupied cell -> no-op
      const b = await run((board) => {
        const before = window.__game.setState(board, 'B');
        const after = window.__game.play(3, 4); // already 'W' in fixture
        return { before, after };
      }, t3);
      assert(eq(b.after.board, b.before.board), 'play on an occupied cell must leave board unchanged');
      assert(b.after.turn === b.before.turn && b.after.turn === 'B', 'play on an occupied cell must leave turn unchanged (B)');
    }],

    ['T5 pass + terminal/winner', async () => {
      assert(t5aLegalB.length === 0, 'fixture sanity: B should have no legal move');
      assert(t5aLegalW.length > 0, 'fixture sanity: W should have a legal move');
      // (a) current turn = B with no legal move -> legalMoves() empty.
      const la = await run((board) => { window.__game.setState(board, 'B'); return window.__game.legalMoves(); }, t5a);
      assert(Array.isArray(la) && la.length === 0, 'side-to-move (B) with no move must report empty legalMoves(), got ' + JSON.stringify(la));
      // pass rule: set turn to W (who can move), play a W move; afterwards B has no move,
      // so the engine must pass back -> turn returns to W (not stuck on B).
      const wMove = t5aLegalW[0];
      const afterPlay = await run((args) => {
        window.__game.setState(args.board, 'W');
        return window.__game.play(args.m[0], args.m[1]);
      }, { board: t5a, m: wMove });
      // compute expected board after W's move via reference engine
      const expBoard = clone(t5a);
      const wf = flipsFor(t5a, wMove[0], wMove[1], 'W');
      expBoard[wMove[0]][wMove[1]] = 'W';
      for (const [fr,fc] of wf) expBoard[fr][fc] = 'W';
      const bAfter = refLegalMoves(expBoard, 'B');
      assert(eq(afterPlay.board, expBoard), 'W move must flip correctly, got ' + JSON.stringify(afterPlay.board));
      if (bAfter.length === 0 && refLegalMoves(expBoard, 'W').length > 0){
        assert(afterPlay.turn === 'W', 'when B cannot move after W, turn must pass back to W, got ' + afterPlay.turn);
        assert(afterPlay.status === 'playing', 'game should still be playing after a pass, got ' + afterPlay.status);
      } else {
        assert(afterPlay.turn === 'B', 'turn should switch to B when B has a move, got ' + afterPlay.turn);
      }
      // (b-i) terminal full board, Black ahead.
      // The instruction documents the terminal/winner determination inside play()
      // (not as a setState side-effect). A full board has no playable move, so we
      // accept EITHER an engine that eagerly reports terminal on setState (over +
      // winner) OR one that correctly reports no legal moves for either side
      // (terminal by the documented rules). We only require the winner when the
      // engine itself declares the game over.
      const w = await run((board) => {
        const st = window.__game.setState(board, 'B');
        const movesB = window.__game.legalMoves().length;
        window.__game.setState(board, 'W');
        const movesW = window.__game.legalMoves().length;
        return { st, movesB, movesW };
      }, t5bWin);
      assert(eq(w.st.counts, winCounts), 'counts must match terminal board, got ' + JSON.stringify(w.st.counts));
      const wNoMoves = w.movesB === 0 && w.movesW === 0;
      assert(w.st.status === 'over' && wNoMoves,
        'full terminal board must be reported "over" OR have no legal moves for either side; got status ' + w.st.status + ' movesB=' + w.movesB + ' movesW=' + w.movesW);
      if (w.st.status === 'over') assert(w.st.winner === 'B', 'winner must be B (more discs), got ' + JSON.stringify(w.st.winner));
      assert(la.length === 0, 'guard'); // keep la referenced
      // (b-ii) terminal full board, tie.
      const d = await run((board) => {
        const st = window.__game.setState(board, 'W');
        const movesB = (window.__game.setState(board, 'B'), window.__game.legalMoves().length);
        window.__game.setState(board, 'W');
        const movesW = window.__game.legalMoves().length;
        return { st, movesB, movesW };
      }, t5bDraw);
      assert(eq(d.st.counts, drawCounts), 'tie counts must be {B:32,W:32}, got ' + JSON.stringify(d.st.counts));
      const dNoMoves = d.movesB === 0 && d.movesW === 0;
      assert(d.st.status === 'over' && dNoMoves,
        'full tie board must be reported "over" OR have no legal moves for either side; got status ' + d.st.status + ' movesB=' + d.movesB + ' movesW=' + d.movesW);
      if (d.st.status === 'over') assert(d.st.winner === 'draw', 'winner must be draw on a tie, got ' + JSON.stringify(d.st.winner));
    }],
  ];

  let passed = 0;
  for (const [name, fn] of tiers){
    try { await fn(); passed++; console.log('PASS ' + name); }
    catch (e){ console.log('FAIL ' + name + ': ' + (e && e.message || e)); }
  }
  console.log('TIERS ' + passed + '/' + tiers.length);
  console.log('SCORE=' + (passed / tiers.length).toFixed(3));
  await browser.close();
})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); });