0% found this document useful (0 votes)
52 views28 pages

Project File Edited

The Car Racing Game is a Java-based 2D arcade game where players navigate a car through obstacles to achieve the highest score. It features dynamic difficulty, sound integration, and a high score tracking system, utilizing Java's Swing framework for the graphical interface. The project showcases key programming concepts such as object-oriented design, event-driven programming, and collision detection, offering a foundation for future enhancements.

Uploaded by

yashyadav3602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views28 pages

Project File Edited

The Car Racing Game is a Java-based 2D arcade game where players navigate a car through obstacles to achieve the highest score. It features dynamic difficulty, sound integration, and a high score tracking system, utilizing Java's Swing framework for the graphical interface. The project showcases key programming concepts such as object-oriented design, event-driven programming, and collision detection, offering a foundation for future enhancements.

Uploaded by

yashyadav3602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

CAR RACING GAME

A. PROJECT. REPORT

Submitted by

Yash Yadav (RA2111003030450)

Undertheguidanceof

MR.HIMANSHU Assistant. Professor


(Department of Computer Science & Engineering) in

partial fulfillment for the award of the degree

of
BACHELOR OF TECHNOLOGY
in

COMPUTER SCIENCE & ENGINEERING


of

FACULTY OF ENGINEERING AND TECHNOLOGY

SRM INSTITUTE OF SCIENCE & TECHNOLOGY,NCRCAMPUS


May 2025
SRM INSTITUTE OF SCIENCE &
TECHNOLOGY
(Under Section 3 of UGC Act,1956)

BONAFIDE CERTIFICATE

Certified that this project report titled “Car Racing Game ” is the
bonafidework of Yash Yadav RA2111003030450 who carried out the project work
under my supervision. Certified further, that to the best of my knowledge the
work reported herein does not form any other project report onthe basis of which
a degree or award was conferred.

SIGNATURE SIGNATURE

MR.HIMANSHU DR. AVNEESH VASHISTHA


AssistantProfessor HEAD OF THE DEPARTMENT
Department of Computer Science Department of Computer Science
and Engineering and Engineering
We would like to express our deepest gratitude to our teacher, Mr. Himanshu for his
valuable guidance, consistent encouragement, personal caring, timely help
andprovidinguswithanexcellentatmospherefordoingresearch.Allthroughthework, in
spite of his busy schedule, he has extended cheerful and cordial support to us for
completing this research work.

Table of contents
1.ACKNOWLEDGEMENTS.
3
2.ABSTRACT.
5
3. INTRODUCTION.
6
4.LITERATURESURVEY.
7
5.SYSTEMANALYSIS.
7-8
6.SYSTEMDESIGN.
9
7.CODING,TESTING
10
8.LIMITATION &
FUTURE ENHANCEMENIS
23
9.CONCLUSION
24

REFERENCS
Abstract
The Car Racing Game is a Java-based 2D arcade game designed to
provide an engaging, interactive experience where players control a car
and navigate through an obstacle-filled road. The primary objective of the
game is to avoid randomly generated obstacles while accumulating points
as the player survives longer. The game features increasing difficulty as
the player progresses, with obstacles appearing more frequently and
moving faster. The graphical user interface (GUI) is built using Java’s
Swing framework, while real-time game events, such as car movement
and obstacle collision, are managed using a Timer and KeyListener.

This project integrates sound effects using the javax.sound.sampled


library to enhance the gameplay, including background music and a
collision sound upon game over. The game tracks the player's current
score and maintains a persistent high score using Java’s Preferences
API, allowing the highest score to be saved across game sessions. The
difficulty dynamically increases as the score rises, ensuring the game
remains challenging and engaging over time. The player can pause and
resume the game using keyboard inputs, and the game ends when the
player collides with an obstacle, providing a restart option for continuous
gameplay.

The project demonstrates the application of key programming concepts


such as object-oriented design, event-driven programming, collision
detection, and multimedia integration. The use of Java’s Rectangle class
simplifies collision handling, while the KeyAdapter and Timer enable
real-time input and game state updates. This project offers valuable
learning opportunities in game development, particularly in designing
responsive interfaces, managing game loops, and incorporating user
feedback mechanisms. The modular design also allows for future
improvements, such as additional game modes, power-ups, and enhanced
graphics, providing a strong foundation for further development.
1.INTRODUCTION
The Car Racing Game is a 2D arcade-style game developed in Java,
where players control a car navigating through a road filled with obstacles.
The objective is simple yet challenging: avoid collisions with the obstacles
while maintaining control of the car and achieving the highest possible
score. Inspired by the mechanics of classic racing games like "Road
Fighter" and "Out Run," this project offers an engaging gameplay
experience through its dynamic obstacle generation and increasing
difficulty.

