Java Car Race Game – Race to Victory

FREE Online Courses: Knowledge Awaits – Click for Free Access!

In this Java car race game project, we will be creating a classic car race game using java swing. The game will contain three cars, one of which will be the player’s car, and the other two cars will be the traffic cars which the player has to dodge.

The score of the player will increase as the traffic cars go out of the screen, and if the car hits another car, then the game will stop, and the game over message will be displayed.

About Java Car Race Game

By the end of this project, you will be able to create a simple car racing game using Java Swing library, implement basic game mechanics such as moving game objects, checking for collisions, and keeping score, and gain a fundamental understanding of how to use the graphics and event handling features of Java Swing.

Prerequisites for Car Race game using Java

  • Basic knowledge of Java programming language
  • Familiarity with object-oriented programming concepts like classes, inheritance, and polymorphism
  • Basic understanding of the Swing framework and its components
  • Understanding of event-driven programming and handling user input with listeners
  • Familiarity with 2D graphics and how to work with images in Java using the ImageIO class
  • Familiarity with Eclipse IDE.

Download Java Car Race Game Project

Please download the source code of Java Car Race Game Project: Java Car Race game Project Code

Steps to Create Car Race Game Project Using Java

Following are the steps for developing the Java Car Race game Project:

Step 1: Create the SourcePictures folder to contain the game assets
Step 2: Creating the necessary classes
Step 3:Writing the code for the classes

Step 1: Create the SourcePictures folder to contain the game assets

After creating a new Java project in Eclipse, follow this:

Right click on the project folder and select the option New, then Folder and Name the folder SourcePictures. Now move all of your images into that folder.

Step 2: Creating the necessary classes

We will be creating four classes, namely.

GameMap: It will initialize the map or the background of the frame, like drawing grass and a highway onto the frame. This class will extend the JPanel class.

Car: This class will initialize the cars and the game logic of collision, movements and the game boundaries. It will extend the GameMap class and implement the ActionListener and KeyListener interfaces.

GameFrame: This class will extend the JFrame class, will provide the frame for our application, and will have a main method to initialize the frame and launch the game.

Step 3: Writing the code for the classes

For GameMap.java the code is:

package org.ProjectGurukul;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GameMap extends JPanel {
    private BufferedImage grass;
    private BufferedImage highway;
    private JLabel scoreLabel = new JLabel("Score");

    
    
    public BufferedImage getGrass() {
        return grass;
    }

    public BufferedImage getHighway() {
        return highway;
    }


    public void drawApp() {
    	try {
            grass = ImageIO.read(new File("SourcePictures/grass_tile.png"));
            highway = ImageIO.read(new File("SourcePictures/highway.png"));
        } catch (IOException ex) {
            System.out.println("Image not found");
            System.exit(0);
        }

    }

    public void paintComponent(Graphics g) {
        drawApp();
        for (int i = 0; i < 150; i+=32) {
        	for (int j = 0; j < 1000; j+=32) {
        		g.drawImage(getGrass(), i, j, null);
                g.drawImage(getGrass(), 620+i, j, null);
            }
        	
        }
        g.drawImage(getGrass(), 0, 0, null);
        g.drawImage(getGrass(), 620, 0, null);
        
        g.drawImage(getHighway(),150, 0, null);
    }
}

In this class, we have created the background or the Map of the game the drawApp() method loads the images of the grass and the highway, and the paintComponent method paints the frame with the grass and the highway.

For Car.java the code is:

