Make a html game about flappy bird
Sure, here's a simple HTML game about Flappy Bird:
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
// Game variables
var canvas;
var canvasContext;
var birdX = 50;
var birdY = 300;
var birdSpeedY = 0;
var gravity = 0.5;
var gap = 100;
var pipeWidth = 50;
var pipeHeight = 600;
var pipeGap = 150;
var pipeX = 400;
var score = 0;
var gameOver = false;
// On page load
window.onload = function () {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
setInterval(updateGame, 20);
canvas.addEventListener('click', flapBird);
}
// Update game state
function updateGame() {
if (gameOver) {
return;
}
birdSpeedY += gravity;
birdY += birdSpeedY;
if (birdY > canvas.height || birdY < 0) {
endGame();
}
pipeX -= 5;
if (pipeX < -pipeWidth) {
pipeX = canvas.width;
score++;
}
if (birdX + 30 > pipeX && birdX < pipeX + pipeWidth && (birdY < pipeHeight - gap || birdY + 30 > pipeHeight)) {
endGame();
}
drawGame();
}
// Draw game objects
function drawGame() {
// Clear canvas
canvasContext.fillStyle = 'lightblue';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
// Draw bird
canvasContext.fillStyle = 'yellow';
canvasContext.fillRect(birdX, birdY, 30, 30);
// Draw pipe
canvasContext.fillStyle = 'green';
canvasContext.fillRect(pipeX, 0, pipeWidth, pipeHeight);
canvasContext.fillRect(pipeX, pipeHeight + pipeGap, pipeWidth, canvas.height - (pipeHeight + pipeGap));
// Draw score
canvasContext.fillStyle = 'black';
canvasContext.font = '20px Arial';
canvasContext.fillText('Score: ' + score, 10, 30);
}
// Handle bird flap
function flapBird() {
birdSpeedY = -10;
}
// End game
function endGame() {
gameOver = true;
canvas.removeEventListener('click', flapBird);
canvasContext.fillStyle = 'red';
canvasContext.font = '40px Arial';
canvasContext.fillText('Game Over!', 100, canvas.height / 2);
}
</script>
</body>
</html>
You can copy and paste this code into a new HTML file and open it in a web browser to play the Flappy Bird game. Use the mouse click to make the bird flap and try to navigate through the pipes without hitting them. The score will increase whenever you successfully pass through a pair of pipes. If you hit a pipe or go off the screen, the game will end and display a "Game Over" message.
原文地址: http://www.cveoy.top/t/topic/i7BR 著作权归作者所有。请勿转载和采集!