Meta Description" name="description" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Car Racing Game</title>
<style>
body{
margin:0;
overflow:hidden;
background:#222;
}
canvas{
display:block;
margin:auto;
background:#555;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="700"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
let car = {
x:170,
y:600,
width:60,
height:100,
speed:7
};
let enemy = {
x:170,
y:-100,
width:60,
height:100,
speed:5
};
let score = 0;
document.addEventListener("keydown",e=>{
if(e.key==="ArrowLeft" && car.x>20) car.x-=car.speed*5;
if(e.key==="ArrowRight" && car.x<320) car.x+=car.speed*5;
});
function drawRoad(){
ctx.fillStyle="#444";
ctx.fillRect(0,0,400,700);
ctx.strokeStyle="white";
ctx.lineWidth=5;
for(let i=0;i<700;i+=40){
ctx.beginPath();
ctx.moveTo(200,i);
ctx.lineTo(200,i+20);
ctx.stroke();
}
}
function drawCar(x,y,color){
ctx.fillStyle=color;
ctx.fillRect(x,y,60,100);
}
function update(){
enemy.y+=enemy.speed;
if(enemy.y>700){
enemy.y=-100;
enemy.x=Math.random()*300+20;
score++;
}
if(
car.x<enemy.x+60 &&
car.x+60>enemy.x &&
car.y<enemy.y+100 &&
car.y+100>enemy.y
){
alert("Game Over! Score: "+score);
location.reload();
}
}
function game(){
drawRoad();
drawCar(car.x,car.y,"red");
drawCar(enemy.x,enemy.y,"blue");
ctx.fillStyle="white";
ctx.font="25px Arial";
ctx.fillText("Score: "+score,20,40);
update();
requestAnimationFrame(game);
}
game();
</script>
</body>
</html>1
1
2KB
2KB
82.0ms
100.0ms
82.0ms