JIT
Pacman game HTML CSS Javascript
create a complete pacman game using html javascript and css in one file

Okay, here is a complete Pac-Man game implemented in a single HTML file using HTML, CSS, and JavaScript.

This single HTML file contains the structure (HTML), styling (CSS within <style>), and all the game logic (JavaScript within <script>). Open this index.html file in your browser to play the game. Use the arrow keys to control Pac-Man.

Updated files
v1
i have nothing, only a blue square in a black background

Okay, it seems like there might be an issue in the drawing logic or an early JavaScript error stopping the execution after drawing just one part of the map (likely the first wall tile).

Let's refine the code, particularly focusing on the drawing functions and ensuring the game loop runs correctly. I'll also adjust how collision detection and movement permissions are handled to be more robust.

Key Changes:

  1. Centering Entities: Pac-Man and Ghosts now use their center coordinates for positioning and calculations, which simplifies collision and grid alignment checks. pacman.x, pacman.y, ghost.x, ghost.y now represent the center.
  2. canMove Refinement: The canMove function now takes the entity as an argument and checks collision points around the entity's perimeter based on its radius and potential next position. It handles walls, ghost gate logic, and tunnel boundaries more explicitly.
  3. Grid Alignment: Introduced isAlignedToGrid helper function to check if an entity is close enough to the center of a tile, which is crucial for making turns at intersections. Turns are now only allowed when aligned. Entities also snap to the grid center when turning or stopping at a wall.
  4. Ghost House Logic: Added more distinct states (IN_HOUSE, EXITING) and logic for ghosts entering, waiting (with bobbing), exiting, and returning when eaten. Added simple exit delays.
  5. Ghost Targeting: Refined target calculations, including the Pinky 'up' bug fix and Inky's vector calculation.
  6. Ghost Movement: chooseBestDirection and chooseRandomDirection now use the refined canMove and grid alignment checks. Ghosts prioritize directions based on standard Pac-Man rules (Up > Left > Right > Down).
  7. Collision Checks: Pellet collision uses grid coordinates. Ghost collision uses distance between centers.
  8. Game Loop & States: Added a gameStarted flag and a "Ready?" timer. The game loop now handles the initial delay and stops correctly on permanent game over or win. handleDeath temporarily sets gameOver to pause updates during the death sequence.
  9. Drawing: Adjusted drawing functions to work with center coordinates. Improved wall drawing slightly. Added "Ready?" text. Scoreboard drawing is separated.
  10. Map Coordinates: Corrected Pac-Man's starting Y position and potentially the ghost house gate row in the map array (though the original seemed okay, adjusted to common layouts). Ensured canvas height matches map rows.
  11. Input Handling: Using event.code for better keyboard layout compatibility. Allowed immediate 180-degree turns.

This revised version addresses potential issues with collision, movement logic, state management, and drawing that might have caused the previous version to fail or render incorrectly. Try running this updated index.html._

Updated files
v2
now i have the drawing logic, but i cannot move the pacman

Okay, if the drawing is correct but Pac-Man isn't moving, the issue likely lies in the input handling, the movement update logic (updatePacman), or the collision detection (canMove) preventing any movement from starting.

Let's add some console.log statements to help diagnose where the process is breaking down and refine the movement logic slightly.

  1. Verify Input: Check if key presses are registered.
  2. Verify Game State: Ensure the game is in a state where movement should occur (gameStarted is true, gameOver is false).
  3. Verify Movement Attempt: Check if the code tries to change pacman.dx or pacman.dy.
  4. Verify Collision Check: See if canMove is preventing the initial move.

Here's the updated code with logging and minor adjustments:

Key Changes & Debugging Focus:

  1. handleInput: Added logs to confirm key presses are detected and requestedDirection is set. Also added logic to potentially set the initial direction during the "Ready?" phase if the move is valid, allowing Pac-Man to start moving immediately when gameStarted becomes true.
  2. updatePacman:
    • Added extensive logging (console.log) to trace the flow: checking requestedDirection, alignment (isAlignedToGrid), and collision (canMove) during turns and forward movement. Check your browser's developer console (usually F12) for these messages.
    • Refined the turning logic: It now explicitly checks for reversal, then checks for turns only when aligned, snapping to the grid before checking canMove for the turn. It also has a condition to start movement if currently stopped.
    • Ensured forward movement only happens if pacman.dx or pacman.dy is non-zero and canMove allows it.
    • If forward movement is blocked, Pac-Man stops and snaps to the grid center.
  3. isAlignedToGrid: Added logging and adjusted the tolerance slightly based on speed. This function is critical for allowing turns only at the correct spots.
  4. canMove: Added logging to pinpoint potential collision issues. Made sure tunnel logic correctly handles coordinates going out of bounds.
  5. init: Corrected Pac-Man's starting X coordinate to be properly centered (TILE_SIZE * 10.5). Reset readyTimer in init.
  6. Game Loop: Added logging for when gameStarted becomes true and when the loop stops. Capped deltaTime to prevent extreme jumps if the tab loses focus.
  7. State Handling: Ensured gameOver correctly pauses updates during the death sequence and resumes if lives remain. gameWon also stops updates. Input is ignored if gameOver or gameWon.

To Use:

  1. Replace the previous HTML file content with this new code.
  2. Open the index.html file in your browser.
  3. IMPORTANT: Open your browser's Developer Console (usually by pressing F12).
  4. Try pressing the arrow keys or WASD.
  5. Observe the messages in the console. They should tell you:
    • If key presses are registered (Key pressed..., Requested Direction Set...).
    • What happens in updatePacman each frame (alignment, turn attempts, movement attempts, canMove results).
    • If gameStarted becomes true.

