File size: 8,766 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
// Tiered, deterministic correctness verifier for the Minesweeper task.
// Drives window.__game with EXPLICIT mine layouts (no RNG) 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 assert(cond, msg){ if (!cond) throw new Error(msg); }

// --- independent reference model (mirrors the spec) -----------------------
function buildExpected(rows, cols, mines){
  const mineSet = new Set(mines.map(m => m[0] + ',' + m[1]));
  const isMine = (r,c) => mineSet.has(r + ',' + c);
  const adj = (r,c) => {
    let n = 0;
    for (let dr=-1; dr<=1; dr++) for (let dc=-1; dc<=1; dc++){
      if (dr===0 && dc===0) continue;
      const rr=r+dr, cc=c+dc;
      if (rr<0||rr>=rows||cc<0||cc>=cols) continue;
      if (isMine(rr,cc)) n++;
    }
    return n;
  };
  return { isMine, adj };
}

// Expected revealed set from a flood-fill reveal of (sr,sc) on a board where
// nothing is flagged: BFS through zero-adj cells, including bordering numbered
// cells, never crossing a mine.
function expectedFlood(rows, cols, mines, sr, sc){
  const { isMine, adj } = buildExpected(rows, cols, mines);
  const revealed = new Set();
  const stack = [[sr,sc]];
  while (stack.length){
    const [r,c] = stack.pop();
    if (r<0||r>=rows||c<0||c>=cols) continue;
    const key = r + ',' + c;
    if (revealed.has(key)) continue;
    if (isMine(r,c)) continue;
    revealed.add(key);
    if (adj(r,c) === 0){
      for (let dr=-1; dr<=1; dr++) for (let dc=-1; dc<=1; dc++){
        if (dr===0 && dc===0) continue;
        stack.push([r+dr, c+dc]);
      }
    }
  }
  return revealed;
}

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({ viewport: { width: 480, 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.reveal === 'function'
    && typeof window.__game.toggleFlag === 'function'));

  // Helper to run a scripted scenario in-page and return the resulting state(s).
  const run = (fn, arg) => page.evaluate(fn, arg);

  // Layouts used throughout. A 5x5 with mines clustered in the top-left corner
  // plus a vertical "wall" down column 2 (rows 2-4). Flooding from the lower-
  // right zero cell (4,4) reveals only the right-hand region + its numbered
  // border; the left-hand region stays hidden, so the game does NOT auto-win.
  const L = { rows: 5, cols: 5, mines: [[0,0],[0,1],[1,0],[2,2],[3,2],[4,2]] };

  const tiers = [
    ['T1 API present + init known layout: rows*cols hidden cells, status playing', async () => {
      assert(hasApi, 'window.__game with init/getState/reveal/toggleFlag is required');
      assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | '));
      const st = await run((L) => window.__game.init(L), L);
      assert(st.rows === 5 && st.cols === 5, 'rows/cols must match init, got ' + st.rows + 'x' + st.cols);
      assert(Array.isArray(st.cells) && st.cells.length === 25, 'cells must be rows*cols=25, got ' + (st.cells && st.cells.length));
      assert(st.status === 'playing', 'fresh game status must be playing, got ' + st.status);
      assert(st.cells.every(c => c.revealed === false && c.flagged === false), 'all cells must start hidden and unflagged');
    }],

    ['T2 adjacency: mine flags + adj counts match independent computation', async () => {
      const st = await run((L) => window.__game.init(L), L);
      const { isMine, adj } = buildExpected(L.rows, L.cols, L.mines);
      // Check specific cells: the mines themselves, and several numbered cells.
      const checks = [
        [0,0],[0,1],[1,0],            // mines
        [1,1],[0,2],[2,0],[1,2],[2,1],[2,2], // border / numbered cells
        [4,4],[3,3]                   // far zero cells
      ];
      for (const [r,c] of checks){
        const cell = st.cells[r * L.cols + c];
        assert(cell.mine === isMine(r,c), 'mine flag wrong at ('+r+','+c+'): got '+cell.mine+' want '+isMine(r,c));
        assert(cell.adj === adj(r,c), 'adj wrong at ('+r+','+c+'): got '+cell.adj+' want '+adj(r,c));
      }
    }],

    ['T3 flood-fill: full zero-region + numbered border revealed, rest hidden', async () => {
      await run((L) => window.__game.init(L), L);
      const sr = 4, sc = 4; // a zero-adj cell deep in the mine-free region
      const boardView=page.locator('[data-testid=board],#board').first();
      const beforePaint=await boardView.screenshot();
      const st = await run((arg) => window.__game.reveal(arg.sr, arg.sc),
        { sr, sc });
      const expected = expectedFlood(L.rows, L.cols, L.mines, sr, sc);
      assert(expected.has(sr+','+sc), 'sanity: start cell must be a revealable zero cell');
      assert(expected.size > 5, 'sanity: zero-region should be sizeable, got ' + expected.size);
      for (let r=0; r<L.rows; r++) for (let c=0; c<L.cols; c++){
        const cell = st.cells[r * L.cols + c];
        const want = expected.has(r+','+c);
        assert(cell.revealed === want,
          'revealed mismatch at ('+r+','+c+'): got '+cell.revealed+' want '+want);
      }
      assert(st.status === 'playing', 'status must still be playing after a safe flood, got ' + st.status);
      // Render-reflection anti-fake: the rendered DOM board must mirror the
      // in-memory state. An engine that computes state but paints nothing fails.
      // The instruction contracts the board via data-testid="board" (id="board"
      // is NOT required); a revealed cell may be marked by a class token OR by
      // visible painted content (a number / mine glyph). Count revealed cells
      // broadly so any visibly-correct rendering passes.
      const afterPaint=await boardView.screenshot();
      assert(!beforePaint.equals(afterPaint),'revealed region must visibly update the actual board');

    }],

    ['T4 flag: toggle flips flagged; reveal on flagged is a no-op; toggle unflags', async () => {
      await run((L) => window.__game.init(L), L);
      // flag a hidden non-mine cell
      let st = await run(() => window.__game.toggleFlag(3,3));
      assert(st.cells[3*5+3].flagged === true, 'toggleFlag should set flagged=true');
      assert(st.cells[3*5+3].revealed === false, 'flagged cell must remain hidden');
      // reveal on a flagged cell is a no-op (stays hidden)
      st = await run(() => window.__game.reveal(3,3));
      assert(st.cells[3*5+3].revealed === false, 'reveal on a flagged cell must be a no-op (stay hidden)');
      assert(st.cells[3*5+3].flagged === true, 'reveal on flagged cell must not clear the flag');
      // unflag
      st = await run(() => window.__game.toggleFlag(3,3));
      assert(st.cells[3*5+3].flagged === false, 'second toggleFlag should unflag');
    }],

    ['T5 win/lose: revealing a mine -> lost + mines shown; clearing all -> won', async () => {
      // Lose: reveal a mine; all mines become revealed, status lost.
      let st = await run((L) => { window.__game.init(L); return window.__game.reveal(0,0); }, L);
      assert(st.status === 'lost', 'revealing a mine must set status lost, got ' + st.status);
      for (let r=0; r<L.rows; r++) for (let c=0; c<L.cols; c++){
        const cell = st.cells[r*L.cols+c];
        if (cell.mine) assert(cell.revealed === true, 'all mines must be shown on loss, ('+r+','+c+') not revealed');
      }
      // Win: a fresh small board; reveal every non-mine cell -> won.
      const W = { rows: 3, cols: 3, mines: [[0,0]] };
      st = await run((W) => {
        window.__game.init(W);
        let s;
        for (let r=0; r<W.rows; r++) for (let c=0; c<W.cols; c++){
          if (r===0 && c===0) continue; // skip the mine
          s = window.__game.reveal(r,c);
        }
        return s;
      }, W);
      assert(st.status === 'won', 'revealing all non-mine cells must set status won, got ' + st.status);
    }],
  ];

  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'); });