Simple Pac-Man

Score: 0

Use Arrow Keys to Move

// If Pac-Man's x is greater, Pac-Man is to the right. if (pacman.x > ghost.x) dx = ghost.speed; // Move right // If Pac-Man's x is less, Pac-Man is to the left. else if (pacman.x < ghost.x) dx = -ghost.speed; // Move left // If Pac-Man's y is greater, Pac-Man is below. if (pacman.y > ghost.y) dy = ghost.speed; // Move down // If Pac-Man's y is less, Pac-Man is above. else if (pacman.y < ghost.y) dy = -ghost.speed; // Move up // 1. Attempt the horizontal move let nextX = ghost.x + dx; if (!isWall( ... )) { // Check for a wall ghost.x = nextX; // If no wall, make the move } // 2. Attempt the vertical move let nextY = ghost.y + dy; if (!isWall( ... )) { // Check for a wall ghost.y = nextY; // If no wall, make the move } /* Map Legend: 0 = Wall 1 = Dot 2 = Empty Space */ const map = [ [0,0,0,0,0,0,0,0,0,0,...], // Row 0 [0,1,1,1,1,1,1,1,1,1,...], // Row 1 [0,1,0,0,1,0,0,1,0,1,...], // Row 2 [0,1,0,0,1,0,0,1,0,1,...], // Row 3 [0,1,1,1,1,1,1,1,1,1,...], // Row 4 // ...and so on ]; function drawMap() { // Loop through each row for (let y = 0; y < map.length; y++) { // Loop through each column in that row for (let x = 0; x < map[y].length; x++) { const tile = map[y][x]; // Get the number (0, 1, or 2) if (tile === 0) { // Wall context.fillStyle = '#0000FF'; // Blue context.fillRect(x * tileSize, y * tileSize, tileSize, tileSize); } else if (tile === 1) { // Dot // ...draw a dot at (x, y) } } } } // 1. Get Pac-Man's next potential position let nextX = pacman.x + pacman.dx * pacman.speed; let nextY = pacman.y + pacman.dy * pacman.speed; // 2. Check for a wall at that next position. // This function checks the map for us! if (!isWall(nextX, nextY)) { // 3. If it's NOT a wall, allow the move. pacman.x = nextX; pacman.y = nextY; } function isWall(x, y) { // Convert pixel position to array index const tileX = Math.floor(x / tileSize); const tileY = Math.floor(y / tileSize); // Look up the number in the map const tile = map[tileY][tileX]; // Is it a wall? return tile === 0; }