Look for patterns: Is requestedDirection being set but never applied? Is isAlignedToGrid always false? Is canMove always returning false when you try to move? The console logs should guide you to the exact point of failure._

Updated files
v3
tetris.html:245 Initializing game... tetris.html:278 Total pellets: 172 tetris.html:282 Initialization complete. tetris.html:1078 Starting game loop... tetris.html:1045 Game Started! tetris.html:750 Pac-Man died! tetris.html:770 Resetting positions... tetris.html:750 Pac-Man died! tetris.html:770 Resetting positions...

Okay, the logs show the game initializes, starts, then Pac-Man immediately dies, resets, and dies again. This strongly suggests an instant collision is happening right at the start of the level or immediately after Pac-Man respawns.

The most likely causes are:

  1. Initial Position Collision: Pac-Man's starting/reset position (10.5 * TILE_SIZE, 16.5 * TILE_SIZE) is somehow causing an immediate collision check failure with a ghost's initial/reset position (especially Blinky, who starts outside the house at 10.5 * TILE_SIZE, 8.5 * TILE_SIZE).
  2. Collision Check Flaw: The checkGhostCollisions function's distance calculation or threshold is triggering incorrectly at the start.
  3. Ghost State on Reset: A ghost might not be resetting its state correctly (e.g., remaining in CHASE instead of going back to IN_HOUSE or SCATTER appropriately) and instantly hits the newly spawned Pac-Man.

Let's add more specific logging inside checkGhostCollisions to see exactly which ghost is causing the collision and what their positions/states are. We'll also log the positions during the reset.

Changes Made:

  1. checkGhostCollisions: Added a console.log that prints the positions, states, distance, and threshold only when Pac-Man and a ghost are potentially close (within one tile + threshold). This helps identify the culprit without flooding the console. Also added a specific log when a collision is detected. Made the collision threshold slightly more lenient (- 2 instead of - 4).
  2. resetPositionsAfterDeath: Added logs to confirm Pac-Man's reset position and that ghosts are being recreated. Recreating ghosts (createGhosts()) is generally the safest way to ensure they are in the correct initial state after a death.
  3. handleDeath: Slightly shortened the delay. Crucially, ensured gameOver is set to true immediately to stop further updates during the pause, and only set back to false after positions are reset and the new readyTimer starts.
  4. createGhosts: Added logging to show the state and position of each ghost upon creation/reset. Increased the staggering of exit delays.
  5. init: Ensured pacman object is defined before createGhosts is called. Added logging for Pac-Man's initial position.
  6. Game Loop: Clarified the condition for running the update function: game must be started, not currently in the death pause (!gameOver), and not won.

Next Steps:

  1. Run this updated code.
  2. Open the Developer Console (F12).
  3. Observe the logs carefully, especially right after "Game Started!" and after "Resetting after death...".
  4. Look for the Collision Check: logs. Which ghost (Ghost id) is close to Pac-Man? What are their states and positions? Is the distance less than the threshold immediately?
  5. Look for the !!! Collision detected !!! log. This confirms which ghost triggered handleDeath.
  6. Compare the logged positions at the time of collision with the logged reset/initial positions.

This detailed logging should pinpoint exactly why the instant death is occurring._

Updated files
v4
now it's better, i can move the pacman, but ghosts doesn't exit from the central cage

Okay, if the ghosts aren't leaving the cage, the problem is likely within the state management for IN_HOUSE and EXITING states in the updateGhosts function, or potentially how canMove handles the ghost house tiles (4 and 5) for ghosts trying to leave.

Let's focus on debugging that specific logic:

  1. Add Logging: Insert console.log statements within the IN_HOUSE and EXITING state blocks in updateGhosts to track their progress.
  2. Review canMove: Double-check the conditions in canMove related to ghosts, the gate (tile 4), and the house interior (tile 5). Ensure exiting ghosts can pass through the gate.
  3. Check Exit Coordinates: Verify ghostHouseCenter and ghostExitPos are correct relative to the map.

Here's the code with added logging specifically for ghost exiting:

Changes Made:

  1. canMove: Explicitly added continue statements for tile 5 (house interior) and tile 4 (gate) when the ghost state is EXITING or EATEN. This ensures they are allowed to be on these tiles in those specific states. Added a check to block non-exiting/eaten ghosts from entering the gate (tile 4).
  2. updateGhosts:
    • Added logging within the IN_HOUSE state to track the exitDelayTimer.
    • Added logging when the ghost reaches the center X and transitions to EXITING.
    • Added logging within the EXITING state to track the ghost's Y position relative to the target ghostExitPos.y.
    • Added logging when the ghost successfully exits.
    • Added logging (as console.error) if canMove returns false during an EXITING movement attempt, as this indicates a problem.
    • Added logging (as console.warn) if any ghost movement gets blocked.

How to Debug:

  1. Run the updated code.
  2. Open the Developer Console (F12).
  3. Watch the logs for messages starting with Ghost X ...:
    • Do you see ghosts logging Waiting in house...? Does the timer decrease?
    • Do you see them log Reached center X, changing state to EXITING...?
    • Do you see them log Exiting. y=..., targetY=...? Does the y value decrease towards the targetY?
    • Crucially: Do you see any CANNOT MOVE while EXITING! errors? If so, this points directly to the canMove function or the coordinates being wrong.
    • Do you see them log Exited house! ...?

This should clearly show at which step the exiting process is failing for each ghost (Pinky, Inky, Clyde).*_

Updated files
v5