Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

TIC TAC TOE GAME

MINI PROJECT REPORT

Submitted by

AARTHI C

in partial fulfillment for the award of the degree


of
BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE AND ENGINEERING

DR. SIVANTHI ADITANAR COLLEGE OF


ENGINEERING, TIRUCHENDUR

ANNA UNIVERSITY:: CHENNAI 600 025


DECEMBER 2023
ANNA UNIVERSITY : CHENNAI 600 025

BONAFIDE CERTIFICATE

Certified that this project report “TIC TAC TOE GAME” is


the Bonafide work of
“AARTHI C” who carried out the project work
under my supervision.

STAFF IN CHARGE HEAD OF THE DEPARTMENT

EXTERNAL EXAMINER INTERNAL EXAMINER


Abstract:
This mini-project presents the development of a console-based Tic Tac
Toe game in Java, applying fundamental principles of object-oriented
programming. The project aims to create an interactive and user-friendly gaming
experience for two players engaging in the classic Tic Tac Toe competition. The
implementation encompasses modular components such as the game board, player
entities, and game logic, demonstrating a clear separation of concerns and
adherence to Java's object-oriented paradigm.
The project's main components include the Board class responsible for
managing the game grid, displaying the current state, and determining the winner.
The Player class defines the properties and actions of each player, facilitating
moves on the board. The Game class orchestrates the gameplay, alternating turns
between players, validating input, and declaring the outcome of each match.
Throughout the development, a focus on simplicity and readability guided
the design, allowing for easy comprehension and maintenance of the codebase. The
implementation includes features such as user input validation, win detection, and
a clean console interface. The project not only serves as an entry-level application
of core Java concepts but also as a foundation for potential future enhancements.
Future possibilities for improvement encompass the introduction of a
graphical user interface (GUI), support for additional players, and the integration
of an artificial intelligence opponent for single-player mode. The mini-project
offers an engaging and educational exploration into Java programming,
demonstrating the application of theoretical concepts into a practical, interactive
software project.
The successful completion of this Tic Tac Toe mini-project in Java lays the
groundwork for further exploration and extension of game development concepts
within the Java programming language. The modular design and adherence to best
practices in coding provide a solid foundation for future enhancements and
modifications, making it a valuable learning experience for novice Java
programmers.
Table of Contents:
1. Introduction
1.1 Background
1.2 Objective
2. Implementation
2.1 Board
2.1.1 Displaying the Board
2.1.2 Checking for a Winner
2.1.3 Updating the Board
2.2 Player
2.2.1 Player Properties
2.2.2 Making a Move
2.3 Game Flow
3. Code Snippet
3.1 Overview
4. Code
4.1 Program
4.2 Output
4.2.1 Output for X to win
4.2.2 Output for O to win
4.2.3 Output for draw
5. Conclusion
6. Future Enhancements
7. Acknowledgments
1. Introduction:
. Tic Tac Toe, a timeless and ubiquitous game, serves as a perennial
favorite for those seeking a quick and engaging challenge. Its simplicity belies a
rich set of strategic possibilities, making it an ideal playground for implementing
and honing fundamental programming concepts. In this mini-project, we delve into
the realm of Java programming to craft a console-based Tic Tac Toe game.
The choice of Tic Tac Toe as the subject of this project is deliberate. While
its rules are elementary, the implementation unveils a tapestry of object-oriented
principles, user input management, and algorithmic decision-making. Through the
development of this Java-based application, we aim to solidify our understanding
of core programming concepts and their application in a real-world context

1.1 Background:
Tic Tac Toe, also known as Noughts and Crosses, is a classic two-player
game played on a 3x3 grid. The simplicity of its rules and mechanics makes it an
ideal candidate for introductory programming projects. The objective is for players
to mark three consecutive cells either horizontally, vertically, or diagonally with
their respective symbols ('X' or 'O').

1.2 Objective:
The primary objective of this Tic Tac Toe mini-project in Java is to create
a functional and interactive console-based game that embodies key principles of
object-oriented programming. The project aims to achieve the following specific
goals:
 Implementing Core Game Logic:
 Develop a robust and efficient game engine that captures the essential
