Simple HTML Game: Build a Basic Jump and Avoid Game with HTML & JavaScript
Simple HTML Game: Build a Basic Jump and Avoid Game with HTML & JavaScript
Introduction
This tutorial will guide you through creating a simple HTML game where you control a character that needs to avoid obstacles to reach the end of the level. We'll be using HTML and JavaScript to bring this game to life.
Game Play
The game is controlled using the arrow keys on your keyboard. Your goal is to jump over obstacles using the 'ArrowUp' key. If you collide with an obstacle, the game is over, and you'll have to start again. Reach the end of the level to win!
Code
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML Game</title>
</head>
<body>
<canvas id='gameCanvas' width='800' height='600'></canvas>
<script src='game.js'></script>
</body>
</html>
JavaScript Code
// Create game canvas
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
// Define player and obstacle properties
var player = {
x: 50,
y: 450,
width: 50,
height: 50,
speed: 5,
jumping: false
};
var obstacle = {
x: 700,
y: 475,
width: 50,
height: 50,
speed: 3
};
// Define game functions
function drawPlayer() {
context.fillStyle = '#000';
context.fillRect(player.x, player.y, player.width, player.height);
}
function drawObstacle() {
context.fillStyle = '#f00';
context.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}
function update() {
// Move obstacle
obstacle.x -= obstacle.speed;
if (obstacle.x < 0) {
obstacle.x = 700;
}
// Move player
if (player.jumping) {
player.y -= player.speed * 2;
player.speed -= 1;
if (player.speed < 0) {
player.jumping = false;
player.speed = 5;
}
}
// Check for collision
if (player.x < obstacle.x + obstacle.width &&
player.x + player.width > obstacle.x &&
player.y < obstacle.y + obstacle.height &&
player.y + player.height > obstacle.y) {
// Collision detected, game over
alert('Game over!');
document.location.reload();
}
// Check for win
if (player.x > 750) {
alert('You win!');
document.location.reload();
}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawObstacle();
}
function gameLoop() {
update();
draw();
window.requestAnimationFrame(gameLoop);
}
// Start game loop
gameLoop();
// Handle keyboard input
document.addEventListener('keydown', function(event) {
if (event.key === 'ArrowUp' && !player.jumping) {
player.jumping = true;
}
});
Conclusion
This simple HTML game gives you a basic understanding of how to build a game using HTML and JavaScript. You can now expand upon this foundation by adding more levels, obstacles, and exciting features to your game!
原文地址: https://www.cveoy.top/t/topic/lntW 著作权归作者所有。请勿转载和采集!