Arcade games have long been popular for their straightforward mechanics,
fast-paced action, and emphasis on high scores. The Car Racing Game
draws on these elements by combining intuitive controls with progressively
more difficult gameplay. Players can move the car left or right using the
keyboard's arrow keys, while the obstacles, represented as yellow blocks,
move downward at varying speeds. The longer the player survives, the
higher the score, with the challenge increasing as obstacles appear more
frequently and move faster.

The game is developed using Java’s Swing library for graphical


rendering, offering a simple yet effective visual interface. The player’s car,
obstacles, and road are all drawn dynamically, and the game screen is
updated in real-time using a Timer. Collision detection is handled
using Java’s Rectangle class, ensuring that any interaction
between the car and obstacles results in an immediate game-
over scenario. Upon collision, the player has the option to
restart the game, with the high score tracked and saved across
sessions using Java’s Preferences API.

One of the key features of the game is its sound integration.


Background music plays continuously during gameplay, and a
sound effect is triggered upon collision, enhancing the overall
user experience. The game also includes a pause-and-resume
function, allowing players to temporarily halt the game and
resume at any point. This feature is especially useful as the
game becomes more intense with increasing difficulty levels.
2. Literature Survey
Arcade racing games have been a popular genre in the gaming
world since the 1980s, with titles like "Road Fighter" and "Out
Run" becoming iconic examples. These games are known for
their straightforward mechanics, where players control a vehicle
and avoid obstacles while attempting to achieve the highest
score possible. The simplicity of these games has made them a
popular choice for beginner programming projects, especially in
the realm of 2D game development.

In the academic context, many Java-based game development


projects draw from the principles of arcade gaming. The use of
Java’s Swing library for graphical interfaces, along with
KeyListener for user input and
Timer for game loops, has proven to be an effective approach for
implementing real-time gameplay. Furthermore, collision
detection using Java’s Rectangle class is a commonly employed
method in many game projects, allowing developers to manage
interactions between the player and obstacles or enemies.

Existing literature on game development emphasizes the


importance of a smooth game loop, responsive user input, and
the integration of sound to enhance the player’s experience.
Sound effects are often used to provide feedback, while
background music maintains the game's immersive quality. By
studying these principles, we were able to design a car racing
game that balances simplicity in gameplay with increasing
difficulty and sound integration, providing a comprehensive
gaming experience.
3. Methodology Used
The Car Racing Game was developed using object-oriented
programming (OOP) principles in Java. The project’s
architecture is modular, with separate classes handling the
player’s car, the obstacles, and the game logic. Key components
of the methodology include:

1. Game Loop: A Timer object is used to control the game


loop, which updates the positions of the car and obstacles
every 20 milliseconds. This ensures smooth and continuous
gameplay.
2. Collision Detection: Java’s Rectangle class is used to
handle collision detection between the car and obstacles.
When the player’s car intersects with an obstacle, the game
ends, and a collision sound is played.
3. User Input: The player controls the car using the left and
right arrow keys. A KeyAdapter class captures the keyboard
input and moves the car accordingly.
4. Obstacle Generation: Obstacles are randomly generated
at the top of the screen and move down at a fixed speed. As
the player’s score increases, the speed and frequency of the
obstacles increase, making the game progressively more
difficult.
5. Sound Integration: Background music plays continuously
during gameplay, using the javax.sound.sampled library. A
collision sound is triggered when the game ends, adding
auditory feedback to the player’s experience.
6. High Score Persistence: The game uses Java’s
Preferences API to store the high score across multiple
game sessions. This encourages players to improve their
score and adds a competitive element to the game.
4.Hardware And Software Requirements

1. Processor: A modern processor such as an Intel Core i3 or


AMD Ryzen 3 should suffice. While the game doesn’t
require significant computational power, it benefits from a
multi-core processor to handle the game loop, rendering,
and sound processing concurrently.

2. RAM: At least 4 GB of RAM is recommended. Java itself,


along with an Integrated Development Environment (IDE)
like IntelliJ IDEA or Eclipse, can be resource-intensive,
especially during development. The game, being
lightweight, only consumes a minimal amount of RAM while
running, but ample memory ensures that development and
testing processes run smoothly without lag.

