HTML5簡單網(wǎng)頁游戲代碼的編寫對于初學者來說,是個較為實用的學習項目。下面我將帶您了解HTML5游戲代碼的編寫。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5游戲代碼</title> </head> <body> <canvas id="game" width="800" height="600"></canvas> <script> var game = document.getElementById('game'); var ctx = game.getContext('2d'); function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } var fruit = { x: getRandom(0, 780), y: getRandom(0, 580), size: 20 } function drawFruit() { ctx.fillStyle = 'red'; ctx.fillRect(fruit.x, fruit.y, fruit.size, fruit.size); } function hitDetect() { if (fruit.x<= snakeX + 10 && fruit.x + fruit.size >= snakeX && fruit.y<= snakeY + 10 && fruit.y + fruit.size >= snakeY) { ateFruit(); } } function ateFruit() { score++; initData(); } var snakeX = 400; var snakeY = 300; var snakeDirection = 'right'; var snakeSpeed = 10; function drawSnake() { if (snakeDirection == 'right') { snakeX += snakeSpeed; } if (snakeDirection == 'left') { snakeX -= snakeSpeed; } if (snakeDirection == 'up') { snakeY -= snakeSpeed; } if (snakeDirection == 'down') { snakeY += snakeSpeed; } hitDetect(); ctx.fillStyle = 'green'; ctx.fillRect(snakeX, snakeY, 10, 10); } var score = 0; function drawScore() { ctx.fillStyle = 'black'; ctx.font = 'bold 20px Arial'; ctx.textAlign = 'left'; ctx.fillText('Score: ' + score, 10, 30); } function initData() { fruit.x = getRandom(0, 780); fruit.y = getRandom(0, 580); } function initGame() { ctx.clearRect(0, 0, game.width, game.height); drawFruit(); drawSnake(); drawScore(); setTimeout(initGame, 100); } document.addEventListener('keydown', function(event) { if (event.keyCode == 37) { snakeDirection = 'left'; } if (event.keyCode == 38) { snakeDirection = 'up'; } if (event.keyCode == 39) { snakeDirection = 'right'; } if (event.keyCode == 40) { snakeDirection = 'down'; } }); initGame(); </script> </body> </html>
上面是一個非常簡單的貪吃蛇游戲代碼,主要包括了畫布、果實、貪吃蛇、得分、按鍵事件等。
對于初學者來說,運行并理解這些代碼,是一個不錯的入門練習。同時也可以通過修改代碼,增加自己的想法來實現(xiàn)自己的小游戲。
上一篇html5簡單源代碼