Skip to main content

Creating a Simple Car Racing Game with HTML, CSS, Javascript


In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code!

HTML Structure

The HTML structure consists of a game area that contains the road, player car, opponent car, and score display:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Racing Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="gameArea">
        <div class="road"></div>
        <div class="playerCar"></div>
        <div class="opponentCar"></div>
        <div class="score">Score: 0</div>
    </div>
    <script src="script.js"></script>
</body>
</html>
    

CSS Styling

The CSS styles define the appearance of the game area, road, and cars. We also add animations to make the road scroll smoothly:

body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    background: #ffff0b;
    font-family: Arial, sans-serif;
}

.gameArea {
    position: relative;
    width: 100vw;
    height: 100vh;
    background: #05ff71;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.road {
    position: absolute;
    top: 0;
    width: 500px;
    height: 200vh;
    background: linear-gradient(#333 25%, #555 25%, #555 50%, #333 50%);
    background-size: 100% 100px;
    animation: scrollRoad 3s linear infinite;
}

@keyframes scrollRoad {
    0% { top: -100vh; }
    100% { top: 0; }
}

.playerCar, .opponentCar {
    position: absolute;
    width: 50px;
    height: 100px;
    background: red;
    border-radius: 10px;
}

.playerCar {
    bottom: 20px;
    left: calc(50% - 25px);
    background-color: red;
    background-size: contain;
}

.opponentCar {
    top: 0;
    left: calc(50% - 25px);
    background: rgb(0, 255, 255);
    background-size: contain;
}

.score {
    position: absolute;
    top: 20px;
    left: 20px;
    font-size: 24px;
    color: white;
}
    

JavaScript Functionality

The JavaScript code handles the movement of the cars, collision detection, and score updating. The player can use the arrow keys to move the car left and right:

document.addEventListener("DOMContentLoaded", () => {
  const playerCar = document.querySelector(".playerCar");
  const opponentCar = document.querySelector(".opponentCar");
  const road = document.querySelector(".road");
  const scoreDisplay = document.querySelector(".score");

  let playerCarLeft = road.offsetLeft + road.offsetWidth / 2 - 25;
  let opponentCarTop = 0;
  let score = 0;
  let playerCarSpeed = 10;
  let opponentCarSpeed = 5;
  const roadLeftBoundary = road.offsetLeft;
  const roadRightBoundary = roadLeftBoundary + road.offsetWidth;

  function moveOpponentCar() {
    opponentCarTop += opponentCarSpeed;
    if (opponentCarTop > window.innerHeight) {
      opponentCarTop = -100;
      opponentCar.style.left = `${
        Math.random() * (road.offsetWidth - 50) + roadLeftBoundary
      }px`;
      score++;
      scoreDisplay.textContent = `Score: ${score}`;
      opponentCarSpeed = 5 + Math.floor(score / 5);
    }
    opponentCar.style.top = `${opponentCarTop}px`;
  }

  function movePlayerCar(e) {
    if (e.key === "ArrowLeft") {
      playerCarLeft -= playerCarSpeed;
      if (playerCarLeft < roadLeftBoundary) playerCarLeft = roadLeftBoundary;
    } else if (e.key === "ArrowRight") {
      playerCarLeft += playerCarSpeed;
      if (playerCarLeft > roadRightBoundary - 50)
        playerCarLeft = roadRightBoundary - 50;
    }
    playerCar.style.left = `${playerCarLeft}px`;
  }

  function detectCollision() {
    const playerCarRect = playerCar.getBoundingClientRect();
    const opponentCarRect = opponentCar.getBoundingClientRect();

    return !(
      playerCarRect.bottom < opponentCarRect.top ||
      playerCarRect.top > opponentCarRect.bottom ||
      playerCarRect.right < opponentCarRect.left ||
      playerCarRect.left > opponentCarRect.right
    );
  }

  function gameLoop() {
    moveOpponentCar();
    if (detectCollision()) {
      alert(`Game Over! Your final score is ${score}`);
      window.location.reload();
    } else {
      requestAnimationFrame(gameLoop);
    }
  }

  document.addEventListener("keydown", movePlayerCar);
  gameLoop();
});
    

This basic game is a great way to practice your HTML, CSS, and JavaScript skills. Feel free to enhance it with more features and improve its functionality!

Comments

Popular posts from this blog

Pac-Man Game in HTML, CSS, and JavaScript

In this tutorial, we will create a classic Pac-Man game using HTML, CSS, and JavaScript. Follow the steps to build the game board, Pac-Man, and implement the game logic. HTML Structure First, we need to set up the HTML structure for our Pac-Man game. This includes the game board and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pac-Man Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Pac-Man Game</h1> <div id="game-board"></div> <div id="score-display">Score: 0</div> <script src="script.js"></script> </body> </html> CSS Styling Next, we add some CSS to style the game board, walls, dot...

Creating an Interactive Tic Tac Toe Game

In this tutorial, we'll walk through the steps to create a dynamic Tic Tac Toe game using HTML, CSS, and JavaScript. This classic game is a great way to practice your web development skills and learn more about interactive web applications. HTML Structure We'll start with the HTML structure, which includes the game board, a reset button, and a status display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Tic Tac Toe</h1> <div id="board" class="board"></div> <button id="reset">Reset Game</button> <div id=...