const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const logsDiv = document.getElementById('logs'); // 定义目标对象 class Target { constructor(x, y) { this.x = x; this.y = y; this.width = 50; this.height = 50; } draw() { ctx.fillStyle = 'blue'; ctx.fillRect(this.x, this.y, this.width, this.height); } } // 定义子弹对象 class Bullet { constructor(x, y, target, speed) { this.x = x; this.y = y; this.target = target; this.speed = speed; this.radius = 5; } draw() { ctx.fillStyle = 'red'; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); } update() { // 计算方向 const dx = this.target.x + this.target.width / 2 - this.x; const dy = this.target.y + this.target.height / 2 - this.y; const dist = Math.sqrt(dx * dx + dy * dy); if (dist > this.speed) { this.x += dx / dist * this.speed; this.y += dy / dist * this.speed; } else { this.x = this.target.x + this.target.width / 2; this.y = this.target.y + this.target.height / 2; logEvent("Bullet reached the target."); } } } // 创建目标和子弹 const target = new Target(400, 100); const bullets = []; // 发射子弹 function shootBullet() { const startX = canvas.width / 2; const startY = canvas.height - 10; bullets.push(new Bullet(startX, startY, target, 5)); logEvent("Bullet fired from (" + startX + ", " + startY + ")"); } // 游戏循环 function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); target.draw(); bullets.forEach((bullet, index) => { bullet.update(); bullet.draw(); if (Math.abs(bullet.x - target.x - target.width / 2) < target.width / 2 && Math.abs(bullet.y - target.y - target.height / 2) < target.height / 2) { logEvent("Bullet hit the target."); bullets.splice(index, 1); // 移除击中目标的子弹 } }); requestAnimationFrame(gameLoop); } // 记录事件到日志 function logEvent(description) { const logEntry = document.createElement('div'); logEntry.textContent = description; logsDiv.appendChild(logEntry); } // 添加键盘事件监听器 document.addEventListener('keydown', function(event) { if (event.code === 'Space') { shootBullet(); } }); // 启动游戏循环 gameLoop();