HTML小游戲是一種非常有趣的程序代碼,通過HTML語言編寫,可以讓玩家在網頁上進行游戲。下面是一個基于HTML的小游戲程序代碼示例,包含如下幾個部分:
游戲規則:
玩家需要通過鍵盤控制小球躲避障礙物,每成功避開一個障礙物,得到一分,游戲結束條件為撞上障礙物。
var ballX = 50; var ballY = 200; var ballRadius = 10; var ballColor = 'red'; var dx = 5; var dy = -5; var obstacleX = 600; var obstacleY = 100; var obstacleWidth = 50; var obstacleHeight = 100; var obstacleColor = 'blue'; var score = 0; function drawBall() { context.beginPath(); context.arc(ballX, ballY, ballRadius, 0, Math.PI * 2); context.fillStyle = ballColor; context.fill(); context.closePath(); } function drawObstacle() { context.beginPath(); context.rect(obstacleX, obstacleY, obstacleWidth, obstacleHeight); context.fillStyle = obstacleColor; context.fill(); context.closePath(); } function drawScore() { context.font = '16px Arial'; context.fillStyle = 'black'; context.fillText('Score: ' + score, 8, 20); } function moveBall() { ballX += dx; ballY += dy; if (ballX + dx >canvas.width - ballRadius || ballX + dx< ballRadius) { dx = -dx; } if (ballY + dy >canvas.height - ballRadius || ballY + dy< ballRadius) { dy = -dy; } } function moveObstacle() { obstacleX -= 10; if (obstacleX< -obstacleWidth) { obstacleX = canvas.width; obstacleY = Math.floor(Math.random() * (canvas.height - obstacleHeight)); score++; } } function checkCollision() { if (ballX + ballRadius >obstacleX && ballX - ballRadius< obstacleX + obstacleWidth && ballY + ballRadius >obstacleY && ballY - ballRadius< obstacleY + obstacleHeight) { clearInterval(intervalId); alert('Game Over! Your score is: ' + score); } } function draw() { context.clearRect(0, 0, canvas.width, canvas.height); drawBall(); drawObstacle(); drawScore(); moveBall(); moveObstacle(); checkCollision(); } var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var intervalId = setInterval(draw, 10); document.addEventListener('keydown', function(event) { if (event.keyCode == 38) { dy = -5; } else if (event.keyCode == 40) { dy = 5; } });以上代碼包括了小球,障礙物,分數以及鍵盤事件的控制等內容。玩家可以通過鍵盤控制小球的上下移動,躲避障礙物并得分。同時,代碼中還包括了碰撞檢測、定時器等功能。 通過HTML小游戲,玩家可以在網頁上獲得一段輕松愉快的娛樂。編寫HTML小游戲代碼能夠讓開發者鍛煉編寫項目的能力,提升編程技能水平。
上一篇python 連接號
下一篇python 連續奇數和