Creating a complete Pac-Man game involves several components, including rendering the game board, handling user input, managing game entities (Pac-Man and ghosts), collision detection, score tracking, and adding sound and visual effects. Below is a simplified yet comprehensive implementation using HTML, CSS, and JavaScript. This implementation focuses on core functionalities and can be expanded further for additional features.
Project Structure
- HTML: Sets up the game canvas and UI elements.
- CSS: Styles the game canvas and UI.
- JavaScript: Contains the game logic, including rendering, movement, collision detection, and user interactions.
1. HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pac-Man Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas" width="560" height="620"></canvas>
<div id="ui">
<div id="score">Score: 0</div>
<div id="lives">Lives: 3</div>
</div>
</div>
<!-- Sound Effects -->
<audio id="eatSound" src="sounds/eat.wav"></audio>
<audio id="deathSound" src="sounds/death.wav"></audio>
<audio id="powerUpSound" src="sounds/powerup.wav"></audio>
<script src="script.js"></script>
</body>
</html>
2. CSS (styles.css)
/* styles.css */
body {
background-color: #000;
color: #fff;
font-family: 'Arial', sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
#game-container {
position: relative;
width: 560px;
margin: 20px auto;
}
#gameCanvas {
background-color: #000;
display: block;
margin: 0 auto;
border: 2px solid #fff;
}
#ui {
display: flex;
justify-content: space-between;
margin-top: 10px;
font-size: 1.2em;
}
#score, #lives {
padding: 5px 20px;
background-color: #333;
border-radius: 5px;
}
3. JavaScript (script.js)
/* script.js */
// Constants for the game
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const livesElement = document.getElementById('lives');
const eatSound = document.getElementById('eatSound');
const deathSound = document.getElementById('deathSound');
const powerUpSound = document.getElementById('powerUpSound');
const TILE_SIZE = 20;
const ROWS = 31;
const COLS = 28;
const GAME_WIDTH = COLS * TILE_SIZE;
const GAME_HEIGHT = ROWS * TILE_SIZE;
// Game Variables
let score = 0;
let lives = 3;
let gameOver = false;
let powerUp = false;
let powerUpTimer = 0;
// Directions
const directions = {
ArrowUp: { x: 0, y: -1 },
ArrowDown: { x: 0, y: 1 },
ArrowLeft: { x: -1, y: 0 },
ArrowRight: { x: 1, y: 0 },
};
// Simple map layout (1: wall, 0: pellet, 2: power pellet)
// This is a simplified version. A complete map requires a detailed layout.
const map = [
// 31 rows of 28 columns each
// For brevity, only a few rows are defined. Complete this according to the standard Pac-Man map.
// 0 represents empty space, 1 represents walls, 2 represents power pellets
// ... (You need to fill in the map array with the proper layout)
];
// Initialize map with walls and pellets
function initializeMap() {
for (let row = 0; row < ROWS; row++) {
map[row] = [];
for (let col = 0; col < COLS; col++) {
// Example simplistic walls around the border
if (
row === 0 || row === ROWS - 1 ||
col === 0 || col === COLS - 1 ||
(row === 14 && col >= 13 && col <= 14)
) {
map[row][col] = 1; // Wall
} else {
map[row][col] = 0; // Pellet
}
// Place power pellets at corners
if (
(row === 1 && col ===1) ||
(row === 1 && col === COLS -2) ||
(row === ROWS -2 && col ===1) ||
(row === ROWS -2 && col === COLS -2)
) {
map[row][col] = 2;
}
}
}
}
// Entity Class
class Entity {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.dir = { x: 0, y: 0 };
this.color = color;
this.speed = 2;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(
this.x * TILE_SIZE + TILE_SIZE / 2,
this.y * TILE_SIZE + TILE_SIZE / 2,
TILE_SIZE / 2 - 2,
0,
2 * Math.PI
);
ctx.fill();
}
move() {
let newX = this.x + this.dir.x * (this.speed / TILE_SIZE);
let newY = this.y + this.dir.y * (this.speed / TILE_SIZE);
if (!isWall(newX, newY)) {
this.x = newX;
this.y = newY;
}
}
}
// Pac-Man Class
class PacMan extends Entity {
constructor(x, y, color) {
super(x, y, color);
this.nextDir = this.dir;
}
setDirection(key) {
if (directions[key]) {
this.nextDir = directions[key];
}
}
move() {
// Try to change direction if possible
if (!isWall(this.x + this.nextDir.x, this.y + this.nextDir.y)) {
this.dir = this.nextDir;
}
// Move Pac-Man
let newX = this.x + this.dir.x * (this.speed / TILE_SIZE);
let newY = this.y + this.dir.y * (this.speed / TILE_SIZE);
if (!isWall(newX, newY)) {
this.x = newX;
this.y = newY;
this.checkPellet();
}
}
checkPellet() {
let col = Math.floor(this.x);
let row = Math.floor(this.y);
if (map[row][col] === 0) {
map[row][col] = -1; // Empty
score += 10;
eatSound.play();
updateUI();
} else if (map[row][col] === 2) {
map[row][col] = -1; // Empty
score += 50;
powerUp = true;
powerUpTimer = Date.now();
powerUpSound.play();
updateUI();
}
}
draw() {
ctx.fillStyle = this.color;
// Draw Pac-Man with mouth
ctx.beginPath();
let angle = 0.25;
if (this.dir.x === 1) angle = 0.25; // Right
if (this.dir.x === -1) angle = 1.25; // Left
if (this.dir.y === 1) angle = 0.75; // Down
if (this.dir.y === -1) angle = 1.75; // Up
ctx.arc(
this.x * TILE_SIZE + TILE_SIZE / 2,
this.y * TILE_SIZE + TILE_SIZE / 2,
TILE_SIZE / 2 - 2,
angle * Math.PI,
(2 - angle) * Math.PI
);
ctx.lineTo(this.x * TILE_SIZE + TILE_SIZE / 2, this.y * TILE_SIZE + TILE_SIZE / 2);
ctx.fill();
}
}
// Ghost Class
class Ghost extends Entity {
constructor(x, y, color) {
super(x, y, color);
this.directionQueue = [];
this.speed = 1.5;
this.originalPosition = { x, y };
this.scatterMode = true;
this.modeTimer = Date.now();
}
move() {
// Simple AI: random movement
if (Math.random() < 0.02) {
let keys = Object.keys(directions);
let randKey = keys[Math.floor(Math.random() * keys.length)];
this.dir = directions[randKey];
}
let newX = this.x + this.dir.x * (this.speed / TILE_SIZE);
let newY = this.y + this.dir.y * (this.speed / TILE_SIZE);
if (!isWall(newX, newY)) {
this.x = newX;
this.y = newY;
} else {
this.dir = { x: 0, y: 0 }; // Stop if hit wall
}
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(
this.x * TILE_SIZE + TILE_SIZE / 2,
this.y * TILE_SIZE + TILE_SIZE / 2,
TILE_SIZE / 2 - 2,
0,
2 * Math.PI
);
ctx.fill();
// Eyes
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(
this.x * TILE_SIZE + TILE_SIZE / 2 - 5,
this.y * TILE_SIZE + TILE_SIZE / 2 - 5,
3,
0,
2 * Math.PI
);
ctx.fill();
ctx.beginPath();
ctx.arc(
this.x * TILE_SIZE + TILE_SIZE / 2 + 5,
this.y * TILE_SIZE + TILE_SIZE / 2 - 5,
3,
0,
2 * Math.PI
);
ctx.fill();
}
resetPosition() {
this.x = this.originalPosition.x;
this.y = this.originalPosition.y;
this.dir = { x: 0, y: 0 };
}
}
// Helper Functions
function isWall(x, y) {
if (x < 0 || x >= COLS || y < 0 || y >= ROWS) return true;
return map[Math.floor(y)][Math.floor(x)] === 1;
}
function updateUI() {
scoreElement.textContent = `Score: ${score}`;
livesElement.textContent = `Lives: ${lives}`;
}
function detectCollision(pacman, ghost) {
return Math.floor(pacman.x) === Math.floor(ghost.x) &&
Math.floor(pacman.y) === Math.floor(ghost.y);
}
function handleCollision() {
for (let ghost of ghosts) {
if (detectCollision(pacman, ghost)) {
if (powerUp) {
// Eat ghost
score += 200;
eatSound.play();
ghost.resetPosition();
updateUI();
} else {
// Pac-Man dies
deathSound.play();
lives -= 1;
updateUI();
if (lives === 0) {
gameOver = true;
} else {
// Reset positions
resetEntities();
}
}
}
}
}
function resetEntities() {
pacman.x = 14;
pacman.y = 23;
pacman.dir = { x: 0, y: 0 };
pacman.nextDir = { x: 0, y: 0 };
for (let ghost of ghosts) {
ghost.resetPosition();
}
}
function drawMap() {
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
if (map[row][col] === 1) {
ctx.fillStyle = '#0000FF';
ctx.fillRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);
} else if (map[row][col] === 0) {
// Draw pellet
ctx.fillStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(
col * TILE_SIZE + TILE_SIZE / 2,
row * TILE_SIZE + TILE_SIZE / 2,
3,
0,
2 * Math.PI
);
ctx.fill();
} else if (map[row][col] === 2) {
// Draw power pellet
ctx.fillStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(
col * TILE_SIZE + TILE_SIZE / 2,
row * TILE_SIZE + TILE_SIZE / 2,
6,
0,
2 * Math.PI
);
ctx.fill();
}
}
}
}
// Initialize Game Entities
let pacman;
let ghosts = [];
function initializeEntities() {
pacman = new PacMan(14, 23, 'yellow');
// Initialize ghosts at different positions
ghosts.push(new Ghost(13, 11, 'red'));
ghosts.push(new Ghost(14, 11, 'pink'));
ghosts.push(new Ghost(15, 11, 'cyan'));
ghosts.push(new Ghost(12, 11, 'orange'));
}
// Game Loop
function gameLoop() {
if (gameOver) {
ctx.fillStyle = 'white';
ctx.font = '36px Arial';
ctx.fillText('Game Over', GAME_WIDTH / 2 - 100, GAME_HEIGHT / 2);
return;
}
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
drawMap();
pacman.move();
pacman.draw();
for (let ghost of ghosts) {
ghost.move();
ghost.draw();
}
handleCollision();
// Handle power-up timeout
if (powerUp && Date.now() - powerUpTimer > 10000) { // Power-up lasts 10 seconds
powerUp = false;
}
requestAnimationFrame(gameLoop);
}
// Event Listeners
document.addEventListener('keydown', (e) => {
pacman.setDirection(e.key);
});
// Initialize Game
initializeMap();
initializeEntities();
updateUI();
gameLoop();
4. Sound Effects
To enhance the gaming experience, include sound effects for eating pellets, consuming power-ups, and losing lives. Place your sound files (eat.wav, death.wav, powerup.wav) inside a sounds directory relative to your HTML file.
5. Completing the Map
The provided map is highly simplified. For a complete Pac-Man experience, you'll need to define a detailed 31x28 grid that mirrors the classic Pac-Man maze. Each cell should represent walls, pellets, power pellets, or empty spaces. Here's an example of how you can represent a simple map row:
const map = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
// Add the remaining 30 rows similarly
];
For brevity, only the first row is shown. You can populate the map array with appropriate values to design the maze.
6. Enhancements and Optimizations
- Ghost AI: Implement smarter AI for ghosts, such as targeting Pac-Man's position or following predetermined paths.
- Animations: Add animations for Pac-Man's mouth opening and closing, ghost movements, and when ghosts are vulnerable.
- Multiple Levels: Increase difficulty as the player progresses through levels by increasing ghost speed or introducing new ghost behaviors.
- Sound Management: Use the Web Audio API for more advanced sound control and effects.
7. Conclusion
This implementation provides a foundational structure for a Pac-Man game using HTML, CSS, and JavaScript. To create a fully-featured game, consider expanding upon the map design, enhancing ghost behaviors, adding animations, and refining collision detection. Additionally, thorough testing and optimization will ensure smooth gameplay across different devices.
Feel free to customize and expand this code to create a more immersive and complete Pac-Man experience!