<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 &amp;&amp; pacman.x &gt; 0) { // Left
      pacman.x -= pacman.speed;
      pacman.direction = 'left';
    }
    else if (e.keyCode === 38 &amp;&amp; pacman.y &gt; 0) { // Up
      pacman.y -= pacman.speed;
      pacman.direction = 'up';
    }
    else if (e.keyCode === 39 &amp;&amp; pacman.x &lt; canvas.width) { // Right
      pacman.x += pacman.speed;
      pacman.direction = 'right';
    }
    else if (e.keyCode === 40 &amp;&amp; pacman.y &lt; 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();
&lt;/script&gt;
</code></pre>
  </body>
</html>
HTML Pacman Game: Simple and Fun

原文地址: https://www.cveoy.top/t/topic/lniG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录