3. Storage: A minimum of 500 MB of free disk space is


required. While the game files themselves are small,
sufficient space is necessary for Java libraries, the IDE, and
any additional assets (like audio files). Storing project
backups and version control repositories would also benefit
from some extra space.

4. Graphics: The game relies on simple 2D graphics and does


not require a dedicated graphics card. Integrated graphics,
such as Intel UHD or AMD Vega, are more than enough to
render the game's elements. Higher-end GPUs, such as
those found in gaming laptops or desktops, would not be
necessary, as Java’s Swing framework is optimized for basic
graphics rendering.
5.System Design

The Car Racing Game follows a modular system design that


separates the core components for flexibility and scalability:

1. Game Architecture:

Car Class: This class represents the player’s car,


handling its movement and detecting collisions with
obstacles.

Obstacle Class: Obstacles are randomly generated


and move down the screen at a speed that increases as
the game progresses.

Game Loop: The game loop continuously updates the


car’s position, moves obstacles, and checks for
collisions.

2. UI Design: The game uses Swing to create a simple but


functional user interface. The road is represented by a gray
rectangle, the player’s car is a red rectangle, and obstacles
are yellow rectangles that move down the road.
3. Collision Detection: Using the Rectangle class, the game
checks for intersections between the player’s car and any
obstacle. If a collision is detected, the game stops, and a
“Game Over” message is displayed.
4. Sound Design: Background music plays throughout the
game, and a distinct collision sound plays when the game
ends. This sound integration improves the overall user
experience.
6. Coding and Testing
KeyComponentsoftheCode
1. Main Game Loop:
0 The game loop is the core of the game, handling real-
time updates to the game state. It is implemented
using Java’s Timer class, which triggers an
ActionListener every 20 milliseconds to refresh the
screen and update the game logic.
○ Within each iteration of the loop, the positions of the
player’s car and obstacles are updated, collision
detection is performed, and the score is incremented
as the player survives longer.
2. Player Movement:
0 The car is controlled using keyboard input, with the
left and right arrow keys moving the car horizontally
across the screen. Java’s KeyListener interface is
implemented using a KeyAdapter class, which captures
the arrow key events and adjusts the car’s position
accordingly.
○ Boundary checks ensure that the car does not move
outside the road (the bounds of the game screen). The
car's movement is restricted to the center of the
screen, avoiding areas outside the road.
3. Obstacle Generation and Movement:
0 Obstacles are represented as yellow rectangles and
are randomly generated at the top of the screen. The
obstacle’s horizontal position is determined using a
random number generator, ensuring variability in their
placement.
○ Obstacles continuously move downward at a speed
that increases as the game progresses. When an
obstacle moves off the screen, it is re-generated at a
new random position at the top of the screen,
maintaining a continuous flow of obstacles.
4. Collision Detection:
0 Collision detection is handled using Java’s Rectangle
class.
The player’s car and each obstacle are represented as rectangles.
7.Results
The Car Racing Game was successfully developed and
performs as intended. Players can control the car smoothly using
the keyboard, avoiding obstacles and accumulating points as
they survive longer. The game becomes more challenging as the
player progresses, with the speed and frequency of obstacles
increasing. The high score system functions correctly, saving the
player’s best score between game sessions.

The sound effects, including background music and collision


sounds, significantly enhance the gameplay experience. The
game responds well to pause-and-resume commands, allowing
players to stop the game at any point and continue from where
they left off.
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.File;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.Clip;

import java.util.prefs.Preferences;

