Sure! Below is a complete, self-contained HTML file that combines HTML, CSS, and JavaScript to create a simple yet visually appealing car racing game. You can copy this code into a file with a .html extension (e.g., car_racing_game.html) and open it in your web browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Car Racing Game</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: #2c3e50;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
font-family: Arial, sans-serif;
position: relative;
}
#gameArea {
position: relative;
width: 400px;
height: 600px;
background: #34495e;
overflow: hidden;
border: 5px solid #ecf0f1;
border-radius: 10px;
}
.road {
position: absolute;
width: 100%;
height: 100%;
background: repeating-linear-gradient(
0deg,
#2c3e50,
#2c3e50 50px,
#34495e 50px,
#34495e 100px
);
background-size: 100% 100%;
animation: moveRoad 5s linear infinite;
}
@keyframes moveRoad {
from { background-position: 0 0; }
to { background-position: 0 100px; }
}
#playerCar {
position: absolute;
bottom: 20px;
left: 50%;
width: 50px;
height: 100px;
margin-left: -25px;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAABG0lEQVRoge3ZsQ3DMAwF0KZBxugDlwEq1AmvYAtOhvU31oKMI449ehzvSHt2Mu/akkBEURRFARRFEREFRI7oKpjrUEqBZTgVq0MCAuAOiFUHjI4jwAkGmDi5oc/YG05uIJCDkBlEYCtShadowJg6+AY753kJ7BaBaoD3VzAAhOz8BopErwDgE6IuAGgFIg5geQBBQSWAMgCrASgIiAEIgGiAciAmIE6iAmIBiIEuIAoB0gOIgVwQGYOiBxgAS4BTpg/Z4kVjZnqFRpVloA3IMmUADNGvl4eCqC8AAAAASUVORK5CYII=') no-repeat center;
background-size: cover;
}
.obstacle {
position: absolute;
width: 50px;
height: 100px;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAABFUlEQVRoge3ZQQ6DMAwF0PZABToAStBNsArsACKtAkVOj6C2d3YzDmtLQhKdL+fWluVURRFEREFRRFEREFRRFEREFRRFEREFRRFEREFHuAWgMkAiwAa4LOAG6D6AFkAiwBaAG6BNYB7gVSAMsA6gBqABuIF8ARIAuAB6AFtEggBuAF6AABmIB+AAlTwCfAFiBKgBuAEUiBuAG2AKcAhQIZYDLQB0ASZAPYBJNIoAGYp8BIT2bBsCXD/wNjCAAAAAElFTkSuQmCC') no-repeat center;
background-size: cover;
top: -150px;
}
#scoreBoard {
position: absolute;
top: 10px;
left: 10px;
color: #ecf0f1;
font-size: 20px;
z-index: 1000;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #e74c3c;
font-size: 36px;
display: none;
z-index: 1001;
}
#restartBtn {
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px 20px;
background: #27ae60;
color: #ecf0f1;
border: none;
border-radius: 5px;
cursor: pointer;
display: none;
z-index: 1001;
}
#restartBtn:hover {
background: #2ecc71;
}
</style>
</head>
<body>
<div id="gameArea">
<div class="road"></div>
<div id="playerCar"></div>
<div id="scoreBoard">Score: 0</div>
<div id="gameOver">Game Over</div>
<button id="restartBtn">Restart</button>
</div>
<script>
const gameArea = document.getElementById('gameArea');
const playerCar = document.getElementById('playerCar');
const scoreBoard = document.getElementById('scoreBoard');
const gameOver = document.getElementById('gameOver');
const restartBtn = document.getElementById('restartBtn');
const gameWidth = gameArea.clientWidth;
const gameHeight = gameArea.clientHeight;
const carWidth = playerCar.clientWidth;
const carHeight = playerCar.clientHeight;
let playerPos = {
x: (gameWidth / 2) - (carWidth / 2),
y: gameHeight - carHeight - 20
};
let keys = {
ArrowLeft: false,
ArrowRight: false
};
let obstacles = [];
let obstacleSpeed = 5;
let obstacleInterval = 2000; // milliseconds
let lastObstacleTime = Date.now();
let score = 0;
let gameRunning = true;
// Move player car
function movePlayer() {
if (keys.ArrowLeft && playerPos.x > 0) {
playerPos.x -= 5;
}
if (keys.ArrowRight && playerPos.x < (gameWidth - carWidth)) {
playerPos.x += 5;
}
playerCar.style.left = playerPos.x + 'px';
}
// Create obstacles
function createObstacle() {
const obstacle = document.createElement('div');
obstacle.classList.add('obstacle');
obstacle.style.left = Math.floor(Math.random() * (gameWidth - carWidth)) + 'px';
gameArea.appendChild(obstacle);
obstacles.push({
element: obstacle,
x: parseInt(obstacle.style.left),
y: -carHeight
});
}
// Move obstacles
function moveObstacles() {
obstacles.forEach((obstacle, index) => {
obstacle.y += obstacleSpeed;
obstacle.element.style.top = obstacle.y + 'px';
// Collision detection
if (collision(playerPos.x, playerPos.y, carWidth, carHeight,
obstacle.x, obstacle.y, carWidth, carHeight)) {
endGame();
}
// Remove off-screen obstacles
if (obstacle.y > gameHeight) {
gameArea.removeChild(obstacle.element);
obstacles.splice(index, 1);
score += 1;
scoreBoard.innerText = 'Score: ' + score;
}
});
}
// Collision detection function
function collision(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(x2 > x1 + w1 ||
x2 + w2 < x1 ||
y2 > y1 + h1 ||
y2 + h2 < y1);
}
// Game loop
function gameLoop() {
if (!gameRunning) return;
movePlayer();
moveObstacles();
// Generate new obstacles
if (Date.now() - lastObstacleTime > obstacleInterval) {
createObstacle();
lastObstacleTime = Date.now();
}
requestAnimationFrame(gameLoop);
}
// Handle key presses
window.addEventListener('keydown', function(e) {
if (e.code in keys) {
keys[e.code] = true;
}
});
window.addEventListener('keyup', function(e) {
if (e.code in keys) {
keys[e.code] = false;
}
});
// End game
function endGame() {
gameRunning = false;
gameOver.style.display = 'block';
restartBtn.style.display = 'block';
}
// Restart game
restartBtn.addEventListener('click', function() {
// Reset variables
obstacles.forEach(obstacle => gameArea.removeChild(obstacle.element));
obstacles = [];
playerPos.x = (gameWidth / 2) - (carWidth / 2);
playerCar.style.left = playerPos.x + 'px';
score = 0;
scoreBoard.innerText = 'Score: ' + score;
obstacleSpeed = 5;
obstacleInterval = 2000;
lastObstacleTime = Date.now();
gameOver.style.display = 'none';
restartBtn.style.display = 'none';
gameRunning = true;
gameLoop();
});
// Start the game
gameLoop();
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure:
- The
#gameArea div serves as the main container for the game.
- The
.road div creates a moving road effect using CSS animations.
- The
#playerCar represents the player's car.
- The
#scoreBoard displays the current score.
- The
#gameOver message and #restartBtn button appear when the game ends.
-
CSS Styling:
- The game area is centered on the screen with a dark background.
- The road is styled with a repeating linear gradient to simulate lane markings moving downward.
- The player's car and obstacles use base64-encoded images for simplicity and to keep everything self-contained.
- Responsive and visually appealing styles ensure the game looks good.
-
JavaScript Functionality:
- Player Movement: The player can move left and right using the arrow keys. The position is constrained within the game area.
- Obstacles: Obstacles are generated at random horizontal positions and move downward. If an obstacle goes off-screen, it's removed, and the score increases.
- Collision Detection: If the player's car collides with an obstacle, the game ends.
- Game Loop: Uses
requestAnimationFrame for smooth animations.
- Restart Mechanism: Allows the player to restart the game after a collision.
Customization
-
Images: The player's car and obstacles use simple base64-encoded images. You can replace these with your own images by updating the background property in the CSS. Make sure to encode your images in base64 or link them appropriately.
-
Difficulty: Adjust the obstacleSpeed and obstacleInterval variables to make the game easier or harder.
-
Styling: Feel free to enhance the CSS to add more details, such as additional road markings, backgrounds, or animations to improve the visual appeal.
How to Run
- Copy the Code: Copy the entire code above into a text editor.
- Save the File: Save the file with a
.html extension, for example, car_racing_game.html.
- Open in Browser: Double-click the saved file or open it using your preferred web browser.
- Play: Use the left and right arrow keys to move your car and avoid incoming obstacles. Your score increases as you dodge obstacles. If you collide with an obstacle, the game ends, and you can restart by clicking the "Restart" button.
Enjoy your game!