HTML5是一種新的Web技術,它改變了游戲開發的方式。這篇文章將教你如何使用HTML5創建一個簡單的抓金塊游戲。
<!DOCTYPE html> <html> <head> <title>抓金塊游戲</title> <style type="text/css"> #canvas { width: 500px; height: 400px; border: 1px solid #000; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); // 金塊的橫縱坐標 var blockX = canvas.width / 2; var blockY = canvas.height - 30; // 玩家的橫縱坐標 var playerX = canvas.width / 2; var playerY = canvas.height - 10; var playerWidth = 75; var playerHeight = 10; var playerSpeed = 7; // 按鍵狀態 var rightPressed = false; var leftPressed = false; // 監聽按鍵事件 document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); // 按鍵按下事件 function keyDownHandler(event) { if (event.key == "Right" || event.key == "ArrowRight") { rightPressed = true; } else if (event.key == "Left" || event.key == "ArrowLeft") { leftPressed = true; } } // 按鍵松開事件 function keyUpHandler(event) { if (event.key == "Right" || event.key == "ArrowRight") { rightPressed = false; } else if (event.key == "Left" || event.key == "ArrowLeft") { leftPressed = false; } } // 繪制金塊 function drawBlock() { context.beginPath(); context.rect(blockX, blockY, 10, 10); context.fillStyle = "#FFD700"; context.fill(); context.closePath(); } // 繪制玩家 function drawPlayer() { context.beginPath(); context.rect(playerX, playerY, playerWidth, playerHeight); context.fillStyle = "#000"; context.fill(); context.closePath(); } // 游戲主循環 function gameLoop() { context.clearRect(0, 0, canvas.width, canvas.height); drawBlock(); drawPlayer(); // 玩家移動 if (rightPressed && playerX< canvas.width - playerWidth) { playerX += playerSpeed; } else if (leftPressed && playerX >0) { playerX -= playerSpeed; } // 判斷是否抓住了金塊 if (playerY == blockY) { if (blockX >= playerX && blockX<= playerX + playerWidth) { alert("你贏了!"); document.location.reload(); } } // 金塊掉下來 if (blockY<= 0) { blockX = Math.random() * (canvas.width - 10); blockY = canvas.height - 30; } else { blockY -= 5; } } // 開始游戲 setInterval(gameLoop, 10); </script> </body> </html>
在這段代碼中,我們使用了canvas元素來繪制游戲畫面。使用canvas可以很方便地創建各種圖形和動畫效果。
在游戲主循環中,我們不斷地刷新畫面,并且根據按鍵的狀態移動玩家。同時,金塊也在不斷地下落,如果被玩家抓到了,游戲就會結束。
這個抓金塊游戲比較簡單,但是你可以根據自己的想法加入更多的玩法和特效。
上一篇html5技術代碼