Ayman
Ayman
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Open World Car Game</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
canvas {
display: block;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.5);
color: white;
padding: 10px;
border-radius: 5px;
font-size: 14px;
}
.car {
position: absolute;
width: 50px;
height: 100px;
background: red;
border-radius: 5px;
transform-origin: center;
}
.ai-car {
background: blue;
}
#map {
position: absolute;
top: 0;
left: 0;
width: 5000px;
height: 5000px;
background: url('https://i.imgur.com/3fGbZ6G.png') repeat;
}
</style>
</head>
<body>
<div id="ui">Speed: <span id="speed">0</span> km/h</div>
<div id="map"></div>
<div class="car" id="player-car" style="left: 250px; top: 250px;"></div>
<script>
const playerCar = document.getElementById("player-car");
const speedDisplay = document.getElementById("speed");
const map = document.getElementById("map");
let speed = 0;
let angle = 0;
let x = 250, y = 250;
const maxSpeed = 10;
const acceleration = 0.2;
const deceleration = 0.1;
const turnSpeed = 3;
const keys = {
ArrowUp: false,
ArrowDown: false,
ArrowLeft: false,
ArrowRight: false,
};
function updatePlayerCar() {
if (keys.ArrowUp) speed = Math.min(speed + acceleration, maxSpeed);
else if (keys.ArrowDown) speed = Math.max(speed - acceleration, -maxSpeed /
2);
else speed = Math.abs(speed) > deceleration ? speed - Math.sign(speed) *
deceleration : 0;
function createAICar() {
const aiCar = document.createElement("div");
aiCar.classList.add("car", "ai-car");
aiCar.style.left = `${Math.random() * 5000}px`;
aiCar.style.top = `${Math.random() * 5000}px`;
map.appendChild(aiCar);
return {
element: aiCar,
x: parseFloat(aiCar.style.left),
y: parseFloat(aiCar.style.top),
speed: Math.random() * 5 + 2,
};
}
function updateAICars() {
aiCars.forEach((car) => {
car.y += car.speed;
function gameLoop() {
updatePlayerCar();
updateAICars();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>