package org.ProjectGurukul;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Car extends GameMap implements ActionListener, KeyListener {

    private Timer t;

    private BufferedImage playerCar;
    private BufferedImage secondCar;
    private BufferedImage thirdCar;
    private int playerCarX = 980;
    private int playerCarY = 730;
    private int secondCarX = 150;
    private int secondCarY = 400;
    private int thirdCarX = 400;
    private int thirdCarY = 0;


    private int speed = 2;

    private int velocityX = 0;
    private int velocityY = 0;
    
    private int score =0;

    public Car() {
        super.setDoubleBuffered(true);
        t = new javax.swing.Timer(0, this);
        JOptionPane.showMessageDialog(this, "Press Ok to start the game","Car Race",JOptionPane.INFORMATION_MESSAGE);
        t.start();
        this.addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    public Timer getTimer() {
        return t;
    }

    public int getPlayerCarX() {
        return playerCarX;
    }

    public int getPlayerCarY() {
        return playerCarY;
    }

    public int getSecondCarX() {
        return secondCarX;
    }

    public int getSecondCarY() {
        return secondCarY;
    }

    public int getThirdCarX() {
        return thirdCarX;
    }

    public int getThirdCarY() {
        return thirdCarY;
    }


    public BufferedImage getPlayerCar() {
        return playerCar;
    }


    public BufferedImage getSecondCar() {
        return secondCar;
    }


    public BufferedImage getThirdCar() {
        return thirdCar;
    }


    public void OtherCars() {
        try {
            playerCar = ImageIO.read(new File("SourcePictures/PlayerCar.png"));
            secondCar = ImageIO.read(new File("SourcePictures/secondCar.png"));
            thirdCar = ImageIO.read(new File("SourcePictures/thirdCar.png"));
        } catch (IOException ex) {
            System.out.println("Image not found");
        }

    }

    public void paintComponent(Graphics g) {
        OtherCars();
        super.paintComponent(g);
        g.drawImage(getPlayerCar(), getPlayerCarX(), getPlayerCarY(), null);
        g.drawImage(getSecondCar(), getSecondCarX(), getSecondCarY(), null);
        g.drawImage(getThirdCar(), getThirdCarX(), getThirdCarY(), null);
        
        g.setColor(Color.white);
        g.setFont( new Font("Arial",Font.BOLD, 40));
        g.drawString("Score: "+score, 300, 320);
        
        

                
        if(!getTimer().isRunning()) {
             	g.setColor(Color.RED);
                g.setFont( new Font("Arial",Font.BOLD, 80));
                g.drawString("Game Over", 400, 500);
        }
    }

    
    public void move() {
        secondCarY = secondCarY + speed;
        thirdCarY = thirdCarY + speed;
        if (secondCarY == 920) {
            secondCarY = -250;
            score++;
        }
        if (thirdCarY == 920) {
            thirdCarY = -250;
            score++;
        }
        if(checkCollision()) {
        	getTimer().stop();
        }
        
        repaint();
        

    }

//    Method to check the collision of cars
    public boolean checkCollision() {
        Rectangle playerRect = new Rectangle(playerCarX+65, playerCarY, getPlayerCar().getWidth()-130, getPlayerCar().getHeight());
        Rectangle secondRect = new Rectangle(secondCarX, secondCarY, getSecondCar().getWidth()-75, getSecondCar().getHeight());
        Rectangle thirdRect = new Rectangle(thirdCarX+65, thirdCarY, getThirdCar().getWidth()-100, getThirdCar().getHeight());
        

        if (playerRect.intersects(secondRect) || playerRect.intersects(thirdRect)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        int c = e.getKeyCode();
        if (c == KeyEvent.VK_LEFT) {
            velocityX = -35;
            velocityY = 0;
        }
        if (c == KeyEvent.VK_UP) {
            velocityX = 0;
            velocityY = -35;
        }
        if (c == KeyEvent.VK_RIGHT) {
            velocityX = 35;
            velocityY = 0;
        }
        if (c == KeyEvent.VK_DOWN) {
            velocityX = 0;
            velocityY = 35;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {}
//Method to limit the car's movement to the road only
    public void limit() {
        if (playerCarX < 100) {
            velocityX = 0;
            playerCarX = 100;
        }
        if (playerCarX > 450) {
            velocityX = 0;
            playerCarX = 450;
        }
        if (playerCarY < 0) {
            velocityY = 0;
            playerCarY = 0;
        }
        if (playerCarY > 780) {
            velocityY = 0;
            playerCarY = 780;
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        OtherCars();
    	move();
        limit();
        this.addKeyListener(this);
        playerCarX = playerCarX + velocityX;
        velocityX = 0;
        playerCarY = playerCarY + velocityY;
        velocityY = 0;
        repaint();
    }
}

The Car.java class is the class which loads our car images and implements the logic for the game. Like as crash detection and score updation and the basic logic for making the cars move.

For collision, the method checkCollision() is implemented. It creates a rectangle around the cars and checks if any of the rectangles intersect with each other and returns true if they intersect; otherwise returns false. By this method, we can detect if the Player’s car has hit another car.

There are also other methods like limit() and move() to limit the movement of the car into a limited field like the highway.Also, we have overridden the keyPressed() method to move the car in the respective direction if the user pressed any of the arrow keys.

For the GameFrame.java class the code is :

package org.ProjectGurukul;

import javax.swing.*;

public class GameFrame extends JFrame {

    public GameFrame() {
        super.setTitle("Car Race");
        super.setBounds(0, 0, 1950, 1035);
        super.add(new Car());
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        super.setVisible(true);
    }
    public static void main(String[] args) {
        new GameFrame();
    }
}

This class creates a frame which will hold the components of our game.

Java Car Race Game Output

car race game start output

car race game over output

Summary:

In this project, we have created a car race game using Java swing library, which has three cars, and the player has to dodge the traffic cars in order to score points. We learnt how we could implement basic game mechanics such as movement and checking collisions. We have also learned how we can use the images in our game and how we can move the objects and perform operations based on the movements of the images.

If you are Happy with ProjectGurukul, do not forget to make us happy with your positive feedback on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *