(() => { "use strict"; const TILE = 20; const COLS = 28; const ROWS = 31; const canvas = document.getElementById("game"); const ctx = canvas.getContext("2d"); const scoreEl = document.getElementById("score"); const highScoreEl = document.getElementById("high-score"); const livesEl = document.getElementById("lives"); const levelEl = document.getElementById("level"); const messageEl = document.getElementById("message"); const HIGH_SCORE_KEY = "photoreport-pacman-high"; const MAZE_LAYOUT = [ "############################", "#............##............#", "#.####.#####.##.#####.####.#", "#o####.#####.##.#####.####o#", "#.####.#####.##.#####.####.#", "#..........................#", "#.####.##.########.##.####.#", "#.####.##.########.##.####.#", "#......##....##....##......#", "######.##### ## #####.######", " #.##### ## #####.# ", " #.## ##.# ", " #.## ###--### ##.# ", "######.## # # ##.######", " . # # . ", "######.## # # ##.######", " #.## ######## ##.# ", " #.## ##.# ", " #.## ######## ##.# ", "######.## ######## ##.######", "#............##............#", "#.####.#####.##.#####.####.#", "#.####.#####.##.#####.####.#", "#o..##....... .......##..o#", "###.##.##.########.##.##.###", "#......##....##....##......#", "#.##########.##.##########.#", "#..........................#", "############################", ]; const GHOST_COLORS = ["#ff0000", "#ffb8ff", "#00ffff", "#ffb852"]; const GHOST_NAMES = ["Blinky", "Pinky", "Inky", "Clyde"]; const SCORE_PELLET = 10; const SCORE_POWER = 50; const SCORE_GHOST = 200; const POWER_MS = 7000; const GHOST_FRIGHTENED_SPEED = 0.55; const GHOST_NORMAL_SPEED = 0.85; const PAC_SPEED = 1.0; const audioCtx = typeof AudioContext !== "undefined" ? new AudioContext() : null; let muted = false; function playTone(freq, duration, type = "square", volume = 0.04) { if (!audioCtx || muted) return; const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.type = type; osc.frequency.value = freq; gain.gain.value = volume; osc.connect(gain); gain.connect(audioCtx.destination); osc.start(); gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + duration); osc.stop(audioCtx.currentTime + duration); } function playPellet() { playTone(440, 0.05, "square", 0.03); } function playPower() { playTone(220, 0.12, "sawtooth", 0.05); setTimeout(() => playTone(330, 0.12, "sawtooth", 0.05), 80); } function playGhost() { playTone(880, 0.15, "triangle", 0.06); } function playDeath() { playTone(180, 0.4, "sawtooth", 0.05); } function playWin() { [523, 659, 784, 1047].forEach((f, i) => setTimeout(() => playTone(f, 0.12, "square", 0.04), i * 100)); } const state = { maze: [], pellets: 0, score: 0, highScore: Number(localStorage.getItem(HIGH_SCORE_KEY) || 0), lives: 3, level: 1, mode: "ready", paused: false, powerUntil: 0, frightenedGhosts: new Set(), eatenGhosts: 0, frame: 0, pac: null, ghosts: [], pendingDir: null, messageTimer: null, }; function tileAt(col, row) { if (row < 0 || row >= ROWS || col < 0 || col >= COLS) return "#"; return state.maze[row][col]; } function isWall(col, row) { const t = tileAt(col, row); return t === "#"; } function isWalkable(col, row, allowGhostDoor = false) { const t = tileAt(col, row); if (t === "#") return false; if (t === "-" && !allowGhostDoor) return false; return true; } function wrapCol(col) { if (col < 0) return COLS - 1; if (col >= COLS) return 0; return col; } function gridToPixel(col, row) { return { x: col * TILE + TILE / 2, y: row * TILE + TILE / 2 }; } function pixelToGrid(x, y) { return { col: Math.floor(x / TILE), row: Math.floor(y / TILE) }; } function resetMaze() { state.maze = MAZE_LAYOUT.map((row) => row.split("")); state.pellets = 0; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { const t = state.maze[r][c]; if (t === "." || t === "o") state.pellets += 1; } } } function createPac() { return { x: 14 * TILE + TILE / 2, y: 23 * TILE + TILE / 2, dir: { col: 0, row: 0 }, nextDir: { col: 0, row: 0 }, mouth: 0, speed: PAC_SPEED, }; } function createGhosts() { const starts = [ { col: 13, row: 14 }, { col: 14, row: 14 }, { col: 12, row: 14 }, { col: 15, row: 14 }, ]; return starts.map((s, i) => { const p = gridToPixel(s.col, s.row); return { name: GHOST_NAMES[i], color: GHOST_COLORS[i], x: p.x, y: p.y, dir: { col: i % 2 === 0 ? -1 : 1, row: 0 }, mode: "scatter", speed: GHOST_NORMAL_SPEED, home: { col: s.col, row: s.row }, scatterTarget: [ { col: COLS - 2, row: 0 }, { col: 0, row: 0 }, { col: COLS - 1, row: ROWS - 1 }, { col: 0, row: ROWS - 1 }, ][i], }; }); } function setMessage(text, hideAfter = 0) { messageEl.textContent = text; messageEl.classList.remove("hidden"); clearTimeout(state.messageTimer); if (hideAfter > 0) { state.messageTimer = setTimeout(() => messageEl.classList.add("hidden"), hideAfter); } } function updateHud() { scoreEl.textContent = String(state.score); highScoreEl.textContent = String(state.highScore); levelEl.textContent = String(state.level); livesEl.textContent = "●".repeat(Math.max(0, state.lives)); } function saveHighScore() { if (state.score > state.highScore) { state.highScore = state.score; localStorage.setItem(HIGH_SCORE_KEY, String(state.highScore)); } updateHud(); } function canMove(entity, dir, allowGhostDoor = false) { const { col, row } = pixelToGrid(entity.x, entity.y); const center = gridToPixel(col, row); const atCenter = Math.abs(entity.x - center.x) < 2 && Math.abs(entity.y - center.y) < 2; if (!atCenter && (dir.col !== entity.dir.col || dir.row !== entity.dir.row)) { return false; } const nextCol = wrapCol(col + dir.col); const nextRow = row + dir.row; return isWalkable(nextCol, nextRow, allowGhostDoor); } function snapToCenter(entity) { const { col, row } = pixelToGrid(entity.x, entity.y); const center = gridToPixel(col, row); if (Math.abs(entity.x - center.x) < entity.speed + 1) entity.x = center.x; if (Math.abs(entity.y - center.y) < entity.speed + 1) entity.y = center.y; } function moveEntity(entity, allowGhostDoor = false) { snapToCenter(entity); if (!canMove(entity, entity.dir, allowGhostDoor)) return; entity.x += entity.dir.col * entity.speed; entity.y += entity.dir.row * entity.speed; if (entity.x < 0) entity.x = COLS * TILE - 1; if (entity.x >= COLS * TILE) entity.x = 0; } function oppositeDir(dir) { return { col: -dir.col, row: -dir.row }; } function dist2(a, b) { const dx = a.col - b.col; const dy = a.row - b.row; return dx * dx + dy * dy; } function chooseGhostDir(ghost) { const { col, row } = pixelToGrid(ghost.x, ghost.y); const center = gridToPixel(col, row); const atCenter = Math.abs(ghost.x - center.x) < 2 && Math.abs(ghost.y - center.y) < 2; if (!atCenter) return; const options = [ { col: 1, row: 0 }, { col: -1, row: 0 }, { col: 0, row: 1 }, { col: 0, row: -1 }, ].filter((d) => { if (d.col === -ghost.dir.col && d.row === -ghost.dir.row && (ghost.dir.col || ghost.dir.row)) { return false; } const nc = wrapCol(col + d.col); const nr = row + d.row; return isWalkable(nc, nr, true); }); if (options.length === 0) return; const pacGrid = pixelToGrid(state.pac.x, state.pac.y); let target = ghost.scatterTarget; const frightened = state.frightenedGhosts.has(ghost.name); if (frightened) { target = { col: Math.floor(Math.random() * COLS), row: Math.floor(Math.random() * ROWS) }; } else if (ghost.mode === "chase") { if (ghost.name === "Blinky") target = pacGrid; else if (ghost.name === "Pinky") target = { col: pacGrid.col + state.pac.dir.col * 4, row: pacGrid.row + state.pac.dir.row * 4 }; else if (ghost.name === "Inky") { const blinky = state.ghosts[0]; const bg = pixelToGrid(blinky.x, blinky.y); const pivot = { col: pacGrid.col + state.pac.dir.col * 2, row: pacGrid.row + state.pac.dir.row * 2 }; target = { col: pivot.col + (pivot.col - bg.col), row: pivot.row + (pivot.row - bg.row) }; } else { const d = dist2(pacGrid, { col, row }); target = d > 64 ? pacGrid : ghost.scatterTarget; } } let best = options[0]; let bestDist = Infinity; for (const d of options) { const nc = wrapCol(col + d.col); const nr = row + d.row; const dd = dist2({ col: nc, row: nr }, target); if (frightened) { if (dd > bestDist || (dd === bestDist && Math.random() > 0.5)) { bestDist = dd; best = d; } } else if (dd < bestDist || (dd === bestDist && Math.random() > 0.5)) { bestDist = dd; best = d; } } ghost.dir = best; } function eatPellet() { const { col, row } = pixelToGrid(state.pac.x, state.pac.y); const t = tileAt(col, row); if (t === ".") { state.maze[row][col] = " "; state.pellets -= 1; state.score += SCORE_PELLET; playPellet(); updateHud(); } else if (t === "o") { state.maze[row][col] = " "; state.pellets -= 1; state.score += SCORE_POWER; state.powerUntil = performance.now() + POWER_MS; state.frightenedGhosts = new Set(GHOST_NAMES); state.eatenGhosts = 0; playPower(); updateHud(); } } function checkCollisions() { for (const ghost of state.ghosts) { const dx = ghost.x - state.pac.x; const dy = ghost.y - state.pac.y; if (dx * dx + dy * dy > (TILE * 0.55) ** 2) continue; if (state.frightenedGhosts.has(ghost.name)) { state.frightenedGhosts.delete(ghost.name); state.eatenGhosts += 1; state.score += SCORE_GHOST * state.eatenGhosts; playGhost(); const home = gridToPixel(ghost.home.col, ghost.home.row); ghost.x = home.x; ghost.y = home.y; ghost.dir = { col: 0, row: 0 }; updateHud(); } else if (state.mode === "playing") { loseLife(); return; } } } function loseLife() { playDeath(); state.lives -= 1; updateHud(); if (state.lives <= 0) { state.mode = "gameover"; saveHighScore(); setMessage("Game Over — ESPAÇO para reiniciar"); return; } state.mode = "dying"; setMessage("Perdeste uma vida!", 1200); setTimeout(resetPositions, 1200); } function resetPositions() { state.pac = createPac(); state.ghosts = createGhosts(); state.frightenedGhosts.clear(); state.mode = "ready"; setMessage("Prima ESPAÇO para continuar"); } function nextLevel() { playWin(); state.level += 1; state.mode = "ready"; resetMaze(); resetPositions(); setMessage(`Nível ${state.level}! ESPAÇO para começar`); updateHud(); } function startGame() { if (audioCtx && audioCtx.state === "suspended") audioCtx.resume(); if (state.mode === "gameover") { state.score = 0; state.lives = 3; state.level = 1; resetMaze(); } state.mode = "playing"; messageEl.classList.add("hidden"); updateHud(); } function togglePause() { if (state.mode !== "playing" && state.mode !== "ready") return; state.paused = !state.paused; setMessage(state.paused ? "Pausado — ESPAÇO para continuar" : "", state.paused ? 0 : 1); if (!state.paused) messageEl.classList.add("hidden"); } function updatePac() { if (state.pendingDir && canMove(state.pac, state.pendingDir)) { state.pac.dir = state.pendingDir; state.pendingDir = null; } else if (!canMove(state.pac, state.pac.dir)) { state.pac.dir = { col: 0, row: 0 }; } moveEntity(state.pac); if (state.pac.dir.col || state.pac.dir.row) state.pac.mouth = (state.pac.mouth + 0.25) % (Math.PI * 2); eatPellet(); } function updateGhosts() { const now = performance.now(); if (now > state.powerUntil) state.frightenedGhosts.clear(); const cycle = (state.frame % 600) / 600; const scatter = cycle < 0.25 || (cycle > 0.5 && cycle < 0.75); for (const ghost of state.ghosts) { ghost.mode = scatter ? "scatter" : "chase"; ghost.speed = state.frightenedGhosts.has(ghost.name) ? GHOST_FRIGHTENED_SPEED : GHOST_NORMAL_SPEED; chooseGhostDir(ghost); moveEntity(ghost, true); } } function drawMaze() { for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { const t = state.maze[r][c]; const x = c * TILE; const y = r * TILE; if (t === "#") { ctx.fillStyle = "#111"; ctx.fillRect(x, y, TILE, TILE); ctx.strokeStyle = "#2f6bff"; ctx.lineWidth = 2; ctx.strokeRect(x + 2, y + 2, TILE - 4, TILE - 4); } else if (t === "." || t === "o") { ctx.fillStyle = t === "o" ? "#ffb8de" : "#ffd8a8"; const radius = t === "o" ? 4 : 2; ctx.beginPath(); ctx.arc(x + TILE / 2, y + TILE / 2, radius, 0, Math.PI * 2); ctx.fill(); } } } } function drawPac() { const { x, y, mouth, dir } = state.pac; const angle = Math.0; let rotation = 0; if (dir.col === 1) rotation = 0; else if (dir.col === -1) rotation = Math.PI; else if (dir.row === -1) rotation = -Math.PI / 2; else if (dir.row === 1) rotation = Math.PI / 2; ctx.save(); ctx.translate(x, y); ctx.rotate(rotation); ctx.fillStyle = "#ffd54f"; ctx.beginPath(); const open = 0.2 + Math.abs(Math.sin(mouth)) * 0.35; ctx.arc(0, 0, TILE * 0.42, open * Math.PI, (2 - open) * Math.PI); ctx.lineTo(0, 0); ctx.fill(); ctx.restore(); } function drawGhost(ghost) { const frightened = state.frightenedGhosts.has(ghost.name); const x = ghost.x; const y = ghost.y; const w = TILE * 0.85; const h = TILE * 0.9; ctx.fillStyle = frightened ? (Math.floor(state.frame / 8) % 2 ? "#fff" : "#2121de") : ghost.color; ctx.beginPath(); ctx.arc(x, y - h * 0.15, w / 2, Math.PI, 0); ctx.lineTo(x + w / 2, y + h * 0.35); for (let i = 0; i < 4; i++) { const sx = x + w / 2 - (i * w) / 3; ctx.lineTo(sx, y + h * 0.35 + (i % 2 ? 4 : 0)); } ctx.lineTo(x - w / 2, y + h * 0.35); ctx.closePath(); ctx.fill(); if (!frightened) { ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.arc(x - 4, y - 2, 3.5, 0, Math.PI * 2); ctx.arc(x + 4, y - 2, 3.5, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "#000"; ctx.beginPath(); ctx.arc(x - 3 + ghost.dir.col, y - 2 + ghost.dir.row, 1.8, 0, Math.PI * 2); ctx.arc(x + 5 + ghost.dir.col, y - 2 + ghost.dir.row, 1.8, 0, Math.PI * 2); ctx.fill(); } } function render() { ctx.fillStyle = "#000"; ctx.fillRect(0, 0, canvas.width, canvas.height); drawMaze(); drawPac(); for (const ghost of state.ghosts) drawGhost(ghost); } function tick() { state.frame += 1; if (!state.paused && state.mode === "playing") { updatePac(); updateGhosts(); checkCollisions(); if (state.pellets <= 0) nextLevel(); } render(); requestAnimationFrame(tick); } function handleKey(e) { const key = e.key.toLowerCase(); if (key === " " || key === "spacebar") { e.preventDefault(); if (state.mode === "ready" || state.mode === "gameover") startGame(); else togglePause(); return; } if (key === "m") { muted = !muted; setMessage(muted ? "Som desligado" : "Som ligado", 800); return; } const map = { arrowup: { col: 0, row: -1 }, arrowdown: { col: 0, row: 1 }, arrowleft: { col: -1, row: 0 }, arrowright: { col: 1, row: 0 }, w: { col: 0, row: -1 }, s: { col: 0, row: 1 }, a: { col: -1, row: 0 }, d: { col: 1, row: 0 }, }; if (map[key]) { e.preventDefault(); state.pendingDir = map[key]; if (state.mode === "ready") startGame(); } } function init() { resetMaze(); state.pac = createPac(); state.ghosts = createGhosts(); updateHud(); setMessage("Prima ESPAÇO para começar"); window.addEventListener("keydown", handleKey); requestAnimationFrame(tick); } init(); })();