rules of Tic Tac Toe.
 Create classes and methods to represent the game board, players, and
their interactions.
 User Interface Design:
 Design a clear and user-friendly console interface to facilitate player
interactions.
 Provide a visually intuitive display of the game board after each
move.
 User Input Handling:
 Implement mechanisms to handle user input for moves, ensuring
validity and preventing errors.
 Offer a seamless and responsive input system that enhances the
overall gaming experience.
 Winning and Draw Conditions:
 Establish algorithms to detect winning moves for both players based
on the game rules.
 Implement checks for a draw when the entire board is filled without a
winner.
 Modular Code Structure:
 Develop a modular and well-organized codebase, adhering to best
practices of object-oriented programming.
 Encapsulate functionalities within classes and methods to promote
code readability and maintainability.
 Educational Value:
 Reinforce understanding of core Java concepts such as classes,
objects, methods, and control flow.
 Provide a hands-on experience in applying programming principles to
a practical, real-world problem.
 Future Enhancements:
 Lay the groundwork for potential future expansions, such as
implementing a graphical user interface (GUI), supporting multiple
players, or integrating an artificial intelligence opponent.
By achieving these objectives, this mini-project aims to serve as a pedagogical
tool, offering a tangible application of theoretical concepts while providing an
enjoyable and interactive experience for users engaging with the classic game of
Tic Tac Toe.

2. Implementation:
The Tic Tac Toe game has been implemented in Java, a versatile and
object-oriented programming language. The choice of Java allows for platform
independence and ease of development.
2.1 Board:

In this game each cell is a 3X3 grid and players can make their move by
entering the respective box number during their turn. The board is refreshed after
every match. During gameplay, players make their move by placing X or O in each
box.
And so on, until a player wins or the game ends in a draw. This format is a
simple way to represent the Tic Tac Toe board visually in a text-based
environment.

2.1.1 Displaying the board:

1 2 3

4 5 6

7 8 9

In this program the board is displayed as shown above. It is a 3X3 board


and a two player game.

2.1.2 Checking for a winner:


In this game the winner can be palyer1(X) or player2(O). The winner is
choosed based on the placement of X and O in the board. If the X and O are placed
continuously 3 times either horizontally or vertically or diagonally, then the player
is considered as the winner. There are 8 possibilities to win this game. Let’s check
the way for player1(X) to win this game.
1)
X X X

4 5 6

7 8 9

Here the X is played horizontally and hence X won the game.


2)
1 2 3

X X X

7 8 9

Here also the X is played horizontally and hence X won the game.
3)
1 2 3

4 5 6

X X X

Here also the X is played horizontally and hence X won the game.
4)
X 2 3

X 5 6

X 8 9

Here, the X is played vertically and hence X won the game.


5)
1 X 3

4 X 6

7 X 9

Here also the X is played vertically and hence X won the game.
6)
1 2 X

4 5 X

7 8 X

Here also the X is played vertically and hence X won the game.
7)
1 2 X

4 X 6

X 8 9

Here the X is played diagonally and hence X won the game.


8)
X 2 3

4 X 6

7 8 X

Here also the X is played diagonally and hence X won the game.
These are the possible ways to win the game. Likewise if O is placed then
Player2(O) wins the game.

2.1.3 Updating the board:


When a player makes a move, the game board must be updated to reflect
the current state of the game. This involves modifying the internal representation
of the board and displaying the updated board to the players. In this game the
board is updated after every move of the player by entering the number of
respected box.

2.2 Player:
In the Tic-Tac-Toe mini project, there are two players, 'X' and 'O.' The
players take turns making moves on the game board, where each move consists of
specifying a row and a column to place their respective symbol ('X' or 'O'). The
player symbols alternate between 'X' and 'O' with each turn.
2.2.1 Player Properties:
In the provided Tic-Tac-Toe mini project, the player is represented by the
symbols 'X' and 'O'. These symbols are used to mark the moves made by the
players on the game board. The players take turns making moves until the game is
either won by one of the players or ends in a tie.
The concept of the player property is fundamental to the turn-based nature
of the game, where 'X' and 'O' alternate in making moves until the game reaches a
conclusion.

2.2.2 Making a Move:


