HTML5箱子游戲源代碼是一個非常流行的游戲程序,可以讓玩家在開發自己的游戲網站時快速添加有趣的游戲功能。下面是箱子游戲的源代碼:
<html><head><title>HTML5 Box Game</title><style>canvas{border: 1px solid #333;}</style></head><body><canvas id="game" width="800" height="600"></canvas><script>// 設置畫布var canvas = document.getElementById("game"); var context = canvas.getContext("2d");// 定義游戲變量var boxSize = 40; var playerX = 0; var playerY = 0; var speed = 5; var boxes = [ { x: 200, y: 100 }, { x: 300, y: 200 }, { x: 400, y: 300 } ];// 繪制游戲function draw(){ context.clearRect(0, 0, canvas.width, canvas.height); for(var i = 0; i< boxes.length; i++){ var box = boxes[i]; context.fillRect(box.x, box.y, boxSize, boxSize); } context.fillRect(playerX, playerY, boxSize, boxSize); }// 更新游戲function update(){ if(keyPressed === "ArrowLeft"){ playerX -= speed; } else if(keyPressed === "ArrowRight"){ playerX += speed; } else if(keyPressed === "ArrowUp"){ playerY -= speed; } else if(keyPressed === "ArrowDown"){ playerY += speed; }// 檢查是否碰撞for(var i = 0; i< boxes.length; i++){ var box = boxes[i]; if(playerX< box.x + boxSize && playerX + boxSize >box.x && playerY< box.y + boxSize && playerY + boxSize >box.y){ boxes.splice(i, 1); break; } } }// 監聽鍵盤事件var keyPressed = null; document.addEventListener("keydown", function(event){ keyPressed = event.key; }); document.addEventListener("keyup", function(event){ keyPressed = null; });// 游戲循環setInterval(function(){ update(); draw(); }, 1000/60);</script></body></html>