HTML Pacman Game: Simple and Fun
<html>
<head>
<title>HTML Pacman Game</title>
<style>
canvas {
background: #000000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="game" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
<pre><code> const pacman = {
x: canvas.width/2,
y: canvas.height/2,
speed: 5,
color: 'yellow',
radius: 10,
direction: 'right',
alive: true
}
function drawPacman() {
ctx.fillStyle = pacman.color;
ctx.beginPath();
ctx.arc(pacman.x, pacman.y, pacman.radius, (Math.PI / 180) * 30, (Math.PI / 180) * 330, false); // Draw Pacman
ctx.lineTo(pacman.x, pacman.y);
ctx.fill();
}
function movePacman(e) {
if (e.keyCode === 37 && pacman.x > 0) { // Left
pacman.x -= pacman.speed;
pacman.direction = 'left';
}
else if (e.keyCode === 38 && pacman.y > 0) { // Up
pacman.y -= pacman.speed;
pacman.direction = 'up';
}
else if (e.keyCode === 39 && pacman.x < canvas.width) { // Right
pacman.x += pacman.speed;
pacman.direction = 'right';
}
else if (e.keyCode === 40 && pacman.y < canvas.height) { // Down
pacman.y += pacman.speed;
pacman.direction = 'down';
}
}
document.addEventListener('keydown', movePacman);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPacman();
requestAnimationFrame(draw);
}
draw();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lniG 著作权归作者所有。请勿转载和采集!