public class CarRacingGame extends JPanel implements ActionListener {

private Timer timer;

private int carX = 220, carY = 600;


private int obstacleX = (int) (Math.random() * 400), obstacleY = -50;
private int score = 0, highScore = 0;

private boolean gameOver = false, isPaused = false, showInstructions = true;

private Clip backgroundMusic, collisionSound;

private Preferences preferences =


Preferences.userRoot().node(this.getClass().getName());

private int difficultyLevel = 1;

public CarRacingGame() {

this.setPreferredSize(new Dimension(500, 700));

this.setBackground(Color.DARK_GRAY);

this.setFocusable(true);

this.addKeyListener(new CarKeyAdapter());

highScore = preferences.getInt("HighScore", 0);

timer = new Timer(20, this);

timer.start();

playBackgroundMusic("background.wav");

@Override

protected void paintComponent(Graphics g) {


super.paintComponent(g);

if (showInstructions) {
drawInstructions(g);

} else {

g.setColor(Color.GRAY);

g.fillRect(150, 0, 200, 700);

g.setColor(Color.WHITE);

for (int i = 0; i < 700; i += 50) {

g.fillRect(245, i, 10, 30);

g.setColor(Color.RED);

g.fillRect(carX, carY, 50, 100);

g.setColor(Color.YELLOW);

g.fillRect(obstacleX, obstacleY, 50, 100);

g.setColor(Color.WHITE);

g.setFont(new Font("Arial", Font.BOLD, 20));

g.drawString("Score: " + score, 20, 30);

g.drawString("High Score: " + highScore, 300, 30);


if (gameOver) {

g.setFont(new Font("Arial", Font.BOLD, 50));

g.setColor(Color.RED);

g.drawString("Game Over", 120, 350);

g.setFont(new Font("Arial", Font.PLAIN, 20));

g.drawString("Press 'R' to Restart", 150, 400);

stopMusic();

} else if (isPaused) {

g.setFont(new Font("Arial", Font.BOLD, 50));

g.setColor(Color.YELLOW);

g.drawString("Paused", 170, 350);

g.setFont(new Font("Arial", Font.PLAIN, 20));

g.drawString("Press 'P' to Resume", 160, 400);

private void drawInstructions(Graphics g) {

g.setColor(Color.WHITE);

g.setFont(new Font("Arial", Font.BOLD, 30));

g.drawString("Instructions", 150, 50);

g.setFont(new Font("Arial", Font.PLAIN, 20));

g.drawString("1. Use Left Arrow key to move left.", 100, 150);

g.drawString("2. Use Right Arrow key to move right.", 100, 200);


g.drawString("3. Avoid the yellow obstacles.", 100, 250);

g.drawString("4. Press 'P' to Pause/Resume.", 100, 300);

g.drawString("5. Press 'R' to Restart after Game Over.", 100, 350);

g.drawString("Press any key to start the game.", 100, 450);

@Override

public void actionPerformed(ActionEvent e) {

if (!gameOver && !isPaused) {

obstacleY += 10 * difficultyLevel;

if (score % 100 == 0 && score != 0) {

difficultyLevel++;

if (obstacleY > 700) {

obstacleY = -50;

obstacleX = (int) (Math.random() * 400);

score += 10; // Increase score for avoiding the obstacle

if (new Rectangle(carX, carY, 50, 100).intersects(new


Rectangle(obstacleX, obstacleY, 50, 100))) {
gameOver = true;

playCollisionSound("collision.wav");

if (score > highScore) {

highScore = score;

preferences.putInt("HighScore", highScore);

repaint();

private class CarKeyAdapter extends KeyAdapter {

@Override

public void keyPressed(KeyEvent e) {

if (showInstructions) {

showInstructions = false;

return;

if (!gameOver) {

int key = e.getKeyCode();

if (key == KeyEvent.VK_LEFT && carX > 150) {


carX -= 20; // Move car left

}
if (key == KeyEvent.VK_RIGHT && carX < 300) {

carX += 20;

if (key == KeyEvent.VK_P) {

isPaused = !isPaused;

if (isPaused) {

timer.stop();

} else {

timer.start();

repaint();

if (gameOver && e.getKeyCode() == KeyEvent.VK_R) {

restartGame();

private void restartGame() {


gameOver = false;

score = 0;
carX = 220;

carY = 600;

obstacleX = (int) (Math.random() * 400);

obstacleY = -50;

difficultyLevel = 1;

playBackgroundMusic("background.wav");

timer.start();

repaint();

private void playBackgroundMusic(String soundFile) {

try {

backgroundMusic = AudioSystem.getClip();

backgroundMusic.open(AudioSystem.getAudioInputStream(new
File(soundFile)));

backgroundMusic.loop(Clip.LOOP_CONTINUOUSLY);

} catch (Exception e) {

e.printStackTrace();

private void playCollisionSound(String soundFile) {


try {

collisionSound = AudioSystem.getClip();

collisionSound.open(AudioSystem.getAudioInputStream(new
File(soundFile)));

collisionSound.start();

} catch (Exception e) {

e.printStackTrace();

private void stopMusic() {

if (backgroundMusic != null && backgroundMusic.isRunning()) {

backgroundMusic.stop();

public static void main(String[] args) {

JFrame frame = new JFrame("Enhanced Car Racing Game");

CarRacingGame game = new CarRacingGame();

frame.add(game);

frame.pack();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

frame.setLocationRelativeTo(null);

}
9. Advantages
1. Educational Value: The project provides a hands-on
introduction to various key Java programming concepts,
including object-oriented programming (OOP), event-driven
programming, collision detection, real-time game loops, and
graphical rendering using Java's Swing framework. It also
introduces sound handling through the javax.sound.sampled
library, giving developers a comprehensive learning
experience in multimedia application development.

2. Modular Code Design:

The game is designed with modular components, such as


separate classes for the car, obstacles, sound, and game
logic. This separation of concerns allows for easy
modification and future enhancements. New features or
changes (e.g., different game modes or additional power-
ups) can be implemented without needing to overhaul the
entire codebase.

3. Real-time Event Handling:


0 zThe game makes excellent use of real-time event
handling. The player’s inputs, like car movement, are
processed instantly through keyboard events
(KeyListener), and the game state is updated every few
milliseconds using a Timer. This results in smooth and
responsive gameplay.
4. Difficulty Scaling:
0 The game includes a dynamic difficulty system, which
gradually increases the speed and frequency of
obstacles as the player’s score increases. This ensures
that the game remains engaging and challenging for
players as they progress, enhancing replayability.
5. Sound Integration:
0 The integration of background music and sound
effects creates a more immersive and enjoyable
gaming experience.
10. Conclusion
The Car Racing Game successfully demonstrates the
application of key Java programming concepts in a real-time,
interactive game environment. The project combines object-
oriented design, event handling, graphical rendering, and
multimedia integration to create an engaging and functional 2D
arcade game. Through the development process, we explored
essential techniques like using Java's Swing framework for the
user interface, implementing real-time game loops with Timer,
and handling collision detection with the Rectangle class.

One of the game’s highlights is the seamless integration of


sound effects and background music using the
javax.sound.sampled library, which greatly enhances the player
experience. The inclusion of a high score tracking system,
managed via Java’s Preferences API, adds a competitive element
to the game, encouraging players to beat their previous best
performances. Additionally, the dynamic difficulty scaling
ensures that the game remains challenging and engaging as the
player progresses, preventing it from becoming monotonous.
11.Limitations
● Basic Graphics: The game uses simple 2D graphics with
limited visual effects. More detailed graphics and
animations could improve the user experience.
● Single Mode: Currently, the game has only one mode of
play.
Adding different levels, modes, or multiplayer options could
enhance the gameplay.
● No Power-ups: The game does not include power-ups or
bonuses, which could add variety to the gameplay and make
it more engaging.
● Fixed Speed: The game speed increases with difficulty, but
there are no dynamic adjustments to the car’s speed or
abilities, which could offer more strategic gameplay

Single Game Mode: The game currently features only one


mode, limiting replayability. Players may desire different
challenges or objectives, such as time trials, racing against
a clock, or competing against AI opponents. Adding
multiple modes could enhance the overall gaming
experience.

● Players cannot customize their cars, obstacles, or game


environment. Allowing players to select different car
designs, colors, or skins could significantly improve the
game's personal appeal and user experience.
12. References
1. Java Documentation: https://docs.oracle.com/javase/
2. Oracle’s Java 2D API:
https://docs.oracle.com/javase/tutorial/2d/
3. Game Loop in Java:
https://www.tutorialspoint.com/game-loop-in-java
4. Handling Key Events:
https://www.geeksforgeeks.org/keylistener-interface-java/
5. Sound Integration in Java:
https://docs.oracle.com/javase/tutorial/sound/
6. Collision Detection Techniques:
https://www.gamedevelopment.tutsplus.com/tutorials/
collision-dete ction-using-java/
7. Java Swing GUI Programming:
https://www.javatpoint.com/java-swing
8. Working with Preferences API in Java:
https://docs.oracle.com/javase/8/docs/api/java/util/prefs/
Preferenc es.html
9. How to Create 2D Games in Java: https://www.real-
tutsgml.com
10. Managing Timers in Java:
https://www.baeldung.com/java-timer-and-timertask
11. Introduction to Linked Lists:
https://www.geeksforgeeks.org/linked-list-in-java/
12.Using Random Class in Java:
https://www.programiz.com/java-programming/library/rando
m
13.Game Development Patterns:
http://gameprogrammingpatterns.com/
14.Event-Driven Programming Concepts:
https://www.baeldung.com/java-event-listener
15.Game Development with Java:
https://www.udemy.com/course/java-game-development/

You might also like