### user
You are a code expert. Please use your professional knowledge to generate accurate and professional responses. Be sure that the code you generate is executable for demonstration.
Please use HTML and JavaScript to implement a "Reflection Maze".
**Task**: Design a reflection maze where players can only determine the correct path by looking at the reflection.
**Hint**: You can create a mirror effect and make the true path of the maze visible only in the reflection.
Please create this game and include comments in your code to help other developers understand your implementation process.
### assistant · thinking
The user wants a "Reflection Maze" game in HTML/JavaScript. The key idea: the maze's true path is only visible in a mirror/reflection. So we need a canvas-based game where the maze is drawn mirrored (or the real maze is hidden), and the player must navigate using the reflection.
Design idea:
- Main canvas shows the maze but the actual walls are hidden — only a "reflection" region (like a puddle/water/mirror at the bottom or a mirror panel on the side) reveals the true layout, flipped.
- The player moves a ball with arrow keys/WASD. The top view shows... hmm.
Let me think of a coherent mechanic:
Classic idea: The maze is rendered normally, but the visible maze is a decoy/mirrored. Actually the hint says "make the true path of the maze visible only in the reflection."
Implementation:
- Left/top area: the "real" maze view, but it's dark/foggy — you can only see the player and walls very close, OR the walls are invisible.
- A mirror strip at the bottom (like a lake) reflects the maze — the reflection shows the TRUE maze walls, but mirrored vertically. So the player sees the reflection of the maze which is flipped, and must mentally un-flip it.
Better: Use a "mirror" panel on the right side that shows the true maze, but horizontally flipped. The main play area shows the maze with walls hidden (or rendered with wrong/fake walls). The player must use the mirror to figure out where walls are.
Actually a cleaner and very playable design:
- Canvas with the maze grid.
- The main view: the player's token and a "fog of war" — you only see a small radius around the player. Walls outside fog are invisible.
- The mirror at the bottom of the screen shows a reflected (vertically flipped) copy of the full maze with the player's position, so you can plan.
Hmm, but then it's just fog + minimap. The "reflection" part is that the mirror is flipped, so it's a challenge to read.
Let me design:
**Layout**: A single canvas, split into two regions:
1. Top region (playfield): the maze where the player moves. Walls are NOT drawn (invisible). Only the player and the goal are drawn. Maybe the floor shows faint hints.
2. Bottom region (mirror/water): a reflection of the maze. Actually, physically, a reflection in water below shows the world above flipped vertically. So we draw the maze reflected across the horizontal axis: the mirror region shows the maze flipped vertically, i.e., row 0 of the maze appears at the bottom of the reflection.
So the player sees the whole maze layout only in the reflection, but flipped vertically. To know if there's a wall above them, they need to look at the reflection below... wait, in a real reflection, what's above the water line appears directly below in the reflection. So a wall right above the player appears right below the player in the mirror. Actually the mirror reflection of the point at height h above the water appears at depth h below the water. So the vertical flip is around the water line.
So if the play area is above the water line and the mirror below, then a point at row y in the play area appears at the mirrored position below. The player can look straight down from their position in the reflection to see what's directly above... no, the reflection shows the whole maze flipped.
Simplest readable design: Play area on top, mirror at the bottom. The mirror shows the maze flipped vertically. So the top row of the maze appears at the bottom of the mirror... which is confusing but that's the challenge. Hmm, actually for a water reflection: the maze sits on the ground plane, and the reflection is below. Point at distance d from the water line appears at distance d below. So the row closest to the water line in the maze appears closest to the water line in the reflection. The farthest row appears farthest down in the reflection.
So if the water line is at the bottom of the maze, then the maze's bottom row is at the water line, and it reflects to just below the water line. The maze's top row reflects to the bottom of the mirror. So the mirror image is the maze flipped vertically. Yes.
That's actually intuitive: the mirror image is flipped, so the bottom of the maze appears at the top of the reflection.
But wait — if the player is in the maze and the walls are invisible in the maze but visible in the reflection, then the player looks at the reflection and sees their own position reflected, and can see where walls are around them. But the vertical flip means "up" in the maze = "down" in the reflection. That's a mental challenge but manageable.
Hmm, but actually, maybe simpler and more elegant: the entire visible maze IS the reflection. I.e., you can't see the maze directly (it's dark/above), you only see it in the mirror. And the reflection is flipped.
Alternatively — a different, more "maze-like" mechanic: **the player is a light beam**. You rotate mirrors to guide a laser. But the hint says the true path is visible only in reflection.
Let me stick with: fog of war + mirror reflection.
Actually, let me reconsider for maximum fun and clarity:
**Design:**
- Canvas split into two halves horizontally (top = "The Maze" real world, bottom = "The Mirror").
- In the real world, the maze walls are invisible (transparent). You see only the player (a glowing orb) and the exit (a portal).
- The mirror below shows a vertically flipped reflection of the entire maze including all walls, drawn with a bluish/watery tint and slight wavy distortion.
- The player moves with arrow keys/WASD. Movement is grid-based or continuous with collision.
- Since walls are invisible in the real world, the player must consult the reflection to know where walls are. Because it's flipped vertically, they must mentally flip.
- Goal: reach the exit.
Wait, but if the maze is invisible in the real world, and the reflection shows the maze flipped, the player can just look at the reflection. The flip makes it a real cognitive task. Good.
But there's a subtlety: in the reflection, the player's own position is also flipped. So the player can locate themselves in the reflection and see the walls around them. That works.
To make it more interesting, add a "reveal" mechanic: when the player bumps into a wall, the wall flashes briefly in the real world? Or maybe not — keep it pure.
Hmm, actually maybe a nicer touch: the reflection is slightly distorted (wavy water) making it harder to read. But too much distortion = frustrating. Let's add subtle ripples that don't affect gameplay.
Let me also add: the walls in the real world are drawn very faintly (like 6% opacity) so you can barely see them — no, better to be fully invisible to force the mirror usage. Hmm, but then the player might feel lost. Actually the mirror gives full information, so it's fine.
Let me reconsider: maybe the real world should show walls as faint "ghosts" only when the player is adjacent? No, keep it clean.
Actually, let me reconsider the whole thing once more. Another interpretation: "reflection maze" — you see a mirror image of the maze, and you have to navigate the real one which is the mirror of what you see. Same thing basically.
OK let's implement.
**Technical plan:**
- HTML5 Canvas, single canvas ~ 900x760.
- Grid maze: e.g., 13 cols x 9 rows, cell size 44px. Maze width = 13*44 = 572, height = 9*44 = 396.
- Layout: canvas width 900. Maze drawn centered horizontally at x offset. Top: real maze area from y=60 to y=456. Water line at y=456. Mirror from y=470 to y=866... too tall. Let's scale down.
Let me compute: canvas 800 wide, 820 tall.
- Header 50px.
- Maze area: 12 cols x 8 rows, cell 40px => 480 x 320. Hmm, want bigger cells.
Let's do: canvas width 720, height 800.
- Cell size 48. Maze 12 x 8 => 576 x 384.
- Maze offset x = (720-576)/2 = 72. y = 60.
- Water line at y = 60 + 384 + 20 = 464.
- Mirror area height = 384 (same), from y = 464+... Actually reflection should be right below the water line, and the reflection of the maze's bottom row is right at the water line. So mirror region: y from 464 to 464+384 = 848. Canvas height 800 → too small.
Reduce cell size to 40: maze 480x320. Canvas 640x760? Let's do canvas 700 x 700.
- Cell 40, maze 12x8 = 480x320.
- x offset = (700-480)/2 = 110.
- Maze y from 40 to 360. Water line at 380.
- Mirror from 380 to 380+320 = 700. Perfect, canvas height 700 (maybe 720 with some padding).
Hmm, mirror starts exactly at water line y=380 and extends 320 down to 700.
The reflection: maze cell (col, row) with row 0 at top. Its screen y = mazeY + row*cell. Distance above water line = waterY - (mazeY + row*cell) ... for row 0 that's 380-40 = 340, for row 7 it's 380 - (40+280) = 60. Reflection: mirrored y = waterY + distance = 380 + 340 = 720 for row 0 → off canvas (canvas 700). Hmm.
Right, because the maze is 320 tall and the water line is at 380, the top of the maze is 340 above the water, so its reflection is 340 below the water = 720. The bottom row is 60 above the water → reflection at 440. So the mirror region spans from 440 to 720 for the maze content... plus the gap between water line (380) and bottom row (400). Hmm, the maze bottom is at y=360, which is 20 above the water line. Its reflection is at 400.
So the reflection occupies y from 400 to 720. Canvas height 740 would work. But it's not aligned with the maze horizontally... it is aligned horizontally (same x), just flipped vertically.
Hmm, but that's a bit odd visually — the reflection is offset. Actually in a real reflection, yes: the object's reflection appears below the water line at equal distance. If the object is 340 above the water, its reflection is 340 below.
Actually for a cleaner look, let's put the water line right at the bottom of the maze. Then the maze bottom row (row 7) is at the water line, and its reflection is right at the water line too. The top row (row 0) is 320 above → reflection at 320 below.
So: maze y from 40 to 360, water line y = 360, mirror from 360 to 680. Canvas height 700.
Then the reflection of the maze occupies y from 360 to 680, which is exactly the same height as the maze. And it's a perfect vertical flip: reflected y = 360 + (360 - y) = 720 - y.
So mirror(row) y = 720 - (mazeY + row*cell) - cell = 720 - mazeY - row*cell - cell. With mazeY=40: = 680 - 40 - row*40 = 640 - row*40... let's verify: row 0 → y=640? Mirror region goes from 360 to 680. Row 0 (top of maze) reflects to bottom of mirror: y = 680 - 40 = 640. Yes. Row 7 → y = 680 - 320 = 360. Yes!
So the reflection drawing: for each cell at (x, y) in maze coords, draw at (x, 720 - y - cell) — i.e., flip vertically about y = 360.
Let me define: mirrorY(y) = 2*waterY - y - cellSize, where waterY = 360. = 720 - y - 40.
Check: y=40 → 720-40-40 = 640. ✓. y=40+7*40=320 → 720-320-40 = 360. ✓.
Great.
Now, is this too confusing? The player at maze row 7 (bottom) sees themselves in the reflection at the top of the mirror region. Hmm. The player is near the bottom of the real maze, and their reflection is near the water line (top of mirror). That's physically correct and quite intuitive actually.
Wait no. Row 7 in the maze is at y=320..360, which is adjacent to the water line at 360. Its reflection is at y=360..400, right below the water line. And mirrorY for row 7 = 720-320-40 = 360. ✓. So the player standing at the bottom of the maze (near the water) has their reflection right below the water line. Correct and intuitive!
And a player at the top of the maze (row 0) has their reflection at the far bottom of the mirror. Also correct.
So the reflection is a true mirror image.
Now the cognitive task: to know if there's a wall directly above the player in the real world, they look at the reflection... the reflection of "above the player" is "below the player's reflection". Hmm, so they look at the mirror and find their reflection, then the walls below the reflection correspond to walls above in reality. Since the mirror is a vertical flip, "up in reality" = "down in mirror". OK.
Actually simpler: the mirror image IS the maze flipped. So they can just read the flipped maze. It's like reading a map that's upside down. Fine.
Hmm, wait. Is this too hard / annoying? Maybe. Let's add an option to toggle the reflection flip... no, the whole point is the reflection.
Alternative: make the reflection horizontally flipped (like a real mirror you face). Then it's a left-right flip, which is also a mental challenge and arguably more "mirror-like". Hmm. But a water reflection is a vertical flip.
I think vertical flip (water reflection) is visually compelling. Let's go with it.
Actually, hold on. Let me reconsider: maybe it's better if the mirror is a vertical panel on the right side of the screen (like a standing mirror), reflecting horizontally. Then the maze and its reflection are side by side at the same height, which makes comparison easier visually but the flip is left-right.
Hmm, with a horizontal flip side-by-side, the player at maze position (col, row) appears at mirror position (mirrored col, row). Then to see what's to the left of the player in reality, they look to the right of their reflection. That's the classic mirror confusion.
Both work. The water reflection below is prettier and more thematic ("reflection"). I'll go with the water/lake reflection below. Actually, let me do the water reflection — it also lets me add nice water ripple effects.
Hmm, but one issue: with the water reflection below, the maze and its reflection are in the same x-range, stacked vertically. The player's eye has to move down. That's fine.
Let me reconsider one more time... Actually I realize there might be an issue: if the reflection is directly below and is a true mirror image, then the player's reflection is directly below them (same x). So "left" and "right" are preserved in the reflection! Only up/down is flipped. That means the player can easily see left/right walls but must mentally flip up/down. That's a nice, learnable challenge.
Now let's build the maze generation. Use recursive backtracker on a grid with walls between cells.
Representation: cells[r][c] = { walls: {n, e, s, w} } or use a bitmask. Or simpler: a grid of (2*rows+1) x (2*cols+1) where 1 = wall. But for smooth rendering with cell size, let's use the cell-with-walls approach.
Actually, for drawing, drawing wall segments as lines is easy.
Maze gen (recursive backtracker):
```js
function generateMaze(cols, rows) {
const cells = [];
for (let r = 0; r < rows; r++) {
cells.push([]);
for (let c = 0; c < cols; c++) {
cells[r].push({ r, c, walls: { n: true, e: true, s: true, w: true }, visited: false });
}
}
const stack = [];
let current = cells[0][0];
current.visited = true;
let visitedCount = 1;
const total = cols * rows;
while (visitedCount < total) {
const neighbors = [];
const { r, c } = current;
if (r > 0 && !cells[r-1][c].visited) neighbors.push(['n', cells[r-1][c]]);
if (r < rows-1 && !cells[r+1][c].visited) neighbors.push(['s', cells[r+1][c]]);
if (c > 0 && !cells[r][c-1].visited) neighbors.push(['w', cells[r][c-1]]);
if (c < cols-1 && !cells[r][c+1].visited) neighbors.push(['e', cells[r][c+1]]);
if (neighbors.length) {
const [dir, next] = neighbors[Math.floor(Math.random()*neighbors.length)];
// remove walls
current.walls[dir] = false;
next.walls[opposite(dir)] = false;
stack.push(current);
current = next;
current.visited = true;
visitedCount++;
} else {
current = stack.pop();
}
}
return cells;
}
```
Player movement: continuous movement with collision would be smoother, but grid-based is simpler and cleaner for a maze. Let's do smooth-ish: the player moves cell to cell with a tween animation? Or just instant snap with a small animation. Let's do tween: player has logical (r,c) and a render position that lerps toward the target. Movement queued.
Actually let's do continuous movement with circle-vs-wall collision — it feels better. Hmm, but with cell size 40 and a player radius of ~12, it's fine.
Hmm, grid-based is safer and easier to make correct. But continuous feels much better for a maze game. Let me do continuous with AABB collision against wall segments.
Player is a circle of radius 12 in a 40px cell. Walls are thin (4px) segments on cell boundaries. Collision: treat the player as a circle, check against each wall segment as a line segment, push out. That's a bit involved but doable.
Simpler: axis-separated movement with AABB. Player is a square (or circle) of half-size 11. Move X, check collisions with walls, revert X if colliding. Then move Y similarly.
Wall collision detection: for the player's AABB, find which cells it overlaps, and for each cell check its walls. Convert walls into rectangles:
- North wall of cell (r,c): rect(x, y-2, cell, 4) where (x,y) is the cell's top-left.
- etc.
Then AABB vs rect test. That works and is simple.
Actually, let's just use the "grid of tiles" approach: create a boolean grid of size (2*rows+1) x (2*cols+1). tile[2r+1][2c+1] = floor. Walls at even indices. Then collision is trivial with AABB vs tile grid.
Hmm, but then cell size halves. Let's use: mazeW = cols cells, each cell 40px. Tile grid: 2*cols+1 tiles wide, each tile 20px. That's the same overall size. Rendering walls as tiles (20x20 blocks) looks chunky but fine... Actually it looks like a classic maze. But thin walls look nicer.
Let me just do: render walls as thin lines (4px), collision via AABB vs wall rectangles. It's not hard.
Let me define:
- CELL = 40
- MAZE_X = 110 (offset), MAZE_Y = 40
- cols = 12, rows = 8 → 480 x 320
- waterY = MAZE_Y + rows*CELL = 360
- canvas: width 700, height 700 (mirror from 360 to 680, plus 20 padding at bottom)
Hmm, 700x700 canvas. Let's make it 720 wide for margin. MAZE_X = (720-480)/2 = 120.
Canvas: 720 x 700.
- Maze: x 120..600, y 40..360.
- Water line: y = 360.
- Mirror: y 360..680.
- Title text at top? Let's put UI outside the canvas in HTML instead. Then maze y from 20 to 340, water line at 340, mirror 340..660, canvas height 680.
Let's do:
- MAZE_Y = 20, waterY = 340, mirror bottom = 660. Canvas 720 x 680.
Hmm, I'd like a bit of space at the top for "the maze (walls invisible)" label. Let's put labels in HTML above/below the canvas. Or draw them on canvas.
Let me finalize:
- CELL = 40, COLS = 12, ROWS = 8
- MAZE_X = 120, MAZE_Y = 40
- MAZE_W = 480, MAZE_H = 320
- waterY = 360
- Canvas: 720 x 700 (mirror region 360..680, 20px padding at the bottom)
Good.
Now rendering:
**Real maze area (y 40..360):**
- Background: dark, with a subtle grid pattern.
- Walls: NOT drawn (invisible).
- Player: glowing orb.
- Exit: glowing portal at bottom-right (or wherever).
- Optionally: a faint "wall hit" flash when the player bumps a wall. Let's add a brief ripple/flash on the wall segment that was hit — nice feedback and doesn't give away the whole map. Actually it might make it too easy. Let's make it subtle: a small spark. Actually, let's add it — good feedback. Hmm, but it could let players just brute-force. It only shows one wall at a time and fades fast, so brute-forcing is still slow. I'll add a subtle impact spark.
Hmm, actually if walls are invisible and the player can only see them in the reflection, bumping into invisible walls is confusing without feedback. So yes, add a spark/flash at the collision point.
**Mirror area (y 360..680):**
- Draw the maze reflected vertically, with a blue/teal tint, lower opacity, and a subtle horizontal ripple distortion.
- Draw the player's reflection too.
- Draw the exit's reflection.
- Add a gradient overlay to fade the reflection slightly with depth.
- Add animated water ripple lines.
For the ripple distortion, I could draw the reflection into an offscreen canvas and then draw it in horizontal slices with a sine offset. That's a nice effect and performant enough.
Let's do: render the "maze world" (walls, exit, player) into an offscreen canvas at maze resolution, then draw it flipped into the mirror with per-row x-offset sine waves. Actually per-scanline drawing of 320 lines each frame is fine (320 drawImage calls per frame — OK).
Hmm, but we need the reflection to also show the player. Let's just render everything (walls + player + exit) into the offscreen "world" canvas, then reflect it.
Wait, but the real maze area shows the player but not the walls. The mirror shows everything. So:
- Offscreen canvas A: contains walls (full maze) + exit + player, at maze coordinates.
- Real area: draw player + exit + background (no walls).
- Mirror area: draw offscreen A flipped, with ripple.
Yes.
Actually, simpler: just draw directly with a transform for the mirror. ctx.save(); ctx.translate(0, 2*waterY); ctx.scale(1, -1); then draw the maze normally (which now appears flipped); ctx.restore(). That's clean! And for ripple, apply per-slice offsets... which requires an offscreen canvas.
Let's use the offscreen canvas approach for the ripple. It's nicer.
Plan:
1. `worldCanvas` (offscreen), size 480x320 (maze area only), drawn each frame with: walls, exit, player.
2. Draw to main canvas:
- Real area: draw background, then draw player and exit (from a separate pass, or just draw them directly), then draw a dark overlay. Actually simpler: draw the real area background, then draw exit and player directly (not walls).
- Mirror area: take worldCanvas, and draw it flipped with ripple slices.
Hmm, but then the real area and world canvas both need the player drawn. Fine, just draw the player twice (once directly, once into worldCanvas).
Actually cleanest:
- Draw real area: bg + exit + player + collision sparks.
- Build worldCanvas: walls + exit + player.
- Draw mirror: flipped worldCanvas with ripple + water tint.
OK.
Ripple implementation:
```js
const sliceH = 4;
for (let y = 0; y < MAZE_H; y += sliceH) {
const t = performance.now() / 1000;
const amp = 1.5 + 2.5 * ((y / MAZE_H)); // more distortion further down?
const offset = Math.sin(y * 0.08 + t * 1.6) * amp;
// source: y slice in worldCanvas; dest: flipped position in mirror
const destY = waterY + (MAZE_H - y - sliceH);
ctx.drawImage(worldCanvas, 0, y, MAZE_W, sliceH, MAZE_X + offset, destY, MAZE_W, sliceH);
}
```
Wait, careful: flipping. The world canvas row y (from top) should map to mirror position: the world canvas represents the maze from y=0 (top) to y=MAZE_H (bottom). In the mirror, the top of the maze (y=0) should be at the bottom of the mirror.
Mirror region: from waterY to waterY + MAZE_H. The maze bottom (y=MAZE_H) reflects to waterY + 0 = waterY (just below the water line). The maze top (y=0) reflects to waterY + MAZE_H.
So dest y for source y is: waterY + (MAZE_H - y - sliceH). Check y = MAZE_H - sliceH (bottom slice) → waterY + 0 = waterY ✓. y=0 → waterY + MAZE_H - sliceH ✓ (bottom of mirror).
Great.
And add horizontal offset for ripple.
Then overlay a blue tint with `globalCompositeOperation = 'source-atop'`? Or just draw a semi-transparent blue rect over the mirror area with 'multiply' or normal alpha. Let's draw a gradient overlay.
Also add the water surface line with a glow.
**Now, the "true path visible only in reflection" aspect.** The walls are invisible in the real view. So the player MUST use the reflection.
Let me also add a "light" effect: maybe the player's orb casts a small glow.
Additional touch: add a few decoy/faint walls in the real view? No, keep it clean.
Hmm, one more consideration: should the real maze area show anything at all besides the player? Let's draw a faint dot grid at cell centers to give a sense of scale. And the exit portal.
Also the goal: reach the exit. On win, show a message and allow restart.
**Controls:** Arrow keys / WASD. Also on-screen touch buttons? Maybe add a note. Let's keep keyboard + maybe touch drag. Keep it simple: keyboard.
Let's also add: press R to regenerate, and maybe a "hint" button.
Let me now also think about whether the maze should be regenerated each time — yes, with a "New Maze" button.
Now, collision details:
```js
const PLAYER_R = 11; // half-size for AABB
player = { x: cx, y: cy, vx: 0, vy: 0 };
```
Where x,y are the center in maze-local coordinates (0..MAZE_W, 0..MAZE_H)? Or canvas coordinates? Let's use maze-local coordinates (0,0 = top-left of maze). Then when drawing, offset by MAZE_X, MAZE_Y.
Movement:
```js
const speed = 130; // px per second
let dx = 0, dy = 0;
if (keys.left) dx -= 1;
if (keys.right) dx += 1;
if (keys.up) dy -= 1;
if (keys.down) dy += 1;
normalize...
```
Then move X and resolve, then move Y and resolve.
Collision resolution with walls:
```js
function collides(x, y) {
// player AABB: [x-R, x+R] x [y-R, y+R]
const minC = Math.floor((x - R) / CELL);
const maxC = Math.floor((x + R) / CELL);
const minR = Math.floor((y - R) / CELL);
const maxR = Math.floor((y + R) / CELL);
for (let r = minR; r <= maxR; r++) {
for (let c = minC; c <= maxC; c++) {
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return true; // outside bounds
const cell = grid[r][c];
const cx0 = c * CELL, cy0 = r * CELL;
// north wall
if (cell.walls.n && y - R < cy0 && x + R > cx0 && x - R < cx0 + CELL) return true;
...
}
}
return false;
}
```
Hmm, the wall check needs the player AABB to actually overlap the wall rectangle. The wall rect for north wall of cell (r,c): x from cx0 to cx0+CELL, y from cy0 - T/2 to cy0 + T/2, where T = wall thickness (say 6). Actually let's define walls as occupying [cy0 - T, cy0] for the north wall? Simpler: the wall is a rectangle centered on the boundary. But for collision, it's easier to say the north wall occupies y in [cy0 - T, cy0]... Hmm, but then adjacent cell's south wall overlaps. It's the same wall.
Let me define: wall thickness T = 6. North wall of cell (r,c) is the rect: x ∈ [cx0 - T/2, cx0 + CELL + T/2], y ∈ [cy0 - T/2, cy0 + T/2]. But that extends into neighboring cells horizontally, which could cause false positives at corners. It's fine actually since walls meet at corners.
Simpler approach: check the player's AABB against the wall rect:
```js
const R_ = PLAYER_R;
// AABB overlap test
function aabbOverlap(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by;
}
```
Player AABB: (x - R, y - R, 2R, 2R).
North wall rect of cell (r,c): (cx0 - T/2, cy0 - T/2, CELL + T, T).
If both overlap → collision.
That works. But since the player is a square of 22px in a 40px cell, and walls are 6px thick, this should be fine.
Hmm, but there's an issue: with the player AABB being 22 wide and the corridor 40 wide, there's 9px clearance on each side. Fine.
Movement resolution:
```js
// X axis
let nx = player.x + vx * dt;
if (!collides(nx, player.y)) player.x = nx;
else { /* find the exact contact and clamp */ }
```
Simple revert is fine but causes sticking. Let's do a small sub-stepping: move in small increments. Or just do: try the full move; if it collides, try smaller steps. Simplest: clamp to the wall.
Actually, a simple approach: move in steps of at most 2px.
```js
const steps = Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / 2);
for (let i = 0; i < steps; i++) {
const sx = dx / steps, sy = dy / steps;
if (!collides(player.x + sx, player.y)) player.x += sx;
if (!collides(player.x, player.y + sy)) player.y += sy;
}
```
This gives smooth sliding along walls.
Now, the exit: at the bottom-right cell (ROWS-1, COLS-1). Center at ((COLS-0.5)*CELL, (ROWS-0.5)*CELL).
Win when the distance from the player to the exit center < CELL*0.5.
Let's also make the start at (0,0) center.
**Rendering the real maze area:**
- Background: dark navy/black with a subtle radial gradient centered on the player (a "torch" light).
- Draw a faint grid of dots at cell centers to hint at the layout.
- Draw the exit as a glowing green/cyan portal.
- Draw the player as a glowing white/cyan orb.
- Draw collision sparks.
Hmm — should we show the player's light revealing walls? No, walls invisible.
**Rendering the mirror:**
- Draw the flipped world canvas with ripples.
- Tint blue.
- Add a horizontal "water line" with a glow.
- Add the text "MIRROR (true maze)" — well, labels via HTML.
Let me now write the code.
```html
Reflection Maze
Reflection Maze
The walls are invisible... look at the reflection!
...
```
Hmm, canvas 720x700 is a bit tall. Let's reduce: CELL = 36, COLS = 12, ROWS = 8 → 432 x 288. Canvas width 600? Let's recompute.
CELL = 36, COLS = 12 → 432 wide. ROWS = 8 → 288 tall.
MAZE_X = (600 - 432)/2 = 84.
MAZE_Y = 44.
waterY = 44 + 288 = 332.
Mirror: 332 to 620.
Canvas: 600 x 640.
That's reasonable. Let's use that.
Hmm, 36px cells with a 22px player... let's scale the player to R = 9 (18px box) — 9px clearance each side. OK.
Actually let me use CELL = 38, COLS = 12 → 456. Canvas width 620, MAZE_X = 82. ROWS = 8 → 304. MAZE_Y = 44, waterY = 348, mirror to 652. Canvas 620x672.
Eh, let's just keep it simple: CELL = 40, COLS = 12, ROWS = 8, MAZE_X = 100, MAZE_W = 480, canvas width 680. MAZE_Y = 40, waterY = 360, mirror 360..680, canvas height 700.
Canvas 680x700. Fine.
Let's write the code now.
```js
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
// ---------- Configuration ----------
const COLS = 12, ROWS = 8;
const CELL = 40;
const MAZE_W = COLS * CELL; // 480
const MAZE_H = ROWS * CELL; // 320
const MAZE_X = 100;
const MAZE_Y = 40;
const WATER_Y = MAZE_Y + MAZE_H; // 360
const WALL_T = 6;
const PLAYER_R = 10; // half-size
const canvasW = 680, canvasH = 700;
```
Wait, MAZE_X + MAZE_W = 100 + 480 = 580, so canvas width 680 gives 100 on the right too. Symmetric.
Mirror bottom = WATER_Y + MAZE_H = 680. Canvas height 700 → 20px bottom padding. Good.
Now the maze grid.
```js
let grid; // grid[r][c] = { walls: {n,e,s,w} }
let player;
let exitPos;
let won = false;
let sparks = [];
```
Maze generation as described.
Now rendering the world canvas:
```js
const worldCanvas = document.createElement('canvas');
worldCanvas.width = MAZE_W;
worldCanvas.height = MAZE_H;
const wctx = worldCanvas.getContext('2d');
```
drawWorld() — draws walls, exit, player into worldCanvas at maze-local coords.
```js
function drawWorld() {
wctx.clearRect(0, 0, MAZE_W, MAZE_H);
// walls
wctx.strokeStyle = '#7fd8ff';
wctx.lineWidth = WALL_T;
wctx.lineCap = 'round';
wctx.shadowColor = '#3ab6ff';
wctx.shadowBlur = 8;
wctx.beginPath();
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const cell = grid[r][c];
const x = c * CELL, y = r * CELL;
if (cell.walls.n) { wctx.moveTo(x, y); wctx.lineTo(x + CELL, y); }
if (cell.walls.w) { wctx.moveTo(x, y); wctx.lineTo(x, y + CELL); }
if (r === ROWS - 1 && cell.walls.s) { wctx.moveTo(x, y + CELL); wctx.lineTo(x + CELL, y + CELL); }
if (c === COLS - 1 && cell.walls.e) { wctx.moveTo(x + CELL, y); wctx.lineTo(x + CELL, y + CELL); }
}
}
wctx.stroke();
...
}
```
Note: for north and west walls we draw for every cell; for south and east only on the border. That avoids double-drawing. Good.
Then exit and player.
Now the main render:
```js
function render() {
const t = performance.now() / 1000;
// --- Background ---
ctx.fillStyle = '#05060d';
ctx.fillRect(0, 0, canvasW, canvasH);
// --- Real maze area ---
drawRealArea(t);
// --- Water line ---
drawWaterLine(t);
// --- Mirror ---
drawMirror(t);
}
```
drawRealArea:
```js
function drawRealArea(t) {
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
ctx.clip();
// floor
const g = ctx.createLinearGradient(0, MAZE_Y, 0, MAZE_Y + MAZE_H);
g.addColorStop(0, '#0b1020');
g.addColorStop(1, '#111a2e');
ctx.fillStyle = g;
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
// faint cell dots
ctx.fillStyle = 'rgba(120,160,220,0.10)';
for (let r = 0; r < ROWS; r++)
for (let c = 0; c < COLS; c++) {
ctx.beginPath();
ctx.arc(MAZE_X + c*CELL + CELL/2, MAZE_Y + r*CELL + CELL/2, 1.5, 0, Math.PI*2);
ctx.fill();
}
// light around player
const px = MAZE_X + player.x, py = MAZE_Y + player.y;
const lg = ctx.createRadialGradient(px, py, 0, px, py, 110);
lg.addColorStop(0, 'rgba(120,200,255,0.16)');
lg.addColorStop(1, 'rgba(120,200,255,0)');
ctx.fillStyle = lg;
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
// exit portal
drawPortal(MAZE_X + exitPos.x, MAZE_Y + exitPos.y, t);
// sparks
...
// player
drawOrb(px, py, t);
ctx.restore();
// border
ctx.strokeStyle = 'rgba(120,180,255,0.25)';
ctx.lineWidth = 2;
ctx.strokeRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
}
```
Hmm wait, if the walls are invisible, the player might walk outside the maze? No, the outer boundary walls prevent that (all outer walls exist).
drawMirror:
```js
function drawMirror(t) {
const sliceH = 4;
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
ctx.clip();
// dark water background
ctx.fillStyle = '#04070f';
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
for (let y = 0; y < MAZE_H; y += sliceH) {
const destY = WATER_Y + (MAZE_H - y - sliceH);
// ripple: stronger near the bottom (deeper = more distortion)
const depth = (MAZE_H - y) / MAZE_H; // 0 at bottom of world (near water), 1 at top
const amp = 0.6 + 3.5 * depth;
const off = Math.sin(y * 0.05 + t * 1.8) * amp + Math.sin(y * 0.13 - t * 1.1) * amp * 0.4;
ctx.drawImage(worldCanvas, 0, y, MAZE_W, sliceH, MAZE_X + off, destY, MAZE_W, sliceH);
}
// blue tint
ctx.globalCompositeOperation = 'source-atop'; // hmm, clip already applied
...
}
```
Hmm, `source-atop` with the clip... Actually, the clip affects everything. Let's just draw a semi-transparent blue rect over the mirror area after drawing the slices. But that would also tint the black background. Since the background is black, tinting it blue-ish is fine.
Let's draw: `ctx.fillStyle = 'rgba(40,120,200,0.22)'; ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);` That washes everything blue. Good.
Then a vertical gradient to fade the deeper parts: from transparent at the water line to dark at the bottom.
```js
const fade = ctx.createLinearGradient(0, WATER_Y, 0, WATER_Y + MAZE_H);
fade.addColorStop(0, 'rgba(5,8,20,0)');
fade.addColorStop(1, 'rgba(5,8,20,0.85)');
ctx.fillStyle = fade;
ctx.fillRect(...);
```
Hmm, but that fades the far part of the reflection, which is where the top of the maze is reflected. That's fine aesthetically.
Actually, hmm — for gameplay, fading makes it harder to see the top of the maze. Let's make the fade subtle (0.5 max).
Then restore and draw the water line.
Water line: a glowing horizontal line at WATER_Y spanning the canvas, with animated highlights.
Let me also add: a subtle "reflection" of the water line? Nah.
Now, the player's reflection: since we draw the player into worldCanvas, it appears in the mirror automatically.
One issue: the player is drawn as a circle with a glow; when sliced into 4px strips with offsets, it'll look wavy. That's the desired effect.
Now let's handle the spark effect on wall collision.
When the player's movement is blocked, record a spark at the contact point with a lifetime. Actually simpler: when a move is blocked, compute the approximate contact point and add a spark.
```js
function tryMove(dx, dy) {
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / 2));
for (let i = 0; i < steps; i++) {
const sx = dx / steps, sy = dy / steps;
if (!collides(player.x + sx, player.y)) player.x += sx;
else if (Math.abs(sx) > 0.01) addSpark(player.x + Math.sign(sx) * PLAYER_R, player.y);
if (!collides(player.x, player.y + sy)) player.y += sy;
else if (Math.abs(sy) > 0.01) addSpark(player.x, player.y + Math.sign(sy) * PLAYER_R);
}
}
```
Hmm, addSpark would be called every frame while pushing into a wall. That's fine if we cap the number and make them short-lived, but it'd be a constant sparkle. Maybe throttle: only add a spark if the last spark was more than 100ms ago. Let's do that.
Actually, maybe a better feedback: when blocked, briefly reveal the wall segment that was hit in the real view (a flash that fades over ~400ms). That's very helpful feedback and still requires the mirror for planning. Let's do that — it's called "impact echo".
Let's implement `flashes` array with {r, c, dir, t}. Hmm, but determining which wall was hit requires knowing the collision.
Simpler: when blocked in the X direction, find the wall the player is touching. Let's just compute: after a blocked move, scan the cells around the player and find wall segments within a few px of the player's AABB. Push those as flashes.
Actually, let's simplify: on blocked move, add a small spark particle at the contact point and also a brief "reveal" of the nearest wall segment.
Hmm, let me just do the spark. It's simpler and looks good. And to avoid spam, throttle globally.
Actually, let me do a nicer thing: a "bump ripple" — when blocked, add a small circle at the contact point that expands and fades. This gives feedback about where the wall is.
OK, let's code it.
Let me reconsider: maybe simpler and more elegant — when the player bumps a wall, the wall segment glows briefly in the real view. To find the wall, I can check the 4 directions from the player's cell.
```js
function onBlocked(dirX, dirY) {
const c = Math.floor(player.x / CELL);
const r = Math.floor(player.y / CELL);
// find the wall in the direction of the push
}
```
Hmm, but the player might be between cells. Let's just do the expanding ripple at the contact point. Simple.
Let's finalize the code.
Also need: the win condition and a restart.
Also: a "New Maze" button and maybe a difficulty selector. Keep it minimal.
Let me write out the full code.
```html
Reflection Maze
```
Let me write the JS carefully.
```js
(() => {
'use strict';
// ===================== Constants =====================
const COLS = 12;
const ROWS = 8;
const CELL = 40;
const MAZE_W = COLS * CELL; // 480
const MAZE_H = ROWS * CELL; // 320
const MAZE_X = 100; // left offset of the maze inside the canvas
const MAZE_Y = 40; // top offset
const WATER_Y = MAZE_Y + MAZE_H; // 360 – the water/mirror line
const CANVAS_W = MAZE_X * 2 + MAZE_W; // 680
const CANVAS_H = WATER_Y + MAZE_H + 20; // 700
const WALL_T = 6;
const PLAYER_R = 10; // half size of the player's collision box
const SPEED = 145; // px / second
...
})();
```
Maze generation:
```js
function createGrid() {
const g = [];
for (let r = 0; r < ROWS; r++) {
g[r] = [];
for (let c = 0; c < COLS; c++) {
g[r][c] = { walls: { n: true, e: true, s: true, w: true }, visited: false };
}
}
// recursive backtracker
const stack = [];
let cur = g[0][0];
cur.visited = true;
let visited = 1;
const total = ROWS * COLS;
const OPP = { n: 's', s: 'n', e: 'w', w: 'e' };
while (visited < total) {
const r = cur.r ?? ...
}
}
```
I need to store r,c in the cell. Let's store them.
Actually, let me store the grid as `g[r][c]` and pass indices around.
```js
function createGrid() {
const g = [];
for (let r = 0; r < ROWS; r++) {
g[r] = [];
for (let c = 0; c < COLS; c++) {
g[r][c] = { walls: { n: true, e: true, s: true, w: true }, visited: false };
}
}
const OPP = { n: 's', s: 'n', e: 'w', w: 'e' };
const stack = [];
let cr = 0, cc = 0;
g[0][0].visited = true;
let visitedCount = 1;
const total = ROWS * COLS;
while (visitedCount < total) {
const nbrs = [];
if (cr > 0 && !g[cr-1][cc].visited) nbrs.push(['n', cr-1, cc]);
if (cr < ROWS-1 && !g[cr+1][cc].visited) nbrs.push(['s', cr+1, cc]);
if (cc > 0 && !g[cr][cc-1].visited) nbrs.push(['w', cr, cc-1]);
if (cc < COLS-1 && !g[cr][cc+1].visited) nbrs.push(['e', cr, cc+1]);
if (nbrs.length > 0) {
const [dir, nr, nc] = nbrs[(Math.random() * nbrs.length) | 0];
g[cr][cc].walls[dir] = false;
g[nr][nc].walls[OPP[dir]] = false;
stack.push([cr, cc]);
cr = nr; cc = nc;
g[cr][cc].visited = true;
visitedCount++;
} else {
const p = stack.pop();
cr = p[0]; cc = p[1];
}
}
return g;
}
```
Good. Also, add a few extra loops (remove some random walls) to make it less tree-like. Optional; a perfect maze is fine and more challenging. Actually, a perfect maze means there's exactly one path — good for a maze. Let's keep it perfect.
Hmm, but for a "reflection maze" where you can't see the walls, a perfect maze might be brutal. Actually no — the mirror shows everything, so it's fine. But to make it a bit more forgiving, let's add a few loops. Let's remove ~8% of the interior walls randomly. That creates multiple paths. Good.
Actually, with the mirror showing everything, a perfect maze is fine and more satisfying. But let's add a couple of loops anyway for variety. Hmm, I'll add a small number.
Let's keep it perfect for clarity of the "correct path" idea. Actually the task says "determine the correct path". A perfect maze has exactly one correct path. Let's keep it perfect. Hmm, but the player might wander a lot. It's fine.
OK, perfect maze.
Now, the player start at cell (0,0) center: (CELL/2, CELL/2) = (20, 20). Exit at cell (ROWS-1, COLS-1) center: ((COLS-0.5)*CELL, (ROWS-0.5)*CELL) = (460, 300).
Wait, but the player starts at the top-left of the maze, which in the reflection appears at the bottom of the mirror. And the exit at the bottom-right appears at the top-right of the mirror. Fine.
Hmm, maybe start the player at the bottom-left (near the water) so their reflection is near the water line and easy to see. Actually it doesn't matter much.
Let's start at (0,0) — top-left.
Now, let me write the render functions.
drawOrb(x, y, t) — draws the player as a glowing orb.
```js
function drawOrb(x, y, t) {
const pulse = 1 + Math.sin(t * 4) * 0.08;
const rr = PLAYER_R * 1.15 * pulse;
// outer glow
const g = ctx.createRadialGradient(x, y, 0, x, y, rr * 3.2);
g.addColorStop(0, 'rgba(160,240,255,0.55)');
g.addColorStop(0.4, 'rgba(90,190,255,0.18)');
g.addColorStop(1, 'rgba(60,140,255,0)');
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(x, y, rr * 3.2, 0, Math.PI * 2);
ctx.fill();
// core
ctx.fillStyle = '#eafcff';
ctx.beginPath();
ctx.arc(x, y, rr * 0.62, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = 'rgba(140,230,255,0.9)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x, y, rr, 0, Math.PI * 2);
ctx.stroke();
}
```
But drawOrb is used both in the main canvas (with MAZE_X/MAZE_Y offsets) and in the world canvas (no offset). So I'll pass a context.
Let me make helper functions take a ctx parameter.
```js
function drawOrb(g2d, x, y, t) { ... }
```
And drawPortal similarly.
Now, drawWorld uses wctx with local coords.
```js
function drawWorld(t) {
wctx.clearRect(0, 0, MAZE_W, MAZE_H);
// walls
...
drawPortal(wctx, exitPos.x, exitPos.y, t);
drawOrb(wctx, player.x, player.y, t);
}
```
Note: the world canvas is 480x320 and the glow might get clipped at the edges. It's fine.
Hmm, one issue: `createRadialGradient` with the shadow blur — the glow of the player might be clipped at the canvas edge. Not a big deal.
Now the main render.
Let me write it all out.
Also, add the "win" state: when the player reaches the exit, show a "YOU ESCAPED" overlay and stop movement.
Let me also add a subtle "distance to exit" or a timer. A timer adds challenge. Let's add a simple timer and a move counter.
Let me keep it: timer + wins counter. Eh, let's just do a timer.
Let me write the final code.
```js
// ============ Setup ============
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
canvas.width = CANVAS_W;
canvas.height = CANVAS_H;
const worldCanvas = document.createElement('canvas');
worldCanvas.width = MAZE_W;
worldCanvas.height = MAZE_H;
const wctx = worldCanvas.getContext('2d');
```
State:
```js
let grid, player, exitPos, won, startTime, elapsed, lastTime;
let bumps = []; // bump ripples in the real view
let lastBumpTime = 0;
```
Init:
```js
function newGame() {
grid = createGrid();
player = { x: CELL / 2, y: CELL / 2 };
exitPos = { x: (COLS - 0.5) * CELL, y: (ROWS - 0.5) * CELL };
won = false;
elapsed = 0;
bumps.length = 0;
keys = { up:false, down:false, left:false, right:false };
}
```
Wait — the player starting at cell (0,0) means they start at the entrance. And the exit at (ROWS-1, COLS-1).
Hmm, one more thought: should the exit be visible in the real view? Yes, it should be — the player needs to know where to go. It's visible in both the real view and the reflection.
Now the collision function:
```js
function collides(x, y) {
const half = PLAYER_R;
const minC = Math.floor((x - half) / CELL);
const maxC = Math.floor((x + half) / CELL);
const minR = Math.floor((y - half) / CELL);
const maxR = Math.floor((y + half) / CELL);
for (let r = minR; r <= maxR; r++) {
for (let c = minC; c <= maxC; c++) {
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return true;
const cell = grid[r][c];
const x0 = c * CELL, y0 = r * CELL;
const halfT = WALL_T / 2;
// North wall
if (cell.walls.n) {
if (aabb(x - half, y - half, half*2, half*2, x0 - halfT, y0 - halfT, CELL + WALL_T, WALL_T)) return true;
}
// West wall
if (cell.walls.w) {
if (aabb(x - half, y - half, half*2, half*2, x0 - halfT, y0 - halfT, WALL_T, CELL + WALL_T)) return true;
}
// South wall (only needed for last row, but check anyway — adjacent cell covers it)
// East wall (only needed for last column)
if (r === ROWS - 1 && cell.walls.s) {
if (aabb(..., x0 - halfT, y0 + CELL - halfT, CELL + WALL_T, WALL_T)) return true;
}
if (c === COLS - 1 && cell.walls.e) {
if (aabb(..., x0 + CELL - halfT, y0 - halfT, WALL_T, CELL + WALL_T)) return true;
}
}
}
return false;
}
```
Actually, the south wall of cell (r,c) is the north wall of cell (r+1,c), so checking north walls of all cells covers all interior horizontal walls. Similarly for east/west. But for the last row/column, we need to check the outer south/east walls. Since the player can't go outside anyway (the bounds check returns true), we might not need them... but the bounds check only triggers when the player's box crosses the grid boundary. If the player is in the last row and the south wall is at y = ROWS*CELL, the player's box would need to cross y = ROWS*CELL to trigger the bounds check. Actually the bounds check uses `Math.floor((y + half) / CELL)` which would be ROWS if y+half >= ROWS*CELL. So it does trigger. But it triggers only when the player's box crosses, meaning the player can get right up against the boundary. That's fine, same as a wall. So we don't strictly need to check the outer south/east walls. But for visual consistency, let's include them. Actually, simpler: just check north and west walls of all cells, plus the outer bounds. That covers everything.
Hmm, wait: north walls cover all horizontal walls except the bottom border. West walls cover all vertical walls except the right border. The bounds check covers the bottom and right borders.
But careful: the bounds check returns true if the player's box extends beyond the grid, which is exactly the border. Good.
So:
```js
function collides(x, y) {
const h = PLAYER_R;
if (x - h < 0 || x + h > MAZE_W || y - h < 0 || y + h > MAZE_H) return true;
...
}
```
Wait, but the maze's outer border walls are at x=0, x=MAZE_W, y=0, y=MAZE_H. The walls have thickness WALL_T, drawn centered on the line? Let's draw them centered on the boundary: the north wall of cell (0,0) is drawn from y = -WALL_T/2 to WALL_T/2. That would go outside the maze area. Let's instead draw walls inset: the wall occupies [y0 - WALL_T/2, y0 + WALL_T/2] and for the outer border, y0 = 0, so it occupies [-3, 3], which is half outside.
To avoid that, let's draw the walls centered but keep the maze area with some padding. Actually MAZE_Y = 40, so the top wall extends to y = 37 in canvas coords, which is fine visually.
But for collision, the boundary check `y - h < 0` prevents the player from reaching the top wall's outer half. That's fine — the player stops at y = h = 10, and the wall's inner edge is at y = 3. So the player stops 7px away from the wall's inner edge. Hmm, that leaves a visible gap.
Better: make the collision boundary at y = WALL_T/2 = 3. So `if (y - h < WALL_T/2) return true;` etc. Then the player can get up to y = 3 + 10 = 13, which is 3px from the wall center. Good.
Hmm, but actually the inner walls are at cell boundaries, and the north wall of cell (1,0) is at y = CELL = 40. The player in cell (0,0) can move up to y = 40 - 3 - 10 = 27 (bottom edge of player at 37, wall top at 37). Good.
Let's define `const EDGE = WALL_T / 2;` and use it for the boundary check.
Actually, to be consistent, let's make the collision boundary: the playable area is inset by EDGE on all sides.
```js
if (x - h < EDGE || x + h > MAZE_W - EDGE || y - h < EDGE || y + h > MAZE_H - EDGE) return true;
```
Good.
Hmm, but then the player's box is 20x20 and the corridor is 40 wide minus 6 for walls = 34 usable. The player has 7px of slack on each side. Fine.
Now, movement with sub-steps.
```js
function update(dt) {
if (won) return;
elapsed += dt;
let dx = 0, dy = 0;
if (keys.left) dx -= 1;
if (keys.right) dx += 1;
if (keys.up) dy -= 1;
if (keys.down) dy += 1;
if (dx === 0 && dy === 0) return;
const len = Math.hypot(dx, dy);
dx = dx / len * SPEED * dt;
dy = dy / len * SPEED * dt;
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / 1.5));
const sx = dx / steps, sy = dy / steps;
let bumpedX = false, bumpedY = false;
for (let i = 0; i < steps; i++) {
if (!collides(player.x + sx, player.y)) player.x += sx;
else bumpedX = true;
if (!collides(player.x, player.y + sy)) player.y += sy;
else bumpedY = true;
}
if (bumpedX || bumpedY) registerBump();
...
}
```
registerBump: throttled.
```js
function registerBump() {
const now = performance.now();
if (now - lastBumpTime < 120) return;
lastBumpTime = now;
bumps.push({ x: player.x, y: player.y, t: 0 });
}
```
Then draw the bumps as expanding rings in the real view.
Check win:
```js
if (Math.hypot(player.x - exitPos.x, player.y - exitPos.y) < CELL * 0.45) {
won = true;
}
```
Now the render.
Let me write the full render function.
```js
function render(now) {
const t = now / 1000;
ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
// --- deep space background ---
ctx.fillStyle = '#04060e';
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
// --- 1. The real maze (walls hidden!) ---
drawRealWorld(t);
// --- 2. The water / mirror line ---
drawWaterSurface(t);
// --- 3. The reflection ---
drawReflection(t);
// --- HUD ---
drawHUD(t);
if (won) drawWinOverlay(t);
}
```
drawRealWorld(t):
```js
function drawRealWorld(t) {
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
ctx.clip();
// floor
const floorGrad = ctx.createLinearGradient(0, MAZE_Y, 0, MAZE_Y + MAZE_H);
floorGrad.addColorStop(0, '#0a1224');
floorGrad.addColorStop(1, '#0f1c33');
ctx.fillStyle = floorGrad;
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
// subtle dot grid so the player can judge distances
ctx.fillStyle = 'rgba(120,170,240,0.12)';
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
ctx.beginPath();
ctx.arc(MAZE_X + c * CELL + CELL / 2, MAZE_Y + r * CELL + CELL / 2, 1.4, 0, Math.PI * 2);
ctx.fill();
}
}
// exit portal (visible – you know where you must go)
drawPortal(ctx, MAZE_X + exitPos.x, MAZE_Y + exitPos.y, t);
// bump ripples (feedback when you walk into an invisible wall)
for (const b of bumps) {
const p = b.t / 0.45;
if (p >= 1) continue;
ctx.strokeStyle = `rgba(120,220,255,${(1 - p) * 0.7})`;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(MAZE_X + b.x, MAZE_Y + b.y, 8 + p * 22, 0, Math.PI * 2);
ctx.stroke();
}
// player
drawOrb(ctx, MAZE_X + player.x, MAZE_Y + player.y, t);
ctx.restore();
// frame
ctx.strokeStyle = 'rgba(90,160,255,0.22)';
ctx.lineWidth = 2;
ctx.strokeRect(MAZE_X + 1, MAZE_Y + 1, MAZE_W - 2, MAZE_H - 2);
}
```
Hmm — `drawPortal` and `drawOrb` use canvas-absolute coords when called with ctx (main canvas) and maze-local coords with wctx. That's fine since I pass the coordinates.
drawReflection(t):
```js
function drawReflection(t) {
// Build the "true" maze image (walls + exit + player)
drawWorldImage(t);
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
ctx.clip();
// water base
ctx.fillStyle = '#03060d';
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
// draw the flipped image in horizontal slices with a sine ripple
const SLICE = 4;
for (let y = 0; y < MAZE_H; y += SLICE) {
const destY = WATER_Y + (MAZE_H - y - SLICE);
const depth = (MAZE_H - y) / MAZE_H; // 1 = far (top of maze), 0 = near water
const amp = 0.5 + 3.0 * depth;
const off = Math.sin(y * 0.045 + t * 1.7) * amp
+ Math.sin(y * 0.11 - t * 2.3) * amp * 0.45;
ctx.drawImage(
worldCanvas,
0, y, MAZE_W, SLICE,
MAZE_X + off, destY, MAZE_W, SLICE
);
}
// blue tint
ctx.fillStyle = 'rgba(30,110,190,0.20)';
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
// depth fade
const fade = ctx.createLinearGradient(0, WATER_Y, 0, WATER_Y + MAZE_H);
fade.addColorStop(0, 'rgba(4,8,18,0)');
fade.addColorStop(0.55, 'rgba(4,8,18,0.28)');
fade.addColorStop(1, 'rgba(4,8,18,0.72)');
ctx.fillStyle = fade;
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, MAZE_H);
ctx.restore();
// mirror frame
ctx.strokeStyle = 'rgba(90,160,255,0.18)';
ctx.lineWidth = 2;
ctx.strokeRect(MAZE_X + 1, WATER_Y + 1, MAZE_W - 2, MAZE_H - 2);
}
```
Wait, there's an issue with the `depth` variable. In the loop, `y` goes from 0 (top of the world canvas = top of the maze) to MAZE_H (bottom = nearest the water). The `depth` should be larger for the far parts (which are the top of the maze, y=0). So `depth = (MAZE_H - y) / MAZE_H` gives 1 at y=0 (top of maze) and 0 at y=MAZE_H. Hmm, but the ripple should be strongest near the water (y large) since the reflection is distorted... Actually, in a real reflection, the distortion is often stronger further from the water. Either way, it's aesthetic. Let's keep it.
Hmm, actually wait: the destination for y=0 is destY = WATER_Y + MAZE_H - SLICE, which is the bottom of the mirror. So the top of the maze appears at the bottom of the mirror, far from the water. And the distortion amp is highest there (depth=1). Good — the farther from the water, the more distortion. Makes sense.
Now, the ripple offset shifts the image horizontally. Since we're drawing full-width slices with an x-offset, the edges might show gaps. The clip prevents overflow, but there could be a gap at the left/right edges. With amp up to ~3.5, and the maze drawn at MAZE_X + off, the slice spans [MAZE_X + off, MAZE_X + off + MAZE_W]. If off > 0, there's a gap at the left. To fix, draw the slice slightly wider or just accept it (the mirror is clipped to MAZE_X..MAZE_X+MAZE_W, and the water base is dark, so a small dark edge appears). It's a subtle wavy edge, which actually looks fine for water. OK.
Actually, to be safe, let's draw each slice with a bit of overdraw: source x from -8 to MAZE_W+16... but the source canvas doesn't have that. Alternative: draw the slice, then also fill the edges. Meh. The wave effect at the edges looks intentional. Let's keep it.
drawWaterSurface(t):
```js
function drawWaterSurface(t) {
// glow above the line
const g = ctx.createLinearGradient(0, WATER_Y - 26, 0, WATER_Y + 10);
g.addColorStop(0, 'rgba(80,190,255,0)');
g.addColorStop(0.7, 'rgba(80,190,255,0.16)');
g.addColorStop(1, 'rgba(160,230,255,0.05)');
ctx.fillStyle = g;
ctx.fillRect(0, WATER_Y - 26, CANVAS_W, 36);
// the line itself with a shimmering highlight
ctx.save();
ctx.strokeStyle = 'rgba(150,225,255,0.85)';
ctx.lineWidth = 2;
ctx.shadowColor = 'rgba(90,200,255,0.9)';
ctx.shadowBlur = 14;
ctx.beginPath();
for (let x = 0; x <= CANVAS_W; x += 6) {
const y = WATER_Y + Math.sin(x * 0.02 + t * 1.5) * 1.2;
x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.stroke();
ctx.restore();
}
```
Hmm, the water line spans the full canvas width, but the maze is only from MAZE_X to MAZE_X+MAZE_W. The reflection is clipped to the maze area. The water line spanning the full width looks like a lake surface. That's fine, maybe even better.
Actually, let's make the water line only span the maze width plus some margin. Let's span the full canvas — it looks like a horizon. Fine.
Hmm, but the reflection region is only within the maze x-range. Outside that, it's just dark. Let's add a subtle dark "water" fill for the full width below the water line, so it reads as a lake.
```js
// dark water beyond the maze area
ctx.fillStyle = '#03060d';
ctx.fillRect(0, WATER_Y, CANVAS_W, CANVAS_H - WATER_Y);
```
But that would cover the reflection... no, we draw the reflection after. Order: background → real world → water base → reflection → water line. Hmm, but the water line should be drawn before the reflection? No — the reflection is below the line, and the line is at the top of the reflection. Drawing the line after is fine.
Let me reorder:
1. background
2. real world (maze)
3. dark water fill for the whole bottom area
4. reflection (clipped to the maze x-range)
5. water surface line + glow
6. HUD
OK.
Actually the glow above the line would be drawn over the real maze area. It's a subtle glow near the bottom of the maze. That's fine, looks nice.
Now, drawHUD: show the timer and a hint text.
Let's draw text labels:
- Above the maze: "THE MAZE — walls are invisible"
- Below the maze (in the mirror): "THE REFLECTION — everything you cannot see"
Let's put these as HTML labels instead, cleaner. Hmm, but positioning HTML labels to match the canvas regions requires layout work. Let's just draw them on the canvas.
At the top of the canvas (y ~ 20): text "THE MAZE — walls are invisible".
At y = WATER_Y + 14... that's inside the mirror. Hmm. Let's put it at the bottom of the canvas: y = CANVAS_H - 8. Text "THE REFLECTION — the true maze, mirrored".
Hmm, CANVAS_H = 700, mirror bottom = 680. So y=690 for the label. OK.
And the top label at y=24.
Also a timer in the top-right corner.
Let me also add "WASD / Arrows to move" somewhere. Maybe in the HTML below the canvas.
Now, the win overlay: a translucent dark layer over the maze area with "ESCAPED!" text and the time. Plus the button.
Let me also handle the "New Maze" button.
Let me now also consider: the player might find it hard to know their position in the reflection. Let's add a subtle vertical "guide line" connecting the player to their reflection — a faint dotted line from the player down to the water and continuing to the reflection. Actually, since the reflection is directly below (same x), a vertical line at the player's x would help. Let's draw a very faint vertical line from the player down to their reflection. That's a nice touch and physically meaningful (a light beam).
Hmm, in a real reflection, the reflection of the player at height h is at the same x. So yes, a vertical line connects them. Let's draw a faint vertical dashed line.
But wait — the player is on the ground plane (the maze is a top-down view), not standing above it. So the "reflection" concept is a bit abstract. Whatever — it's a game.
Actually, for a top-down maze, a "reflection" in water below makes sense if we think of the maze as drawn on a surface with water below... it's abstract. Fine, it's a game aesthetic.
Let's draw the guide line. Actually, maybe it's more confusing than helpful. Let's add it as a very faint line. Hmm, I'll add it — it helps players locate themselves.
Hmm, actually there's a subtlety: the player's reflection is at the mirrored position. Since the player is at maze-local (px, py), their reflection is at local (px, MAZE_H - py). In canvas coords: (MAZE_X + px, WATER_Y + MAZE_H - py). And the player is at (MAZE_X + px, MAZE_Y + py). Note MAZE_Y + py and WATER_Y + MAZE_H - py = MAZE_Y + MAZE_H + MAZE_H - py. Since WATER_Y = MAZE_Y + MAZE_H. So the reflection y = MAZE_Y + 2*MAZE_H - py. And the player y = MAZE_Y + py. These are symmetric about MAZE_Y + MAZE_H = WATER_Y. Yes! Correct.
So the guide line is vertical at x = MAZE_X + px.
Let's draw it from the player down to the reflection, with a dashed faint style.
OK, now let's write everything out properly.
One more: the exit portal. Draw as a swirling green/cyan circle.
```js
function drawPortal(g2d, x, y, t) {
const pulse = 1 + Math.sin(t * 3) * 0.12;
const R = CELL * 0.30 * pulse;
const grad = g2d.createRadialGradient(x, y, 0, x, y, R * 2.6);
grad.addColorStop(0, 'rgba(120,255,210,0.95)');
grad.addColorStop(0.35, 'rgba(60,220,180,0.35)');
grad.addColorStop(1, 'rgba(20,120,110,0)');
g2d.fillStyle = grad;
g2d.beginPath();
g2d.arc(x, y, R * 2.6, 0, Math.PI * 2);
g2d.fill();
g2d.strokeStyle = 'rgba(150,255,220,0.9)';
g2d.lineWidth = 2;
for (let i = 0; i < 3; i++) {
const rr = R * (0.5 + i * 0.35);
const a = t * (1.2 + i * 0.5) * (i % 2 ? -1 : 1);
g2d.beginPath();
g2d.arc(x, y, rr, a, a + Math.PI * 1.4);
g2d.stroke();
}
}
```
Nice.
Now let me think about the world canvas: when drawing the portal and orb into it, the glow may be clipped. The exit is at (460, 300) in a 480x320 canvas, with R*2.6 ≈ 31. 300 + 31 = 331 > 320. So it gets clipped. Minor. Let's reduce the glow radius or accept it. Accept it.
Hmm, actually it might create a visible hard edge in the reflection. Let's pad the world canvas: make it MAZE_W + 2*PAD by MAZE_H + 2*PAD with PAD = 40, and draw with a translate(PAD, PAD). Then when drawing slices, adjust the source coords.
That complicates the slicing. Alternative: just accept the clipping, or reduce the portal's glow in the world canvas.
Let's just accept it. Actually, let me reduce the glow radius for the portal to R*2.0 and for the orb similar. The clipping at the edges will be minor.
Hmm, actually the exit is at cell (7, 11) center = (11.5*40, 7.5*40) = (460, 300). MAZE_H = 320. The portal's outer glow radius R*2.6 where R = 12 → 31.2. So it extends to y = 331, clipped at 320. There will be a visible cut. Let's reduce the outer glow to R*1.8 = 21.6, extending to 321.6. Still slightly clipped. Use R*1.6 = 19.2 → 319.2. OK, fits.
Hmm, but then the glow is small. Alternatively, move the exit to a different cell. Let's put the exit at (ROWS-1, COLS-1) but that's the corner. The glow extends beyond.
You know what, let's just add padding to the world canvas. It's not that hard.
PAD = 32. worldCanvas: (MAZE_W + 2*PAD) x (MAZE_H + 2*PAD) = 544 x 384.
Draw everything with translate(PAD, PAD).
Slicing: for source y in [-PAD, MAZE_H + PAD), draw at destY. Let's define the reflection region to include the padding too. So the mirror region is from WATER_Y - PAD to WATER_Y + MAZE_H + PAD? Hmm, that would put part of the reflection above the water line. Not good.
Alternative: clip the source to [0, MAZE_H) but the world canvas has extra content. So for y in [0, MAZE_H), source y in world canvas is y + PAD.
```js
ctx.drawImage(worldCanvas, 0, y + PAD, W, SLICE, destX, destY, W, SLICE);
```
Where W = MAZE_W (only the maze's x-range). But then the glow at the left/right edges is clipped again. Hmm, but the horizontal clipping at the mirror's left/right edge is natural (the mirror has a frame). Actually the glow would be cut at the mirror's edge, which is fine visually.
Hmm, but actually the exit at the bottom-right of the maze: in the reflection, it appears at the top-right of the mirror. Its glow extends to the right beyond the mirror edge → clipped. Fine.
OK, let's use the padding approach for vertical only. Actually, let's just do the whole thing with padding. Let's keep it simple: worldCanvas is (MAZE_W + 2*PAD) x (MAZE_H + 2*PAD), and we draw slices from source y+PAD for y in [0, MAZE_H). The horizontal source range is PAD to PAD + MAZE_W.
```js
ctx.drawImage(worldCanvas, PAD, y + PAD, MAZE_W, SLICE, MAZE_X + off, destY, MAZE_W, SLICE);
```
Good. The padding content outside the slice range is just not drawn. Fine.
Actually, hmm, do I even need horizontal padding then? No. But it doesn't hurt.
Let's set PAD = 30. worldCanvas = 540 x 380.
OK.
Now let me write the final code.
Actually, one concern: drawing 80 slices per frame with drawImage from a canvas that's redrawn each frame. That's fine performance-wise.
MAZE_H = 320, SLICE = 4 → 80 drawImage calls. Fine.
Let me write it.
Also, I should handle `requestAnimationFrame` with a delta time.
```js
let lastTs = 0;
function loop(ts) {
const dt = Math.min(0.05, (ts - lastTs) / 1000 || 0);
lastTs = ts;
update(dt);
render(ts);
requestAnimationFrame(loop);
}
```
And update bumps: `bumps.forEach(b => b.t += dt); bumps = bumps.filter(b => b.t < 0.45);`
Let me write the complete code now.
One more: I want the reflection to be clearly a "reflection" — maybe add a slight vertical squash? No, keep it 1:1.
Also, the water line at WATER_Y = 360. The maze's bottom wall is at y = 360 (maze-local 320 → canvas 40+320 = 360). So the bottom wall is exactly at the water line. Hmm, that means the bottom wall would be half in the water. Let's shift the maze up a bit or move the water line down.
Let's set WATER_Y = MAZE_Y + MAZE_H + 6 = 366. Then the reflection region is 366 to 686, and the canvas height should be 706. Hmm.
Actually, the reflection mapping: reflected y = 2*WATER_Y - y_local_canvas. Let me redo with the offset.
Let me define the reflection transform cleanly:
- A point at canvas y = Y (in the real area) reflects to canvas y' = 2*WATER_Y - Y.
- The maze's bottom edge is at Y = MAZE_Y + MAZE_H = 360. Its reflection is at y' = 2*366 - 360 = 372.
- The maze's top edge is at Y = MAZE_Y = 40. Its reflection is at y' = 732 - 40 = 692.
So the mirror region spans 372 to 692. Canvas height 710.
Hmm, that's getting tall. Let's just set WATER_Y = 360 (the maze bottom edge) and accept that the bottom wall straddles the water line. Actually, that looks natural — the maze sits on the edge of the water.
Hmm, but the bottom wall is drawn centered on y=360, so it spans 357..363. Half of it would be reflected. The reflection of the bottom wall would be at 357..363 too. So it'd overlap. Visually it's fine — it looks like the maze is sitting on the water's edge.
Actually, it's cleaner if the water line is a bit below the maze bottom. Let's set WATER_Y = 368 (8px below the maze bottom edge).
Then:
- Maze bottom (Y=360) reflects to 2*368 - 360 = 376.
- Maze top (Y=40) reflects to 736 - 40 = 696.
Mirror region: 376 to 696. Height = 320. Canvas height = 716.
Hmm, 716 tall. That's a lot but OK for a desktop. Let's reduce the cell size to 36.
CELL = 36, COLS = 12 → MAZE_W = 432. ROWS = 8 → MAZE_H = 288.
MAZE_X = (CANVAS_W - 432)/2. Let's set CANVAS_W = 600 → MAZE_X = 84.
MAZE_Y = 36.
Maze bottom = 36 + 288 = 324.
WATER_Y = 332.
Mirror: maze bottom reflection = 2*332 - 324 = 340. Maze top reflection = 664 - 36 = 628.
Mirror region 340..628.
Canvas height = 628 + 30 = 658. Let's say 660.
Hmm, the mirror region is 340..628 but the reflection content is 340..628. And the canvas is 660 tall, so there's 32px of empty water at the bottom. That's fine, looks like the lake continues.
Wait, let me recompute: reflection of maze top (Y=36) → 2*332 - 36 = 628. Yes. And the canvas is 660, so the water extends from 628 to 660 below the reflection. Fine.
Let's use CELL = 36, CANVAS_W = 600, CANVAS_H = 660.
Player radius: PLAYER_R = 9. Corridor is 36 wide, walls 6 thick → usable 30. Player box 18 wide → 6px slack each side. Fine.
Speed: 130 px/s.
Hmm, CELL=36 with a 6px wall — the wall thickness relative to the cell is a bit chunky but fine.
Let's go with:
- COLS = 12, ROWS = 8, CELL = 36
- MAZE_W = 432, MAZE_H = 288
- MAZE_X = 84, MAZE_Y = 36
- MAZE bottom = 324
- WATER_Y = 334
- reflection top (of maze bottom) = 2*334 - 324 = 344
- reflection bottom (of maze top) = 668 - 36 = 632
- CANVAS_W = 600, CANVAS_H = 660
Mirror clip region: y from WATER_Y (334) to WATER_Y + MAZE_H (334+288 = 622)? Hmm, that doesn't match.
Let me reconsider. The mirror region in canvas coordinates: the reflection of the maze occupies y from 344 to 632. Let's just clip the mirror drawing to y in [WATER_Y, WATER_Y + MAZE_H + something].
Actually, let's simplify by defining the reflection mapping directly:
- For a maze-local point (mx, my) with my in [0, MAZE_H], its canvas position in the real view is (MAZE_X + mx, MAZE_Y + my).
- Its reflection canvas position is (MAZE_X + mx, 2*WATER_Y - (MAZE_Y + my)).
With WATER_Y = 334, MAZE_Y = 36: reflection y = 668 - 36 - my = 632 - my.
- my = 0 → 632
- my = MAZE_H = 288 → 344.
So the reflection spans 344 to 632. The water line is at 334. There's a 10px gap between the water line and the top of the reflection (344). That's the "shore". Hmm, that's a bit odd. Let's set WATER_Y = 324 (exactly at the maze bottom edge). Then the reflection of my=288 is 648 - 324 = 324... wait: 2*324 - (36+288) = 648 - 324 = 324. So the maze's bottom edge reflects to the water line exactly. And my=0 → 648 - 36 = 612.
So the reflection spans 324 to 612. The water line is at 324.
But then the maze's bottom wall (centered at y=324) is half above and half below the water line. Hmm. Visually the bottom wall would be drawn over the water line. Let's just draw the water line and not worry.
Actually, let's shift the maze up by 8px: MAZE_Y = 28. Then the maze bottom edge is at 28 + 288 = 316. WATER_Y = 324 (8px below). Reflection: 2*324 - (28 + my) = 648 - 28 - my = 620 - my. my=288 → 332; my=0 → 620. So the reflection spans 332 to 620. The water line is at 324, and the reflection starts at 332 — an 8px gap. That gap is the "reflection of the 8px gap between the maze and the water". Correct physics! Nice.
Canvas height = 620 + 30 = 650.
OK: MAZE_Y = 28, WATER_Y = 324, reflection spans 332..620, CANVAS_H = 650.
Top area: y 0..28 for the title text. A bit tight. Let's make MAZE_Y = 44 and adjust.
MAZE_Y = 44, maze bottom = 44 + 288 = 332. WATER_Y = 340 (8px gap). Reflection: 2*340 - (44 + my) = 680 - 44 - my = 636 - my. my=288 → 348, my=0 → 636.
Reflection spans 348..636. Canvas height = 636 + 30 = 666. Let's use 670.
Title text at y=24. Good.
So:
- CANVAS_W = 600, CANVAS_H = 670
- MAZE_X = 84, MAZE_Y = 44
- MAZE_W = 432, MAZE_H = 288
- WATER_Y = 340
Mirror clip region: x from MAZE_X to MAZE_X + MAZE_W, y from WATER_Y to CANVAS_H (or up to 650).
Reflection drawing: for maze-local y in [0, MAZE_H), the destination y is 636 - y - SLICE... let me derive:
The real canvas y = MAZE_Y + my. The reflection canvas y = 2*WATER_Y - (MAZE_Y + my) = 680 - 44 - my = 636 - my.
For a slice from my to my+SLICE, the destination top y = 636 - (my + SLICE) = 636 - my - SLICE. And the height is SLICE. So the destination spans [636-my-SLICE, 636-my]. Correct.
So:
```js
const destY = 636 - my - SLICE;
```
Equivalently `2*WATER_Y - MAZE_Y - my - SLICE` = `REFLECT_BASE - my - SLICE` where REFLECT_BASE = 2*WATER_Y - MAZE_Y = 636.
Let me define `const REFLECT_BASE = 2 * WATER_Y - MAZE_Y;`
Check: my=288-SLICE → destY = 636 - 288 = 348. ✓ (top of the reflection, just below the water line).
my=0 → destY = 636 - SLICE = 632. ✓
Great.
So the mirror content region is y from 348 to 636. Clip to [WATER_Y, CANVAS_H] = [340, 670]. Good.
Now let me write it all.
Let me double check the maze-local to canvas conversion in the mirror for x: the reflection x is the same as the real x: MAZE_X + mx. Good.
Now the code.
I'll write it now in full.
```html
Reflection Maze — find the path in the mirror
Reflection Maze
The walls of the maze are invisible. Only the mirror tells the truth.
WASD or ↑←↓→ to move • reach the green portal
```
Now the script.
Let me write it carefully.
```js
(() => {
'use strict';
/* =========================================================
* 1. CONFIGURATION
* ========================================================= */
const COLS = 12;
const ROWS = 8;
const CELL = 36;
const MAZE_W = COLS * CELL; // 432
const MAZE_H = ROWS * CELL; // 288
const MAZE_X = 84;
const MAZE_Y = 44;
const WATER_Y = 340; // the mirror line
const CANVAS_W = 600;
const CANVAS_H = 670;
const WALL_T = 6;
const EDGE = WALL_T / 2;
const PLAYER_R = 9; // half-size of the player's collision box
const SPEED = 132; // pixels per second
const REFLECT_BASE = 2 * WATER_Y - MAZE_Y; // 636
// Offscreen canvas that holds the "true" maze (walls + goal + player).
const PAD = 30;
const worldCanvas = document.createElement('canvas');
worldCanvas.width = MAZE_W + PAD * 2;
worldCanvas.height = MAZE_H + PAD * 2;
const wctx = worldCanvas.getContext('2d');
const canvas = document.getElementById('game');
canvas.width = CANVAS_W;
canvas.height = CANVAS_H;
const ctx = canvas.getContext('2d');
/* =========================================================
* 2. STATE
* ========================================================= */
let grid = null;
let player = { x: 0, y: 0 };
let goal = { x: 0, y: 0 };
let won = false;
let elapsed = 0;
let bumps = []; // little ripples shown when the player hits an invisible wall
let lastBump = 0;
const keys = { up: false, down: false, left: false, right: false };
/* =========================================================
* 3. MAZE GENERATION (recursive backtracker)
* ========================================================= */
const DIRS = [
{ key: 'n', dr: -1, dc: 0, opp: 's' },
{ key: 's', dr: 1, dc: 0, opp: 'n' },
{ key: 'w', dr: 0, dc: -1, opp: 'e' },
{ key: 'e', dr: 0, dc: 1, opp: 'w' },
];
function createGrid() {
const g = [];
for (let r = 0; r < ROWS; r++) {
const row = [];
for (let c = 0; c < COLS; c++) {
row.push({ n: true, e: true, s: true, w: true, visited: false });
}
g.push(row);
}
const stack = [];
let cr = 0, cc = 0;
g[cr][cc].visited = true;
let visitedCount = 1;
const total = ROWS * COLS;
while (visitedCount < total) {
// gather unvisited neighbours
const options = [];
for (const d of DIRS) {
const nr = cr + d.dr, nc = cc + d.dc;
if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && !g[nr][nc].visited) {
options.push({ d, nr, nc });
}
}
if (options.length) {
const pick = options[(Math.random() * options.length) | 0];
g[cr][cc][pick.d.key] = false; // knock the wall down…
g[pick.nr][pick.nc][pick.d.opp] = false; // …on both sides
stack.push([cr, cc]);
cr = pick.nr; cc = pick.nc;
g[cr][cc].visited = true;
visitedCount++;
} else {
const prev = stack.pop();
cr = prev[0]; cc = prev[1];
}
}
// clean the visited flags
for (let r = 0; r < ROWS; r++)
for (let c = 0; c < COLS; c++)
delete g[r][c].visited;
return g;
}
/* =========================================================
* 4. COLLISION
* ========================================================= */
function aabb(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by;
}
/**
* Returns true when a player-sized box centred on (x, y)
* (maze-local coordinates) intersects any wall.
*/
function collides(x, y) {
const h = PLAYER_R;
// outside the maze? -> wall
if (x - h < EDGE || x + h > MAZE_W - EDGE ||
y - h < EDGE || y + h > MAZE_H - EDGE) return true;
const minC = Math.floor((x - h) / CELL);
const maxC = Math.floor((x + h) / CELL);
const minR = Math.floor((y - h) / CELL);
const maxR = Math.floor((y + h) / CELL);
for (let r = minR; r <= maxR; r++) {
for (let c = minC; c <= maxC; c++) {
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) continue;
const cell = grid[r][c];
const x0 = c * CELL;
const y0 = r * CELL;
// North wall of this cell == horizontal wall on top of it
if (cell.n && aabb(x - h, y - h, h * 2, h * 2,
x0 - EDGE, y0 - EDGE, CELL + WALL_T, WALL_T)) return true;
// West wall
if (cell.w && aabb(x - h, y - h, h * 2, h * 2,
x0 - EDGE, y0 - EDGE, WALL_T, CELL + WALL_T)) return true;
// South wall only needed on the last row (otherwise it is the north wall of the cell below)
if (r === ROWS - 1 && cell.s &&
aabb(x - h, y - h, h * 2, h * 2,
x0 - EDGE, y0 + CELL - EDGE, CELL + WALL_T, WALL_T)) return true;
// East wall only needed on the last column
if (c === COLS - 1 && cell.e &&
aabb(x - h, y - h, h * 2, h * 2,
x0 + CELL - EDGE, y0 - EDGE, WALL_T, CELL + WALL_T)) return true;
}
}
return false;
}
...
})();
```
Wait, there's a subtle bug: the outer boundary check `x - h < EDGE` handles the outer walls. But the south wall of the last row: `y0 + CELL - EDGE` where y0 = (ROWS-1)*CELL, so y0 + CELL = MAZE_H. The wall rect is [MAZE_H - EDGE, MAZE_H - EDGE + WALL_T] = [MAZE_H - 3, MAZE_H + 3]. And the player is limited by the boundary check to y + h <= MAZE_H - EDGE = MAZE_H - 3. So the player's box bottom is at most MAZE_H - 3, and the wall starts at MAZE_H - 3. AABB overlap: `ay + ah > by` → (MAZE_H - 3) > (MAZE_H - 3)? No, it's false (not strictly greater). So no collision. Good, no double-blocking. Actually it's redundant but harmless.
Hmm, but wait — for the north wall of cell (0,0), y0 = 0, the wall rect is [-3, 3]. The player's box top is at least EDGE = 3. AABB: `ay < by + bh` → 3 < 3? False. Good.
OK, so the boundary check handles the outer walls, and the interior walls are handled by the north/west checks. The south/east checks for the last row/col are redundant. I'll remove them for simplicity. Actually, let me keep them for robustness — no, they're redundant and add confusion. Let me remove them.
Actually wait, I need to double check: are ALL interior walls covered by "north wall of each cell" + "west wall of each cell"?
- Horizontal interior walls: the wall between cell (r,c) and (r+1,c). This is cell (r+1,c)'s north wall. ✓ Covered.
- Vertical interior walls: the wall between cell (r,c) and (r,c+1). This is cell (r,c+1)'s west wall. ✓ Covered.
- Top border: cell (0,c)'s north wall. But the boundary check covers it. Also it's checked. Both fine.
- Left border: cell (r,0)'s west wall. Same.
- Bottom border: cell (ROWS-1,c)'s south wall. NOT covered by north/west checks. But the boundary check covers it. ✓
- Right border: cell (r,COLS-1)'s east wall. NOT covered. Boundary check covers it. ✓
Good. So I can just do the boundary check plus north/west checks.
Now let's write the update.
```js
function update(dt) {
// fade out the bump ripples
for (const b of bumps) b.t += dt;
if (bumps.length) bumps = bumps.filter(b => b.t < 0.5);
if (won) return;
elapsed += dt;
let dx = 0, dy = 0;
if (keys.left) dx -= 1;
if (keys.right) dx += 1;
if (keys.up) dy -= 1;
if (keys.down) dy += 1;
if (dx || dy) {
const len = Math.hypot(dx, dy);
dx = dx / len * SPEED * dt;
dy = dy / len * SPEED * dt;
// sub-step so we never tunnel through a wall
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / 1.5));
const sx = dx / steps, sy = dy / steps;
let blocked = false;
for (let i = 0; i < steps; i++) {
if (!collides(player.x + sx, player.y)) player.x += sx;
else blocked = true;
if (!collides(player.x, player.y + sy)) player.y += sy;
else blocked = true;
}
if (blocked) addBump();
}
// reached the portal?
if (Math.hypot(player.x - goal.x, player.y - goal.y) < CELL * 0.42) {
won = true;
}
}
function addBump() {
const now = performance.now();
if (now - lastBump < 110) return;
lastBump = now;
bumps.push({ x: player.x, y: player.y, t: 0 });
}
```
Now the drawing helpers.
```js
function drawOrb(g2d, x, y, t) {
const pulse = 1 + Math.sin(t * 4.2) * 0.09;
const r = PLAYER_R * 1.05 * pulse;
const glow = g2d.createRadialGradient(x, y, 0, x, y, r * 3.4);
glow.addColorStop(0, 'rgba(190,245,255,0.60)');
glow.addColorStop(0.35,'rgba(90,195,255,0.22)');
glow.addColorStop(1, 'rgba(50,130,255,0)');
g2d.fillStyle = glow;
g2d.beginPath();
g2d.arc(x, y, r * 3.4, 0, Math.PI * 2);
g2d.fill();
g2d.fillStyle = '#f2feff';
g2d.beginPath();
g2d.arc(x, y, r * 0.62, 0, Math.PI * 2);
g2d.fill();
g2d.strokeStyle = 'rgba(160,235,255,0.95)';
g2d.lineWidth = 1.8;
g2d.beginPath();
g2d.arc(x, y, r, 0, Math.PI * 2);
g2d.stroke();
}
```
Hmm, `r * 3.4` with r ≈ 9.45 → 32. The world canvas has PAD=30, so it just fits. Good.
```js
function drawPortal(g2d, x, y, t) {
const pulse = 1 + Math.sin(t * 3.1) * 0.12;
const R = CELL * 0.26 * pulse;
const glow = g2d.createRadialGradient(x, y, 0, x, y, R * 3.2);
glow.addColorStop(0, 'rgba(150,255,215,0.85)');
glow.addColorStop(0.35,'rgba(50,225,175,0.30)');
glow.addColorStop(1, 'rgba(10,120,100,0)');
g2d.fillStyle = glow;
g2d.beginPath();
g2d.arc(x, y, R * 3.2, 0, Math.PI * 2);
g2d.fill();
g2d.lineWidth = 2;
for (let i = 0; i < 3; i++) {
const rr = R * (0.45 + i * 0.42);
const a = t * (1.1 + i * 0.55) * (i % 2 ? -1 : 1);
g2d.strokeStyle = `rgba(150,255,220,${0.85 - i * 0.2})`;
g2d.beginPath();
g2d.arc(x, y, rr, a, a + Math.PI * 1.45);
g2d.stroke();
}
g2d.fillStyle = 'rgba(220,255,245,0.95)';
g2d.beginPath();
g2d.arc(x, y, R * 0.35, 0, Math.PI * 2);
g2d.fill();
}
```
R = 36*0.26 = 9.36, R*3.2 = 30. Fits in the PAD.
Now drawWorldImage:
```js
function drawWorldImage(t) {
wctx.clearRect(0, 0, worldCanvas.width, worldCanvas.height);
wctx.save();
wctx.translate(PAD, PAD);
// ---- walls (the "truth" that is hidden in the real world) ----
wctx.lineCap = 'round';
wctx.lineWidth = WALL_T;
wctx.strokeStyle = '#7fd8ff';
wctx.shadowColor = 'rgba(70,190,255,0.9)';
wctx.shadowBlur = 10;
wctx.beginPath();
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const cell = grid[r][c];
const x = c * CELL;
const y = r * CELL;
if (cell.n) { wctx.moveTo(x, y); wctx.lineTo(x + CELL, y); }
if (cell.w) { wctx.moveTo(x, y); wctx.lineTo(x, y + CELL); }
if (r === ROWS - 1 && cell.s) { wctx.moveTo(x, y + CELL); wctx.lineTo(x + CELL, y + CELL); }
if (c === COLS - 1 && cell.e) { wctx.moveTo(x + CELL, y); wctx.lineTo(x + CELL, y + CELL); }
}
}
wctx.stroke();
// a second, thinner pass for a brighter core
wctx.shadowBlur = 0;
wctx.lineWidth = 2;
wctx.strokeStyle = 'rgba(215,245,255,0.95)';
wctx.stroke(); // re-strokes the same path
// ---- goal ----
drawPortal(wctx, goal.x, goal.y, t);
// ---- player ----
drawOrb(wctx, player.x, player.y, t);
wctx.restore();
}
```
Hmm, `wctx.stroke()` re-strokes the current path — yes, the path is still current after the first stroke. Good.
Now the reflection:
```js
function drawReflection(t) {
drawWorldImage(t);
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, WATER_Y, MAZE_W, CANVAS_H - WATER_Y);
ctx.clip();
// dark water
ctx.fillStyle = '#03060d';
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, CANVAS_H - WATER_Y);
// The image is drawn in thin horizontal slices.
// Each slice is shifted sideways by a sine wave -> shimmering water.
const SLICE = 4;
for (let my = 0; my < MAZE_H; my += SLICE) {
const destY = REFLECT_BASE - my - SLICE;
const depth = (MAZE_H - my) / MAZE_H; // 1 = far from the water, 0 = at the water
const amp = 0.6 + 3.2 * depth;
const off = Math.sin(my * 0.05 + t * 1.9) * amp
+ Math.sin(my * 0.13 - t * 2.6) * amp * 0.45;
ctx.drawImage(
worldCanvas,
PAD, my + PAD, MAZE_W, SLICE, // source (the true maze)
MAZE_X + off, destY, MAZE_W, SLICE // destination (mirrored & rippled)
);
}
// cold water tint
ctx.fillStyle = 'rgba(28,110,190,0.22)';
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, CANVAS_H - WATER_Y);
// fade with depth
const fade = ctx.createLinearGradient(0, WATER_Y, 0, REFLECT_BASE);
fade.addColorStop(0, 'rgba(3,6,14,0)');
fade.addColorStop(0.55, 'rgba(3,6,14,0.25)');
fade.addColorStop(1, 'rgba(3,6,14,0.80)');
ctx.fillStyle = fade;
ctx.fillRect(MAZE_X, WATER_Y, MAZE_W, CANVAS_H - WATER_Y);
ctx.restore();
}
```
Wait, `REFLECT_BASE - my - SLICE` — for my = MAZE_H - SLICE = 284: destY = 636 - 284 - 4 = 348. ✓ For my=0: destY = 632. ✓
Good.
Now the real world:
```js
function drawRealWorld(t) {
ctx.save();
ctx.beginPath();
ctx.rect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
ctx.clip();
// floor
const floor = ctx.createLinearGradient(0, MAZE_Y, 0, MAZE_Y + MAZE_H);
floor.addColorStop(0, '#0a1226');
floor.addColorStop(1, '#0e1a30');
ctx.fillStyle = floor;
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
// faint dot grid (helps you judge distances without revealing the walls)
ctx.fillStyle = 'rgba(120,175,240,0.13)';
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
ctx.beginPath();
ctx.arc(MAZE_X + c * CELL + CELL / 2,
MAZE_Y + r * CELL + CELL / 2, 1.4, 0, Math.PI * 2);
ctx.fill();
}
}
// a soft light around the player
const px = MAZE_X + player.x, py = MAZE_Y + player.y;
const light = ctx.createRadialGradient(px, py, 0, px, py, 120);
light.addColorStop(0, 'rgba(120,200,255,0.16)');
light.addColorStop(1, 'rgba(120,200,255,0)');
ctx.fillStyle = light;
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
// goal
drawPortal(ctx, MAZE_X + goal.x, MAZE_Y + goal.y, t);
// bump ripples = the only "wall feedback" in the real world
for (const b of bumps) {
const p = b.t / 0.5;
ctx.strokeStyle = `rgba(130,225,255,${(1 - p) * 0.75})`;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(MAZE_X + b.x, MAZE_Y + b.y, 7 + p * 24, 0, Math.PI * 2);
ctx.stroke();
}
// player
drawOrb(ctx, px, py, t);
ctx.restore();
// frame
ctx.strokeStyle = 'rgba(95,165,255,0.22)';
ctx.lineWidth = 2;
ctx.strokeRect(MAZE_X + 1, MAZE_Y + 1, MAZE_W - 2, MAZE_H - 2);
}
```
Guide line + water surface:
```js
function drawWaterSurface(t) {
// faint vertical guide connecting the player with their reflection
const gx = MAZE_X + player.x;
const gyTop = MAZE_Y + player.y;
const gyBottom = REFLECT_BASE - player.y - CELL * 0.0;
// hmm
}
```
Wait, the reflection of the player's center: canvas y = REFLECT_BASE - player.y = 636 - player.y. Let's verify: the player's canvas y = MAZE_Y + player.y = 44 + py. The reflection = 2*WATER_Y - (44 + py) = 680 - 44 - py = 636 - py. ✓
So the guide line goes from (gx, 44+py) to (gx, 636-py).
Let's draw it as a dashed line with low alpha, only in the mirror region (below WATER_Y) plus a bit above.
Actually, let's draw it from the player down through the water line to the reflection.
```js
ctx.save();
ctx.setLineDash([4, 6]);
ctx.strokeStyle = 'rgba(120,210,255,0.16)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(gx, MAZE_Y + player.y);
ctx.lineTo(gx, REFLECT_BASE - player.y);
ctx.stroke();
ctx.restore();
```
Hmm, this line passes over the real maze area too, which might be distracting. Let's only draw it from the water line down to the reflection. Actually, drawing from the player to the water line is helpful to see where the reflection aligns. Let's draw the whole thing but very faint.
Hmm, actually the player's position in the real maze and their reflection — since both are at the same x, a vertical line connects them. It's helpful. Let's keep it faint.
Let me draw it after the reflection so it's on top. But it would cross the reflection region... Let's draw it before the reflection so it's under. Hmm.
Order: real world → water line glow → reflection → guide line (on top, faint).
Actually, let's draw the guide line on top of everything in the mirror area. Fine.
Now the water surface line:
```js
function drawWaterLine(t) {
// glow that bleeds into the maze
const glow = ctx.createLinearGradient(0, WATER_Y - 30, 0, WATER_Y + 6);
glow.addColorStop(0, 'rgba(80,190,255,0)');
glow.addColorStop(0.75, 'rgba(80,190,255,0.18)');
glow.addColorStop(1, 'rgba(170,235,255,0.10)');
ctx.fillStyle = glow;
ctx.fillRect(0, WATER_Y - 30, CANVAS_W, 36);
// the surface itself
ctx.save();
ctx.strokeStyle = 'rgba(160,230,255,0.9)';
ctx.lineWidth = 2;
ctx.shadowColor = 'rgba(90,200,255,0.9)';
ctx.shadowBlur = 16;
ctx.beginPath();
for (let x = 0; x <= CANVAS_W; x += 8) {
const y = WATER_Y + Math.sin(x * 0.021 + t * 1.6) * 1.4
+ Math.sin(x * 0.052 - t * 2.2) * 0.7;
if (x === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.stroke();
ctx.restore();
}
```
Now the HUD:
```js
function drawHUD(t) {
ctx.save();
ctx.textAlign = 'center';
ctx.font = '600 11px "Segoe UI", system-ui, sans-serif';
ctx.letterSpacing = '2px'; // not universally supported, skip
ctx.fillStyle = 'rgba(140,190,240,0.55)';
ctx.fillText('THE MAZE · WALLS INVISIBLE', CANVAS_W / 2, 24);
ctx.fillStyle = 'rgba(120,210,255,0.5)';
ctx.fillText('THE REFLECTION · THE TRUE MAZE', CANVAS_W / 2, CANVAS_H - 12);
// timer
ctx.textAlign = 'right';
ctx.fillStyle = 'rgba(150,200,250,0.65)';
ctx.fillText(elapsed.toFixed(1) + 's', CANVAS_W - 14, 24);
ctx.restore();
}
```
Hmm, CANVAS_H - 12 = 658, and the reflection ends at 636. OK, there's space.
Hmm, but the text is centered over the reflection region at the bottom. That's fine.
Wait, the reflection clip is `rect(MAZE_X, WATER_Y, MAZE_W, CANVAS_H - WATER_Y)` = from 340 to 670. And the fade gradient goes to REFLECT_BASE = 636. Beyond 636, the reflection region is just dark (from the fade at 0.8 alpha, plus the dark water fill). Fine.
Actually, the fade gradient ends at 636, and beyond that the fill uses the last color stop (0.8 alpha dark). OK.
Hmm, but the "dark water" fill is drawn first covering the whole mirror region, then the slices are drawn. Beyond y=636 (below the reflection), only the dark water and the tint/fade show. Good.
Now the win overlay:
```js
function drawWinOverlay(t) {
ctx.save();
ctx.fillStyle = 'rgba(3,8,18,0.72)';
ctx.fillRect(MAZE_X, MAZE_Y, MAZE_W, MAZE_H);
const pulse = 0.85 + Math.sin(t * 3) * 0.15;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.shadowColor = 'rgba(120,255,210,0.9)';
ctx.shadowBlur = 26 * pulse;
ctx.fillStyle = '#c9ffe9';
ctx.font = '700 30px "Segoe UI", system-ui, sans-serif';
ctx.fillText('ESCAPED', CANVAS_W / 2, MAZE_Y + MAZE_H / 2 - 18);
ctx.shadowBlur = 0;
ctx.font = '400 14px "Segoe UI", system-ui, sans-serif';
ctx.fillStyle = 'rgba(180,240,220,0.85)';
ctx.fillText(`time ${elapsed.toFixed(1)}s`, CANVAS_W / 2, MAZE_Y + MAZE_H / 2 + 22);
ctx.restore();
}
```
Also, when won, the player's orb should stop at the portal.
Now, the main loop and init.
```js
let lastTs = 0;
function loop(ts) {
if (!lastTs) lastTs = ts;
let dt = (ts - lastTs) / 1000;
lastTs = ts;
if (dt > 0.05) dt = 0.05; // clamp for tab-switch spikes
update(dt);
render(ts);
requestAnimationFrame(loop);
}
function render(ts) {
const t = ts / 1000;
ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
ctx.fillStyle = '#04060e';
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
drawRealWorld(t);
drawReflection(t); // includes drawWorldImage
drawWaterLine(t);
drawGuideLine();
drawHUD();
if (won) drawWinOverlay(t);
}
```
Hmm, drawReflection calls drawWorldImage which uses `t`. Fine.
Order issue: drawWaterLine draws a glow that bleeds upward into the maze area — drawn after the reflection, so it overlays the top of the reflection. That's fine.
The guide line: drawn after the reflection and water line. Good.
Now init:
```js
function newGame() {
grid = createGrid();
player.x = CELL / 2;
player.y = CELL / 2;
goal.x = (COLS - 0.5) * CELL;
goal.y = (ROWS - 0.5) * CELL;
won = false;
elapsed = 0;
bumps = [];
lastBump = 0;
for (const k in keys) keys[k] = false;
}
```
Hmm — the goal is at the bottom-right cell. The player starts at the top-left. Good.
Keyboard:
```js
const KEYMAP = {
ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right',
w: 'up', s: 'down', a: 'left', d: 'right',
W: 'up', S: 'down', A: 'left', D: 'right',
};
window.addEventListener('keydown', (e) => {
const k = KEYMAP[e.key];
if (k) {
keys[k] = true;
e.preventDefault();
}
if (e.key === 'r' || e.key === 'R') newGame();
});
window.addEventListener('keyup', (e) => {
const k = KEYMAP[e.key];
if (k) {
keys[k] = false;
e.preventDefault();
}
});
```
Also add touch controls? Optional. Let's add simple pointer-based control: on pointerdown/move over the canvas, steer toward the pointer. That's a nice addition for mobile.
```js
let pointerTarget = null;
canvas.addEventListener('pointerdown', (e) => { ... });
```
Hmm, it complicates things. Let's add a simple version: if the pointer is held down, the player moves toward the pointer position.
```js
let pointer = { active: false, x: 0, y: 0 };
canvas.addEventListener('pointerdown', (e) => {
pointer.active = true;
updatePointer(e);
canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove', (e) => { if (pointer.active) updatePointer(e); });
canvas.addEventListener('pointerup', (e) => { pointer.active = false; });
canvas.addEventListener('pointercancel', () => { pointer.active = false; });
function updatePointer(e) {
const rect = canvas.getBoundingClientRect();
pointer.x = (e.clientX - rect.left) * (CANVAS_W / rect.width);
pointer.y = (e.clientY - rect.top) * (CANVAS_H / rect.height);
}
```
Then in update, if pointer.active and the pointer is in the maze area, compute the direction to the pointer.
Hmm, but the player would then navigate to the pointer position, which is fine.
Let's add it — but only if the pointer is in the real maze area (y < WATER_Y). Otherwise, ignore.
Actually, that could be confusing. Let's just add it as a bonus.
Hmm, I'll add it but keep it simple.
In update:
```js
if (pointer.active && pointer.y < WATER_Y - 4) {
const tx = pointer.x - MAZE_X;
const ty = pointer.y - MAZE_Y;
const dxp = tx - player.x;
const dyp = ty - player.y;
if (Math.hypot(dxp, dyp) > 6) {
dx += dxp; dy += dyp; // will be normalized
}
}
```
Hmm, need to integrate with the existing dx/dy logic. Let me restructure:
```js
let dx = 0, dy = 0;
if (keys.left) dx -= 1;
if (keys.right) dx += 1;
if (keys.up) dy -= 1;
if (keys.down) dy += 1;
// pointer steering
if (pointer.active && pointer.y < WATER_Y - 4) {
const tx = pointer.x - MAZE_X;
const ty = pointer.y - MAZE_Y;
const ddx = tx - player.x;
const ddy = ty - player.y;
const dist = Math.hypot(ddx, ddy);
if (dist > 4) { dx += ddx / dist; dy += ddy / dist; }
}
```
Good.
Now, `keys` — I used `for (const k in keys)` to reset. Fine.
Let me also prevent the page from scrolling with arrow keys — `e.preventDefault()` in keydown. But only when the key is mapped. Good.
Now, one more consideration: the initial render before the first frame. The loop starts with requestAnimationFrame, so it's fine.
Let me finalize and double-check the constants:
- COLS = 12, ROWS = 8, CELL = 36
- MAZE_W = 432, MAZE_H = 288
- MAZE_X = 84, MAZE_Y = 44
- MAZE_X + MAZE_W = 516; CANVAS_W = 600 → right margin 84. ✓ symmetric
- Maze bottom = 44 + 288 = 332
- WATER_Y = 340 (8px below the maze bottom)
- REFLECT_BASE = 2*340 - 44 = 636
- Reflection top (my = MAZE_H) → 636 - 288 = 348
- Reflection bottom (my = 0) → 636
- CANVAS_H = 670. Reflection ends at 636, leaving 34px. ✓
Mirror clip: from WATER_Y=340 to CANVAS_H=670. The reflection content is 348..636. Good.
Hmm, one thing: the maze's bottom wall is drawn at maze-local y=288, canvas y = 44+288 = 332. The water line is at 340. So there's an 8px gap between the maze's bottom wall and the water. The reflection of that bottom wall is at 636-288 = 348, which is 8px below the water line. Perfectly symmetric.
Now let's double check the reflection slice mapping once more.
For maze-local my (0 = top of the maze), the canvas y in the real view is MAZE_Y + my = 44 + my.
The reflection y = 2*WATER_Y - (44 + my) = 680 - 44 - my = 636 - my.
A slice covering maze-local [my, my+SLICE) maps to canvas y in [44+my, 44+my+SLICE) in the real view, and its reflection is [636-my-SLICE, 636-my).
So destY (top of the destination) = 636 - my - SLICE. ✓ That's what I have.
And the source in worldCanvas: the world canvas is translated by (PAD, PAD), so the maze-local point (mx, my) is at world canvas (PAD + mx, PAD + my). The source rect for the slice is (PAD, PAD + my, MAZE_W, SLICE). ✓
Good.
Now let me verify the reflection's vertical extent once more with the drawing loop:
- my goes from 0 to MAZE_H - SLICE in steps of SLICE.
- For my = 0: destY = 636 - 0 - 4 = 632, covering [632, 636].
- For my = 284: destY = 636 - 284 - 4 = 348, covering [348, 352].
So the drawn range is [348, 636]. ✓
Great.
Now, the goal is at maze-local (11.5*36, 7.5*36) = (414, 270). The player starts at (18, 18).
Let me now also double check `collides` with the goal cell. The goal is at cell (7,11). Fine.
One more: the player's starting position (18, 18) with PLAYER_R = 9 → the box is [9, 27] x [9, 27]. The boundary check: x - h = 9 >= EDGE = 3 ✓. So no immediate collision. Good.
Now let me make sure the maze generation always produces a connected maze — yes, the recursive backtracker does.
Let me also handle: what if the player gets stuck? They can't, since the maze is connected and they can move freely.
Alright, let me also think about whether the "walls invisible" makes the game too hard. The mirror shows everything, so the player can plan. But reading a mirrored maze is cognitively demanding. I think it's fine and it's the point.
One improvement: maybe make the real maze show a very faint hint of walls that are immediately adjacent to the player (within 1 cell). That would help. Hmm, but it undermines the concept. Let's not.
Actually, hmm, let me reconsider. Let's add a subtle "proximity shimmer": walls within ~28px of the player get a very faint glow in the real view. No — that basically reveals the maze locally, making it a normal maze with fog. The reflection would become useless.
Keep it pure: walls invisible, mirror shows all.
OK, one more thought: since the reflection shows the whole maze, the player can plan the entire route. That's good.
Let me write the final code.
Also I should double-check: `ctx.letterSpacing` is not standard everywhere; I'll skip it.
Let me write out the whole file now.
One more detail: `drawGuideLine` needs the current player position.
```js
function drawGuideLine() {
const gx = MAZE_X + player.x;
const y1 = MAZE_Y + player.y;
const y2 = REFLECT_BASE - player.y;
ctx.save();
ctx.setLineDash([3, 7]);
ctx.strokeStyle = 'rgba(130,215,255,0.20)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(gx, y1);
ctx.lineTo(gx, y2);
ctx.stroke();
ctx.restore();
}
```
Good.
Also, maybe highlight the player's reflection with a small ring so it's easy to spot. Let's add a pulsing ring at the reflection position.
```js
// highlight the reflection of the player
const ry = REFLECT_BASE - player.y;
ctx.save();
ctx.strokeStyle = `rgba(150,230,255,${0.35 + Math.sin(t*4)*0.15})`;
...
```
Hmm, the reflection is already drawn in the world canvas with the orb. Adding a ring on top could help. Let's add a subtle one.
Actually, the orb's glow in the reflection is quite visible. Skip the extra ring. But the guide line helps.
Hmm, let me add a subtle pulsing ring anyway — it makes the game more playable.
OK, writing the final code.
Let me also double check `drawOrb` uses `t` for pulsing — in the world canvas it's the same `t`. Fine.
Final code assembly. Let me write it out.
Actually, one thing about `worldCanvas` clearing: `wctx.clearRect(0, 0, worldCanvas.width, worldCanvas.height)` — then `wctx.save(); wctx.translate(PAD, PAD);` and draw. Then `wctx.restore()`. Good.
Also need to make sure `wctx.shadowBlur` doesn't cause issues. It's fine.
Let me write it.
Also: `drawWorldImage` is called inside `drawReflection` every frame. Fine.
Let me write out the final HTML.
I'll also add a small note in the HTML about the mirror being vertically flipped.
Let me finalize.
For the win overlay, I need `t` passed. Let me handle that.
Writing now.
One last check on the HUD text position: `ctx.fillText('THE MAZE · WALLS INVISIBLE', CANVAS_W/2, 24)`. CANVAS_W/2 = 300. MAZE_Y = 44, so y=24 is above the maze. Good.
The bottom text at CANVAS_H - 12 = 658. The reflection ends at 636. Good.
Also, the timer at the top-right: `CANVAS_W - 14 = 586`. Good.
Alright, writing the final answer.
Let me be careful with the `render` function ordering and the `t` parameter.
```js
function render(ts) {
const t = ts / 1000;
...
}
```
And `loop` calls `render(ts)`.
OK. Writing it out.
Also: `requestAnimationFrame(loop)` at the end of `loop`, and kick it off with `requestAnimationFrame(loop)`.
Let me write.
Actually, I realize I should double-check the `drawImage` source coordinates for the world canvas. `worldCanvas.width = MAZE_W + PAD*2 = 432 + 60 = 492`, `height = 288 + 60 = 348`.
Source rect: (PAD, my + PAD, MAZE_W, SLICE) = (30, my+30, 432, 4). Max y = 284+30+4 = 318 <= 348 ✓.
Good.
Now writing.
Let me also consider adding a "reveal" cheat button that shows the true maze for a moment — no, that defeats the purpose.
Alright, final code.
I'll add comments throughout for clarity.
Let me write the complete file.
Also, I want to double check the `update` function's handling of `bumps` filtering — I reassign `bumps = bumps.filter(...)` but `bumps` is declared with `let`. ✓
Let me write it.
Also: in `addBump`, `player.x` and `player.y` are maze-local. When drawing, I add MAZE_X/MAZE_Y. ✓
Final answer time.
One more: the `keydown` handler for 'r' calls `newGame()`. Good.
Let me also handle the button click for "New Maze".
OK writing.
Actually, hmm, one thing I want to reconsider: with a perfect maze and invisible walls, the player might get frustrated. Let me add a small quality-of-life feature: the reflection also shows a faint "trail" of where the player has been. That helps them remember. Let's add it — a breadcrumb trail in the world canvas (so it appears in the reflection) and maybe also faintly in the real view.
Hmm, that adds complexity. Let's add a simple trail: record the player's position every ~0.1s into an array (max ~60 points), and draw it as a fading line in both the real view and the reflection (in the reflection, it's part of the world canvas).
Actually, the trail in the real view would be helpful and doesn't reveal walls. Let's add it.
Hmm, it also could clutter. Let's add a subtle one.
Actually, let me skip the trail to keep the code focused. Hmm... but playability matters. Let me add it — it's only a few lines.
```js
let trail = [];
// in update:
if (!won) {
const last = trail[trail.length - 1];
if (!last || Math.hypot(player.x - last.x, player.y - last.y) > 5) {
trail.push({ x: player.x, y: player.y });
if (trail.length > 80) trail.shift();
}
}
```
Draw in the real view as a faint line, and in the world canvas too.
Hmm, the trail in the world canvas would need to be drawn with the maze-local coordinates. Fine.
Let's add it. In the real view, draw it with a low alpha cyan.
OK, let's finalize.
Actually, for the trail in the reflection: since the world canvas is redrawn each frame with the player's current position, the trail there would be the same. Fine.
Let me draw the trail in `drawRealWorld` before the player, and in `drawWorldImage` before the player.
Alright. Writing the final code now.
Let me make sure the trail is cleared on newGame.
Final write-up.
### assistant · answer
Here's a complete HTML/JavaScript implementation of the Reflection Maze game you requested. The maze walls are invisible in the main view; only the mirror at the bottom reveals the true layout.
```html
Reflection Maze — find the path in the mirror
Reflection Maze
The walls are invisible. Only the mirror tells the truth — and it is flipped.
WASD or ↑←↓→ to move • reach the green portal
```
### Gameplay & Design
The challenge is simple: reach the green portal without seeing any walls in the main view. The real maze layout is drawn offscreen and only appears in the water reflection, flipped vertically and distorted by ripples.
- **Movement:** Use WASD or arrow keys to move. On touch devices, you can also drag inside the maze area to steer.
- **Collision:** A collision system prevents you from passing through walls. When you bump an invisible wall, a ripple appears in the real view to give feedback.
- **The mirror:** The reflection at the bottom shows the full maze—walls, goal, and your current position—as a true vertical mirror image. A dashed guide line and pulsing ring help you locate your reflection.
- **Progression:** A breadcrumb trail tracks your path. Reach the green portal to win, and the timer stops.
- **Restart:** Press R or click the "New Maze" button to generate a fresh random maze.
---
**Optimization Tip:** You can tweak `SPEED` (line 74) to change player movement speed, or adjust `COLS` and `ROWS` (lines 64-65) to make the maze larger or smaller. The reflection ripple amplitude is controlled by the `amp` variable inside `drawReflection`.