JSFiddle - React, Tailwind, and code Playground
HTML
<div id="game-container">
<div id="bird"></div>
</div>
CSS
#game-container {
position: relative;
width: 400px;
height: 400px;
background-color: skyblue;
overflow: hidden;
}
#bird {
position: absolute;
width: 50px;
height: 50px;
background-color: yellow;
}
JavaScript
// Model
let gameData = {
bird: {
position: 150,
velocity: 0,
gravity: 0.5,
},
};
// ViewModel
const birdViewModel = {
jump: function () {
gameData.bird.velocity = -10;
},
update: function () {
gameData.bird.velocity += gameData.bird.gravity;
gameData.bird.position += gameData.bird.velocity;
if (gameData.bird.position > 350) {
gameData.bird.position = 350;
gameData.bird.velocity = 0;
}
},
};
// View
const birdView = document.getElementById('bird');
function render() {
birdView.style.top = gameData.bird.position + 'px';
}
// Game Loop
function gameLoop() {
birdViewModel.update();
render();
if (gameData.bird.position <= 0) {
gameOver();
}
}
// Game Over Function
function gameOver() {
clearInterval(gameInterval);
alert('Game Over');
location.reload();
}
document.addEventListener('keydown', function (event) {
if (event.key === ' ' || event.key === 'ArrowUp') {
birdViewModel.jump();
}
});
// Initialize the game
const gameInterval = setInterval(gameLoop, 20);