Pac-Man Game
body {
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
background-color: #282c34;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.game-container {
border: 5px solid #f7d51d;
background-color: #000;
}
canvas {
display: block;
margin: 0 auto;
background-color: #000;
}
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const pacMan = {
x: 300,
y: 300,
size: 30,
speed: 5,
angle: 0.25,
delta: 0.05
};
const ghosts = [
{ x: 100, y: 100, dx: 2, dy: 2 },
{ x: 500, y: 500, dx: -2, dy: -2 }
];
let keysPressed = {
ArrowUp: false,
ArrowDown: false,
ArrowLeft: false,
ArrowRight: false
};
// Draw Pac-Man
function drawPacMan() {
ctx.beginPath();
ctx.arc(pacMan.x, pacMan.y, pacMan.size, pacMan.angle * Math.PI, (2 - pacMan.angle) * Math.PI);
ctx.lineTo(pacMan.x, pacMan.y);
ctx.fillStyle = '#f7d51d';
ctx.fill();
ctx.closePath();
}
// Draw Ghosts
function drawGhosts() {
ghosts.forEach(ghost => {
ctx.beginPath();
ctx.arc(ghost.x, ghost.y, 20, 0, Math.PI * 2);
ctx.fillStyle = '#ff0000';
ctx.fill();
ctx.closePath();
});
}
// Move Pac-Man
function movePacMan() {
if (keysPressed.ArrowUp) pacMan.y -= pacMan.speed;
if (keysPressed.ArrowDown) pacMan.y += pacMan.speed;
if (keysPressed.ArrowLeft) pacMan.x -= pacMan.speed;
if (keysPressed.ArrowRight) pacMan.x += pacMan.speed;
}
// Move Ghosts
function moveGhosts() {
ghosts.forEach(ghost => {
ghost.x += ghost.dx;
ghost.y += ghost.dy;
if (ghost.x < 0 || ghost.x > canvas.width) ghost.dx *= -1;
if (ghost.y < 0 || ghost.y > canvas.height) ghost.dy *= -1;
});
}
// Update Game
function updateGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
movePacMan();
moveGhosts();
drawPacMan();
drawGhosts();
requestAnimationFrame(updateGame);
}
// Handle Key Down/Up Events
document.addEventListener('keydown', (e) => {
if (e.code in keysPressed) {
keysPressed[e.code] = true;
}
});
document.addEventListener('keyup', (e) => {
if (e.code in keysPressed) {
keysPressed[e.code] = false;
}
});
updateGame();
Comments
Post a Comment