In the provided Tic-Tac-Toe mini project, making a move involves the
player entering the desired row and column to place their symbol ('X' or 'O') on the
game board.

2.3 Game Flow:


How to Play the Game :
 Both the players choose either X or O to mark their cells.
 There will be a 3×3 grid with numbers assigned to each of the 9 cells.
 The player who choose X begins to play first.
 He enters the cell number where he wishes to place X.
 Now, both O and X play alternatively until any one of the two wins.
 Winning criteria: Whenever any of the two players has fully filled one row/
column/ diagonal with his symbol (X/ O), he wins and the game ends.
 If neither of the two players wins, the game is said to have ended in a draw.

main():
In the main() function the array of board is created and the other functions
of the code is called and the board is print and shown. All the subfunction of the
code is called in the main function and the code starts from the main function.
printBoard():

In the printBoard() function the board for the game is displayed and the
board is updated after each move.
checkWinner():

In the checkWinner() function the possibility for a player to win this game
is checked. There are 8 possibility for a player to win and the match may end in a
draw. The possibilities for winning the game is checked after each move.

3. Code Snippet:
3.1 Overview:
This program is designed to run in a console or terminal and allows two
players to take turns making moves in a Tic Tac Toe game. Below is a breakdown
of key components and functionalities:

1. Board Representation:
The Tic Tac Toe board is represented as a 3x3 grid, stored in a 2D array
named board. Each cell can be empty (' '), marked by 'X', or marked by 'O'. The
board is displayed after each move.

2. Player Turn:
Players are identified as 'X' and 'O'. The 'turn' variable keeps track of the
current player, and it alternates between 'X' and 'O' after each valid move.

3. Display Board:
The printBoard() method is responsible for rendering the current state of
the Tic Tac Toe board. It shows the row and column numbers and updates the grid
with the players' moves.

4. Move Validation:
The if condition checks whether a player's move is valid. It ensures that
the selected cell is within the bounds of the board and is not already occupied.

5. Main Game Loop:


The main() method contains the main game loop. Players take turns
making moves until a win or tie condition is met. After each move, the board is
displayed, and the game state is evaluated.
6. Winning Conditions:
The checkWinner() method checks for winning conditions after each move.
It examines rows, columns, and diagonals to determine if a player has achieved
three in a row.

7. Tie Condition:
The for loop checks if the board is full, indicating a tie when there is no
winner.

8. User Input:
Players input their moves by specifying the row and column numbers. The
program uses a Scanner object to read user input from the console.

9. End of Game:
The game concludes when a player wins, there is a tie, or the players
choose to exit. The program provides a message indicating the outcome.

10. Additional Features:


You can further enhance the program by adding features such as input
validation and an option to play again.
This overview summarizes the key aspects of the Tic Tac Toe Java program,
providing a foundation for understanding its functionality and structure.

