Varun Project
Varun Project
A Major Project
Report
on
“TIC TAC TOE”
Submitted in partial fulfillment of the requirement for the award of the degree of
By:
VARUN SHARMA
(220721106100)
UNDER THE GUIDENCE OF
Session-(2022-2025)
CH. HARCHAND SINGH MAHAVIDYALAYA
JEWAR ROAD,KHURJA - 203131
(An Autonomous Institute, Affiliated To CCSU,Meerut )
CERTIFICATE
This is to certify that the project entitled,“TIC TAC TOE” has been successfully
completed and submitted by VARUN SHARMA [220721106100] in partial fulfillment
of the requirements for the award of Bachelor of Computer Application degree of Ch.
Charan Singh University, Meerut during the academic year [2022-2025].It is certified
that all the correction / suggestion indicated have been incorporated in the report and
the copy of the report is deposited in the department library. The project has been
approved as it satisfies the academic requirements in respect of project work
prescribed for the said [Link] project work has been carried out under my
supervision and guidance and is a record of the candidate’s own work carried out with
utmost sincerity and dedication.
I would like to express my sincere gratitude to all those who supported me throughout
the development of this project, "Tic Tac Toe ." This project has been an enriching
experience, and I am thankful for the guidance and encouragement I received.
I would also like to thank Mr AJAY RAGHAV, Head of the Department of COMPUTER
APPLICATION, for providing me with the opportunity to carry out this project and for
the facilities made available.
I am especially grateful to my faculty members, lab staff, and classmates for their
cooperation, insights, and constructive suggestions which helped shape this project into
its final form.
Finally, I thank my family and friends for their moral support and patience during the
project period.
This project has given me a great opportunity to learn and explore, and I am thankful for
this valuable experience.
[VARUN SHARMA ]
[220721106100]
DECLARATION
I hereby declare that the project work entitled "Tic Tac Toe" submitted in partial
fulfillment of the requirements for the award of the degree of
Bachelor of Computer Application is a record of my original work carried out under
the supervision of Mr. AJAY RAGHAV ,Assistant professor, Department of COMPUTER
APPLICATION.
This project has not been submitted earlier in part or full to any other institution or
university for the award of any degree, diploma, or any other similar title.I have fulfilled
all academic and ethical requirements expected in this project and have acknowledged
all sources used in accordance with institutional guidelines.
Abstract
Introduction
About the project
System Design
System Modules
Implementation
Data flow diagram (DFD)
Requirements
About Java Language
Platform
JVM(Java Virtual Machine)
JDK(Java Development kit)
NetBeans IDE and modularity
Source code
Output Screenshots
Future scope
Conclusion
Bibliography
ABSTRACT
The Tic Tac Toe Game in Java (GUI Version) project aims to develop an interactive and
user-friendly Tic Tac Toe game for two players using Java's Swing library for the
graphical user interface (GUI). The game consists of a 3x3 grid where two players,
denoted as "X" and "O", take turns marking cells on the grid. The game ends when a
player successfully aligns three of their marks in a row, column, or diagonal, or when
the board is filled without a winner, resulting in a tie.
The main objectives of this project include designing a functional game with intuitive
interface elements such as buttons representing the cells of the grid, real-time player
interaction, and automatic win or draw detection. This project also incorporates event-
driven programming, where user input through button clicks is captured, processed,
and reflected in the game state.
The application verifies win conditions after each move and provides an option to
restart the game once it concludes. By creating this game, this project serves as a
demonstration of how Java Swing can be leveraged to build simple GUI-based
applications with interactive functionality.
The project allows for learning key concepts in GUI development, event handling, and
game logic implementation in Java. Future enhancements may include adding an AI
player for single-player mode and improving the user interface with animations for a
more engaging experience
INTRODUCTION
The Tic Tac Toe game is a popular two-player game where players take turns marking
cells in a 3x3 grid with their respective symbols, "X" and "O." This project involves the
development of a Tic Tac Toe game using the Java programming language with a
Graphical User Interface (GUI), specifically using Java Swing for UI elements.
This version of the game is designed for two players who take turns playing on the same
device, with one player using "X" and the other using "O." The goal of the game is for
players to align three of their marks in a row, column, or diagonal. If all spots on the
board are filled without a winner, the game results in a tie.
The game is interactive and allows players to enjoy playing directly through a graphical
interface. The use of a GUI helps to enhance the user experience by providing a clear
and intuitive way to interact with the game.
Objective
The primary objective of this project is to create an engaging and functional Tic Tac Toe
game with a graphical interface using Java Swing. The game will follow the standard
rules of Tic Tac Toe, where players alternate between "X" and "O" on a 3x3 grid, aiming
to get three marks in a row (horizontally, vertically, or diagonally).
In addition to implementing the core game logic, the project will focus on:
User-friendly interface: Making the game intuitive and accessible to players of all
ages by using a simple and clear GUI.
Through this project, Java developers can learn and practice GUI development, handling
event-driven programming, and the implementation of game logic. This is a great
introduction to creating interactive desktop applications and understanding the
concepts of managing a game state.
ABOUT THE PROJECT
The Tic Tac Toe Game is a desktop-based graphical application developed in Java
using the Swing framework. It replicates the popular two-player paper game where
players take turns marking spaces in a 3×3 grid with X or O. The goal is to place three
respective marks in a row—vertically, horizontally, or diagonally—before the opponent.
This project provides a polished, interactive, and intuitive experience. Beyond the basic
gameplay, it also includes scorekeeping, a persistent leaderboard, sound effects, and
customizable player names, offering a complete and enjoyable gaming experience.
🎯 Turn-Based Logic
The game automatically switches turns between the two players.
A label at the bottom displays the current player's turn, making it easy to follow
the gameplay.
🎯 Winner Detection
After each move, the program checks for all possible winning combinations:
Three rows
Three columns
Two diagonals
If a player wins, their name is shown in a popup, and their score is incremented.
🎯 Tie Handling
If the grid is completely filled and no winner is found, the game detects a tie and
shows a message accordingly.
🎯 Leaderboard Feature
After every win, the winner's name is saved to a text file ([Link]).
The leaderboard is displayed in a popup after each match, sorted in descending
order of wins.
This creates a competitive environment where players can track long-term
performance.
🎯 Sound Effects
Sound effects are played using Java’s Sound API:
A move sound ([Link]) plays after each valid move.
A win sound ([Link]) plays when a player wins.
These sound effects enhance user engagement and give feedback on actions.
Game logic development, including win condition checks and turn management.
The Tic Tac Toe game is a simple two-player board game implemented using Java
Swing for the GUI and Java I/O for persistent leaderboard storage. The system design
encompasses the following main components:
1. Architecture Overview
Frontend/UI Layer: Built using Java Swing components (JFrame, JPanel,
JButton, JLabel, etc.), providing a responsive and interactive interface for
gameplay.
Event Handling Layer: Implements ActionListener to handle user interactions,
such as button clicks and score resets.
Logic Layer: Handles the game mechanics, including turn switching, win/tie
checking, board state management, and score updates.
Persistence Layer: Utilizes File, BufferedReader, and BufferedWriter to store
and retrieve leaderboard data in [Link].
2. Component Breakdown
a. Main Frame (JFrame)
The main window (frame) uses BorderLayout to organize UI components into
center and south regions.
c. Status Panel
A vertical layout (GridLayout(3,1)) holding:
Status Label: Displays whose turn it is.
Score Label: Displays the current score.
Reset Button: Resets the game scores.
d. Game Logic
Turn Tracking: A boolean xTurn variable tracks which player’s turn it is.
Win Checking: Uses pre-defined index combinations to check for winning
conditions.
Tie Detection: Checks if the board is full and no player has won.
Score Update: Increments the score for the winning player and updates the UI.
e. Sound Effects
Sounds for moves and wins are played using the Java [Link]
package.
Improves user feedback and interaction.
3. Leaderboard System
Each game result is appended to a [Link] file.
The file stores lines in the format: PlayerName won.
On demand, the leaderboard is parsed and displayed with total win counts per
player using a HashMap sorted by values in descending order.
5. Error Handling
Sound Playback Errors: Caught and logged using try-catch.
File Read/Write Errors: Proper exception handling to avoid application crashes
due to I/O issues.
6. UX/UI Features
Highlight winning combination with a green background.
Responsive status messages after each action.
Dynamic score updates and reset functionality.
Popup dialogs for win, tie, and leaderboard display.
7. Extensibility Considerations
AI Opponent: Future enhancement can introduce a computer-controlled player.
Networked Multiplayer: Integration with sockets could allow remote gameplay.
Theme/Style Customization: Support for different skins and button styles.
Timer Mode: Add a countdown for each player's move.
FLOW CHART
System Modules
6. Leaderboard Module
Purpose: Persist and display the historical record of wins.
Key Components:
File leaderboardFile — Stores the leaderboard data ([Link]).
Key Methods:
updateLeaderboard(String winner) — Append winner’s name to the leaderboard
file.
showLeaderboard() — Read the file, count wins per player, and display sorted
leaderboard.
Responsibilities:
Maintain persistent win records across game sessions.
Show players' cumulative performance history.
The Tic Tac Toe game is implemented entirely in Java using the Swing framework for
the graphical user interface (GUI), Java I/O classes for persistent data storage, and Java
Sound API for interactive audio effects. The main goal of this implementation is to
provide a simple and interactive 2-player game with real-time score updates and
leaderboard tracking.
The game layout follows a BorderLayout where the game board is placed in the center,
and the status panel is placed at the bottom.
5.3 Core Features and Logic
a. Player Name Input
Upon starting the game, the system prompts the users to enter their names using
JOptionPane. If a user does not enter a name or cancels the input, default names Player
X and Player O are assigned.
The button is marked with "X" or "O" depending on the current turn.
The button is disabled to prevent re-clicking.
A move sound ([Link]) is played to provide feedback.
The turn then alternates to the next player, and the status label updates accordingly.
int[][] winCombos = {
};
If a match is found:
d. Draw Condition
If all buttons are filled and no winner is found, a draw is declared using a dialog
message, and the board is reset.
e. Score Management
Scores for both players are stored in the variables xScore and oScore. They are updated
after each game round and shown in scoreLabel. The "Reset Scores" button clears both
scores and updates the display.
f. Leaderboard Feature
The application keeps track of all players’ wins across sessions using a text file named
[Link].
Writing to Leaderboard:
The winner's name is appended to the file after each win using BufferedWriter.
Reading and Displaying Leaderboard:
All lines are read from the file.
A HashMap is used to count how many times each player has won.
The map is sorted in descending order of wins.
The sorted data is displayed in a dialog box.
This allows users to track their overall performance over multiple games.
[Link](audioIn);
[Link]();
The audio file must exist in the root directory of the project to work correctly.
Conclusion of Implementation
The implementation ensures a user-friendly, interactive two-player game with a real-
time scoreboard, audio feedback, and persistent leaderboard. All features are built using
standard Java libraries, making the game portable and simple to run on any system with
a Java environment.
Data Stores:
[Link]
Persistent storage for tracking winners across sessions.
Data Flows Summary:
Flow Source Destination Description
Player Names Player Input Handler Collected via JOptionPane
Moves (Button
Player Input Handler Triggers actionPerformed()
Clicks)
Win/Draw Result Game Logic GUI Renderer Displays result on GUI
Updated Score Score Tracker GUI Renderer Updates score label
Winner Name Game Logic Score Tracker Passed to leaderboard file
Display Read and shown in sorted
Leaderboard Data [Link]
Leaderboard format
Requirements
1. Functional Requirements
These define what the system should do.
1.6. Scoring
The game must maintain and display ongoing scores for both players.
The score must update after each win.
A Reset Scores button must be provided to set both scores to zero.
1.7. Leaderboard
The system must write the winner’s name to a file [Link] after each
game.
The leaderboard must be shown after each win, displaying players and the
number of wins in descending order.
🎯 2. Non-Functional Requirements
These define how the system performs its functions.
2.1. Usability
The user interface must be intuitive and easy to use.
Clear instructions should be provided through prompts and labels.
2.2. Performance
The application should respond to player moves with minimal delay.
The leaderboard file read/write operations should be efficient.
2.3. Reliability
The application should accurately detect win and draw conditions.
It should prevent illegal moves (like clicking on an already filled cell).
2.4. Maintainability
The code must be modular, with separate methods handling UI, game logic, and
file operations.
Easy to extend for future improvements (e.g., adding multiplayer over network).
2.5. Portability
The application must run on any system with Java and the required sound files.
Component Requirement
Operating System Windows / macOS / Linux
Java Version Java SE Development Kit (JDK) 8 or higher
Runtime Environment Java Runtime Environment (JRE)
Eclipse / IntelliJ IDEA / NetBeans / VS Code with Java
IDE (optional)
plugin
Audio Support Java Sound API (included in JDK/JRE)
🎯 2. Application Dependencies
Module Requirement
UI Framework Java Swing
Event Handling [Link].* for ActionListeners
[Link].* for reading/writing
File Handling
leaderboard
Sound Playback [Link].* to play .wav files
Collections API [Link].* for leaderboard processing
Tool Purpose
For writing unit tests (if added
JUnit
later)
IDE Debugger For step-by-step code analysis
Console/Logs Output and exception messages
Visual Studio Code (VS Code) is a lightweight, powerful, and highly customizable source-
code editor developed by Microsoft. It supports a wide range of programming languages
and frameworks through its extensive extension marketplace. In this Bus Ticket
Booking System project, Visual Studio Code is used as the primary development
environment for writing and managing Java code. With the help of extensions such as
Java Extension Pack, Maven, and Debugger for Java, VS Code provides essential features
like IntelliSense (code completion), syntax highlighting, error checking, and integrated
terminal support for compiling and running Java programs. Additionally, its integration
capabilities allow developers to easily manage Java Swing for GUI design and JDBC for
database connectivity. Visual Studio Code's simplicity and efficiency make it an ideal
choice for developing Java desktop applications in a clean and organized workflow.
Key Points:
Platform Independence: JVM allows Java programs to run on any operating
system without modification.
Bytecode Execution: It interprets or compiles Java bytecode into machine code
at runtime.
Memory Management: Automatically handles memory allocation and garbage
collection.
Security and Robustness: Provides a secure execution environment with built-
in error and exception handling.
Integral to Java: JVM is part of the JRE (Java Runtime Environment) and is
required to run Java applications.
Complete Development Kit: Includes JRE, compiler, debugger, and other tools
for Java development.
Required for Coding: Essential for writing, compiling, and running Java
programs.
Supports GUI & DB Tools: Enables use of Swing for GUI and JDBC for database
operations.
Version-Specific Features: Different JDK versions offer various enhancements
and tools.
Command-Line Tools: Includes utilities like javac, java, and javadoc for
development tasks.
🎯 1. UI Module
Components: JFrame, JPanel, JButton, JLabel, JOptionPane
Responsibility: Manages the GUI layout and interaction
Location: Inside TicTacToe() constructor and helper methods like resetBoard(),
highlightWin()
🎯 2. Game Logic Module
Components: xTurn, buttons, checkForWinner(), isBoardFull(),
actionPerformed()
Responsibility: Controls turn switching, win/tie checking, and updates to board
state
🎯 4. Sound Module
Component: playSound(String fileName)
Responsibility: Plays .wav files for move and win actions using
AudioInputStream and Clip
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class TicTacToe implements ActionListener {
private final JFrame frame;
private final JPanel boardPanel, statusPanel;
private final JButton[] buttons = new JButton[9];
private final JLabel statusLabel, scoreLabel;
private final JButton resetScoreButton;
private boolean xTurn = true;
private int xScore = 0;
private int oScore = 0;
private String playerX;
private String playerO;
private final File leaderboardFile = new
File("[Link]");
public TicTacToe() {
frame = new JFrame("Tic-Tac-Toe");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new BorderLayout());
// Get player names
playerX = [Link](frame, "Enter
name for Player X:");
playerO = [Link](frame,
"Enter name for Player O:");
if (playerX == null || [Link]()) playerX =
"Player X";
if (playerO == null || [Link]()) playerO =
"Player O";
// Board panel
boardPanel = new JPanel(new GridLayout(3, 3));
[Link]([Link]
(10, 10, 10, 10));
for (int i = 0; i < 9; i++) {
buttons[i] = new JButton();
buttons[i].setFont(new Font("Arial", [Link],
40));
buttons[i].setFocusPainted(false);
buttons[i].addActionListener(this);
[Link](buttons[i]);
}
// Status panel
statusPanel = new JPanel(new GridLayout(3, 1));
statusLabel = new JLabel(playerX + "'s Turn (X)",
[Link]);
[Link](new Font("Arial", [Link],
16));
scoreLabel = new JLabel(getScoreText(),
[Link]);
[Link](new Font("Arial", [Link],
16));
resetScoreButton = new JButton("Reset Scores");
[Link](_ -> {
xScore = 0;
oScore = 0;
updateScore();
});
[Link](statusLabel);
[Link](scoreLabel);
[Link](resetScoreButton);
[Link](boardPanel, [Link]);
[Link](statusPanel, [Link]);
[Link](400, 500);
[Link](true);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) [Link]();
if (![Link]().equals("")) return;
playSound("[Link]");
[Link](xTurn ? "X" : "O");
[Link](false);
if (checkForWinner()) {
String winner = xTurn ? playerX : playerO;
[Link](frame, winner + "
wins!");
if (xTurn) xScore++; else oScore++;
updateScore();
updateLeaderboard(winner);
showLeaderboard();
resetBoard();
return;
}
if (isBoardFull()) {
[Link](frame, "It's a
tie!");
resetBoard();
return;
}
xTurn = !xTurn;
[Link]((xTurn ? playerX : playerO) + "'s
Turn (" + (xTurn ? "X" : "O") + ")");
}
private boolean checkForWinner() {
String symbol = xTurn ? "X" : "O";
int[][] winCombos = {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 3, 6}, {1, 4, 7}, {2, 5, 8},
{0, 4, 8}, {2, 4, 6}
};
for (int[] combo : winCombos) {
if (buttons[combo[0]].getText().equals(symbol) &&
buttons[combo[1]].getText().equals(symbol) &&
buttons[combo[2]].getText().equals(symbol)) {
highlightWin(combo);
playSound("[Link]");
return true;
}
}
return false;
}
private void highlightWin(int[] combo) {
for (int i : combo) {
buttons[i].setBackground([Link]);
}
}
private boolean isBoardFull() {
for (JButton button : buttons) {
if ([Link]().isEmpty()) return false;
}
return true;
}
private void resetBoard() {
for (JButton button : buttons) {
[Link]("");
[Link](true);
[Link](null); // Reset color
}
xTurn = true;
[Link](playerX + "'s Turn (X)");
}
private void updateScore() {
[Link](getScoreText());
}
private String getScoreText() {
return playerX + " (X): " + xScore + " | " + playerO + "
(O): " + oScore;
}
private void playSound(String fileName) {
try {
AudioInputStream audioIn =
[Link](new File(fileName));
Clip clip = [Link]();
[Link](audioIn);
[Link]();
} catch (Exception e) {
[Link]("Sound error: " +
[Link]());
}
}
private void updateLeaderboard(String winner) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(leaderboardFile, true))) {
[Link](winner + " won\n");
} catch (IOException e) {
[Link]("Leaderboard write error: " +
[Link]());
}
}
private void showLeaderboard() {
StringBuilder leaderboard = new
StringBuilder("Leaderboard:\n");
Map<String, Integer> scores = new HashMap<>();
try (BufferedReader reader = new
BufferedReader(new FileReader(leaderboardFile))) {
String line;
while ((line = [Link]()) != null) {
String name = [Link](" won", "").trim();
[Link](name, [Link](name, 0) +
1);
}
[Link]().stream()
.sorted([Link].<String,
Integer>comparingByValue().reversed())
.forEach(entry ->
[Link]([Link]())
.append(": ")
.append([Link]())
.append(" wins\n"));
} catch (IOException e) {
[Link]("Error reading
leaderboard.\n");
}
[Link](frame,
[Link](), "Leaderboard",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
[Link](TicTacToe::new);
}
}
OUTPUT
Future Scope of the Tic Tac Toe Game
The current version of the Tic Tac Toe game provides a solid foundation with a
graphical interface, two-player support, sound effects, and a leaderboard system using
file handling. While the core game functionality is complete, there is significant potential
for enhancement in terms of usability, interactivity, scalability, and intelligence. Below
is an expanded look into the future possibilities for the game:
The Tic Tac Toe game implemented using Java Swing is a comprehensive demonstration
of building a classic board game with a graphical user interface, emphasizing usability,
interactivity, and maintainability. This project successfully combines essential
programming concepts like event-driven programming, GUI component management,
file handling, and multimedia integration to create a functional and engaging game
experience.
The application allows two players to compete in a turn-based game, with clear visual
cues indicating whose turn it is and immediate feedback when a player makes a move.
The logic to detect winning conditions and ties is efficiently implemented, ensuring that
the game state is always accurately reflected to the users. When a player wins, the
winning combination is highlighted visually, providing satisfying feedback and
improving the overall user experience. The inclusion of sound effects for moves and
victories adds another layer of immersion, making the game more engaging and
enjoyable.
One of the notable features of this implementation is the persistent leaderboard system.
By writing the winners’ names to a file and reading from it to display a cumulative
scoreboard, the game encourages continued play and friendly competition. This
persistent scoring mechanism not only tracks wins across sessions but also personalizes
the gaming experience by addressing players by their names. The ability to reset scores
provides users control over their gameplay statistics, making the system flexible and
user-friendly.
From a design perspective, the use of Java Swing components such as JFrame, JPanel,
and JButton, along with layout managers like GridLayout and BorderLayout,
demonstrates effective UI construction techniques that can be adapted for many other
projects. The clean separation between the game logic and the UI elements ensures that
the codebase remains manageable and extensible.
In terms of limitations, this game currently supports only two local players and does not
feature AI or network multiplayer capabilities. The user interface, while functional, is
fairly basic and could be improved with more sophisticated graphics or animations.
In conclusion, this Tic Tac Toe project is a solid example of how fundamental
programming concepts and GUI development techniques come together to create an
interactive and enjoyable game. It provides a good learning experience in Java
programming and serves as a foundation that can be extended and improved to develop
more complex gaming applications.
Bibliography