HTML5吃豆人編程代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5吃豆人游戲</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="canvas"></canvas> <script> // 初始化游戲畫布 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // 定義吃豆人和鬼 var PACMAN_RADIUS = 15; var GHOST_RADIUS = 20; var pacman = { x: 100, y: 100, radius: PACMAN_RADIUS, speed: 5, angle: 0, mouthOpen: true, draw: function() { // 繪制吃豆人 ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, this.angle, this.angle + (Math.PI / 2), false); ctx.lineTo(this.x, this.y); ctx.closePath(); ctx.fillStyle = "#F9B400"; ctx.fill(); // 繪制嘴 ctx.beginPath(); if (this.mouthOpen) { ctx.arc(this.x, this.y, this.radius, this.angle + (Math.PI / 4), this.angle + (7 * Math.PI / 4), false); } else { ctx.arc(this.x, this.y, this.radius, this.angle + (Math.PI / 2), this.angle + (3 * Math.PI / 2), false); } ctx.lineTo(this.x, this.y); ctx.closePath(); ctx.fillStyle = "#000"; ctx.fill(); }, move: function() { // 移動吃豆人 this.x += this.speed; if (this.x > canvas.width - this.radius || this.x < this.radius) { this.speed *= -1; } if (this.mouthOpen) { this.mouthOpen = false; } else { this.mouthOpen = true; } } }; var ghost = { x: 500, y: 200, radius: GHOST_RADIUS, speed: 3, angle: 0, draw: function() { // 繪制鬼 ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fillStyle = "#FFB6C1"; ctx.fill(); // 繪制眼睛 ctx.beginPath(); ctx.arc(this.x + 8, this.y - 6, 5, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fillStyle = "#000"; ctx.fill(); }, move: function() { // 移動鬼 this.y += this.speed; if (this.y > canvas.height - this.radius || this.y < this.radius) { this.speed *= -1; } } }; // 定義游戲循環 function gameLoop() { // 清空畫布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 移動并繪制吃豆人和鬼 pacman.move(); pacman.draw(); ghost.move(); ghost.draw(); // 重復游戲循環 window.requestAnimationFrame(gameLoop); } // 開始游戲循環 gameLoop(); </script> </body> </html>