4. Code:
4.1 Program:
import java.util.*;
public class TTT
{
static String[] board;
static String turn;
static String checkWinner()
{
for (int a = 0; a < 8; a++)
{
String line = null;
switch (a)
{
case 0:
line = board[0] + board[1] + board[2];
break;
case 1:
line = board[3] + board[4] + board[5];
break;
case 2:
line = board[6] + board[7] + board[8];
break;
case 3:
line = board[0] + board[3] + board[6];
break;
case 4:
line = board[1] + board[4] + board[7];
break;
case 5:
line = board[2] + board[5] + board[8];
break;
case 6:
line = board[0] + board[4] + board[8];
break;
case 7:
line = board[2] + board[4] + board[6];
break;
}
if (line.equals("XXX"))
{
return "X";
}
else if (line.equals("OOO"))
{
return "O";
}
}

for (int a = 0; a < 9; a++)


{
if (Arrays.asList(board).contains(String.valueOf(a + 1)))
{
break;
}
else if(a==8)
{
return "draw";
}
}
System.out.println(turn + "'s turn; enter a slot number to place "+ turn + "
in:");
return null;
}
static void printBoard()
{
System.out.println("|---|---|---|");
System.out.println("| " + board[0] + " | "+ board[1] + " | " + board[2]+ " |");
System.out.println("|-----------|");
System.out.println("| " + board[3] + " | "+ board[4] + " | " + board[5]+ " |");
System.out.println("|-----------|");
System.out.println("| " + board[6] + " | "+ board[7] + " | " + board[8]+ " |");
System.out.println("|---|---|---|");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
board = new String[9];
turn = "X";
String winner = null;
for (int a = 0; a < 9; a++)
{
board[a] = String.valueOf(a + 1);
}
System.out.println("Welcome to 3x3 Tic Tac Toe.");
printBoard();
System.out.println("X will play first. Enter a slot number to place X in:");
while (winner == null)
{
int numInput;
try
{
numInput = in.nextInt();
if (!(numInput > 0 && numInput <= 9))
{
System.out.println("Invalid input; re-enter slot number:");
continue;
}
}
catch (InputMismatchException e)
{
System.out.println("Invalid input; re-enter slot number:");
continue;
}
if (board[numInput - 1].equals(String.valueOf(numInput)))
{
board[numInput - 1] = turn;
if (turn.equals("X"))
{
turn = "O";
}
else
{
turn = "X";
}
printBoard();
winner = checkWinner();
}
else
{
System.out.println("Slot already taken; re-enter slot number:");
}
}
if (winner.equalsIgnoreCase("draw"))
{
System.out.println("It's a draw! Thanks for playing.");
}
else
{
System.out.println("Congratulations! " + winner+ "'s have won! Thanks for
playing.");
}
in.close();
}
}

4.2 Output:
4.2.1 Output for X to win:
Welcome to 3x3 Tic Tac Toe.
|---|---|---|
|1|2|3|
|-----------|
|4|5|6|
|-----------|
|7|8|9|
|---|---|---|
X will play first. Enter a slot number to place X in:
5
|---|---|---|
|1|2|3|
|-----------|
|4|X|6|
|-----------|
|7|8|9|
|---|---|---|
O's turn; enter a slot number to place O in:
9
|---|---|---|
|1|2|3|
|-----------|
|4|X|6|
|-----------|
|7|8|O|
|---|---|---|
X's turn; enter a slot number to place X in:
4
|---|---|---|
|1|2|3|
|-----------|
|X|X|6|
|-----------|
|7|8|O|
|---|---|---|
O's turn; enter a slot number to place O in:
3
|---|---|---|
|1|2|O|
|-----------|
|X|X|6|
|-----------|
|7|8|O|
|---|---|---|
X's turn; enter a slot number to place X in:
6
|---|---|---|
|1|2|O|
|-----------|
|X|X|X|
|-----------|
|7|8|O|
|---|---|---|
Congratulations! X's have won! Thanks for playing.

4.2.2 Output for O to win:


Welcome to 3x3 Tic Tac Toe.
|---|---|---|
|1|2|3|
|-----------|
|4|5|6|
|-----------|
|7|8|9|
|---|---|---|
X will play first. Enter a slot number to place X in:
1
|---|---|---|
|X|2|3|
|-----------|
|4|5|6|
|-----------|
|7|8|9|
|---|---|---|
O's turn; enter a slot number to place O in:
5
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|7|8|9|
|---|---|---|
X's turn; enter a slot number to place X in:
9
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|7|8|X|
|---|---|---|
O's turn; enter a slot number to place O in:
8
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|7|O|X|
|---|---|---|
X's turn; enter a slot number to place X in:
7
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|X|O|X|
|---|---|---|
O's turn; enter a slot number to place O in:
2
|---|---|---|
|X|O|3|
|-----------|
|4|O|6|
|-----------|
|X|O|X|
|---|---|---|
Congratulations! O's have won! Thanks for playing.

4.2.3 Output for draw:


Welcome to 3x3 Tic Tac Toe.
|---|---|---|
|1|2|3|
|-----------|
|4|5|6|
|-----------|
|7|8|9|
|---|---|---|
X will play first. Enter a slot number to place X in:
1
|---|---|---|
|X|2|3|
|-----------|
|4|5|6|
|-----------|
|7|8|9|
|---|---|---|
O's turn; enter a slot number to place O in:
5
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|7|8|9|
|---|---|---|
X's turn; enter a slot number to place X in:
7
|---|---|---|
|X|2|3|
|-----------|
|4|O|6|
|-----------|
|X|8|9|
|---|---|---|
O's turn; enter a slot number to place O in:
4
|---|---|---|
|X|2|3|
|-----------|
|O|O|6|
|-----------|
|X|8|9|
|---|---|---|
X's turn; enter a slot number to place X in:
6
|---|---|---|
|X|2|3|
|-----------|
|O|O|X|
|-----------|
|X|8|9|
|---|---|---|
O's turn; enter a slot number to place O in:
8
|---|---|---|
|X|2|3|
|-----------|
|O|O|X|
|-----------|
|X|O|9|
|---|---|---|
X's turn; enter a slot number to place X in:
2
|---|---|---|
|X|X|3|
|-----------|
|O|O|X|
|-----------|
|X|O|9|
|---|---|---|
O's turn; enter a slot number to place O in:
3
|---|---|---|
|X|X|O|
|-----------|
|O|O|X|
|-----------|
|X|O|9|
|---|---|---|
X's turn; enter a slot number to place X in:
9
|---|---|---|
|X|X|O|
|-----------|
|O|O|X|
|-----------|
|X|O|X|
|---|---|---|
It's a draw! Thanks for playing.

5. Conclusion:
In conclusion, the Java Tic Tac Toe program presented here is a console-
based implementation that allows two players to engage in the classic game. The
program leverages a 3x3 grid represented by a 2D array, offering players the
opportunity to take turns marking 'X' or 'O' on the board. The game continues until
a player achieves a winning configuration or the board is filled, resulting in a tie.
Key features of the program include a dynamic display of the game board
after each move, move validation to ensure players make legal moves, and
functions to check for a winning condition or a tie. The alternating turns of players
are tracked through the ‘turn’ variable, and user input is obtained using the
‘Scanner’ class.
This project serves as an introductory example of Java programming,
showcasing fundamental concepts such as arrays, loops, conditionals, and user
input handling. Furthermore, it provides a solid foundation for those interested in
expanding the game's functionalities, incorporating error handling, or creating a
graphical user interface for a more interactive user experience.
As a next step, developers can consider adding features like input
validation, error handling for incorrect input, implementing a play again option, or
creating a graphical user interface to enhance the overall user experience. The code
can be expanded and modified to accommodate additional functionality and
improvements based on individual preferences or project requirements.
6. Future Enhancement:
1. Graphical User Interface (GUI):
Convert your console-based game into a graphical one using Java Swing or
JavaFX. This will provide a more user-friendly and visually appealing interface.

2. Player Names and Scores:


Allow players to enter their names, and keep track of scores for multiple
rounds. Display the scoreboard after each game.

3. AI Opponent:
Implement a computer player with varying levels of difficulty. You can
start with a simple AI that makes random moves and gradually enhance it to
become more strategic.

4. Animations and Sound Effects:


Add animations for player moves and winning sequences. Include sound
effects for a better gaming experience.

5. Multiple Board Sizes:


Allow users to choose between different board sizes (e.g., 4x4, 5x5) for a
more challenging game.

6. Undo and Redo:


Implement functionality to undo and redo moves during the game.

7. Save and Load Game:


Allow users to save the game state and continue playing later. This involves
saving the state of the game board, player turns, and other relevant information.

8. Network Multiplayer:
Implement a networked version of the game to allow two players to play
against each other over the internet.
9. Themes and Customization:
Add different themes and customization options, such as choosing
different symbols for players, changing the background, or selecting different
board designs.

10. Difficulty Levels:


If you implement an AI opponent, allow users to choose the difficulty
level, ranging from easy to expert.

11. Statistics and Achievements:


Track and display statistics like the number of games played, wins, losses,
and implement an achievement system for reaching specific milestones.

12. Responsive Design:


If you are creating a GUI, ensure that your game is responsive and works
well on different screen sizes.

7.Acknowledgement:
I take this opportunity to express my deep gratitude and sincerest thank you
to my project mentor, Mrs. Anandhi. S. V for giving the most valuable suggestion,
helpful guidance and encouragement in the execution of this project work.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy