[go: up one dir, main page]

0% found this document useful (0 votes)
110 views19 pages

Mini Project

This document describes the development of a Tic Tac Toe game using Java. It provides an overview of the game and its scope. It then outlines the key steps and algorithms needed to create the game, including: initializing a 3x3 board array, getting player names, drawing and printing the board, alternating turns, validating user input, checking for a winner or tie, and looping the game until there is a conclusion. Advantages of the game include teaching strategy, logic, and problem solving skills, while disadvantages include it becoming boring or easy to solve. The document also discusses programming the game as a finite state machine and provides an example of gameplay flow.

Uploaded by

꧁༒Ajay༒꧂
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views19 pages

Mini Project

This document describes the development of a Tic Tac Toe game using Java. It provides an overview of the game and its scope. It then outlines the key steps and algorithms needed to create the game, including: initializing a 3x3 board array, getting player names, drawing and printing the board, alternating turns, validating user input, checking for a winner or tie, and looping the game until there is a conclusion. Advantages of the game include teaching strategy, logic, and problem solving skills, while disadvantages include it becoming boring or easy to solve. The document also discusses programming the game as a finite state machine and provides an example of gameplay flow.

Uploaded by

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

PANIMALAR INSTITUTE OF TECHNOLOGY

(A CHRISTIAN MINORITY INSTITUTION)


AN ISO 9001:2008 CERTIFIED INSTITUTION JAISAKTHI EDUCATIONAL TRUST
BANGALORE TRUNK ROAD, VARADHARAJAPURAM NASARATHPET, POONAMALLEE,
CHENNAI -600 123
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ACCREDITED BY NATIONAL BOARD OF ACCREDITATION (NBA)

MINI PROJECT REPORT

NAME : AJAY.S

ROLL NUMBER : 2021PITCS167

REGISTER NUMBER : 211521104004

DEPARTMENT : B.E COMPUTER SCICENCE AND ENGINEERING

YEAR : 2021-2025
MINI PROJECT : TIC TAC TOE GAME

AIM:

TO DEVELOP THE TIC TAC TOE GAME USING JAVA PROGRAM

INTRODUCTION ABOUT THE PROJECT:

In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In
this game, two players will be played and you have one print board on the screen
where from 1 to 9 number will be displayed or you can say it box number. Now, you
have to choose X or O for the specific box number. For example, if you have to
select any number then for X or O will be shown on the print board, and turn for
next will be there. The task is to create a Java program to implement a 3×3 Tic-
Tac-Toe game for two players.

Scope of the project :

Tic Tac Toe is traditionally played on a 3 × 3 grid. Players take turns placing a mark
in one of the cells of the grid. The goal of the game is for players to position their
marks so that they make a continuous line of three cells vertically,
horizontally, or diagonally.
Proposed gaming system The Tic Tac Toe game is a game for two players, called
"X" and "O", who take turns marking the spaces in a 3×3 grid. The player who
succeeded in placing three respective marks in a horizontal, vertical, or diagonal row
wins the game.

ALGORITHM:

Step 1: Create a 3x3 array to represent the tic tac toe board and fill
it with dashes.

We need to make a 2D array of characters, which can be x, o, or -.

Hint: We can use the following line of code to make a 3x3 array of chars: char[][]
board = new char[3][3]

Now we have to fill our board with dashes.


Hint: We can use a nested for loop to iterate through each position on our board. Inside both
for loops, we can set board[i][j] equal to a dash.
Step 2: Ask the users for their names.

First, we import the Scanner to help us get input from the user, by adding import

java.util.Scanner to the top of our program.

Then, we create our Scanner variable.

Next, we print out a message asking the user to type in their name
using System.out.print().

We store their input in a String called p1.

Do the same for p2.


Step 3: Create a function that draws the board and prints it out like a 3x3 square.

In order for our function to draw the board and print it out, do we need to pass a parameter

into the function? Do we need to return anything?

Hint: We need to pass in the board 2D array in order for the function to be able to print it.
We don’t need to return anything since the function is simply printing out the board.

Inside our function, we need to print out each position on our board.

Hint: If we do System.out.println(), then each position is on a new line.

Hint: If we do System.out.print(), then all of the positions are on one line.

Hint: We can do System.out.print() in the inner for loop, and


do System.out.println() at the end of the outer for loop so that it starts a new line after
each row has been printed.
Step 4: Print out the correct player’s turn and store the player’s char (x or o).

We need a way to keep track of which player’s turn it is in our game.

Hint: We can use a boolean called player1 which is true if it is player 1’s turn and false if it
is player 2’s turn.
We can use a conditional to check whose turn it is.

Also, we can use string concatenation to print out the player’s name.

Step 5: Ask the user for the row and col and check if it is valid.

Print a message asking the user for a row and use the Scanner to get their input, storing it in

a variable called row; repeat this for col.

Now, why would the row and col the user entered not be valid?

Hint: If the user types a row and col that is a spot that is not on the board, then the row and
col aren’t valid. Use a conditional to check if the row and col are not greater than 2 and not
less than 0.

Hint: If the user types a row and col that is a spot that already has an x or o on it, then the
row and col aren’t valid. Use a conditional to check if the position on the board at row and
col does not already have an x or o.
Step 6: Use a loop to keep asking the player to enter a valid row and col.

If the user enters a row and col that is out of bounds or a row and col that already has an x or

o on it, then we want to ask the user to re-enter a row and col. We can use a loop to do this!

Hint: We can use a while(true) loop and break once the player has entered a valid row and
col.
Step 7: Set the right position on the board to the player char.

Outside of the while loop, we know that we have a valid row and col. We can get the position
on the board by doing board[row][col].

Now we can set this position to be equal to the char of the player, which we stored in the
variable c.
Step 8: Create a function that checks if either player has won.

In tic tac toe, a player wins if they have 3 of their symbols in one row, column, or diagonal.

Let’s start with rows. We can use a for loop to iterate through each row i.
Inside the for loop, we can use a conditional to check if board[i][0] equals board[i]

[1] and if board[i][1] equals board[i][2]. Remember, we also have to check

if board[i][0] doesn’t equal a dash so that we don’t win if there are three empty spots in a

row. If that is all true, then we can return the value of board[i][0].

We can repeat similar steps for columns.

There are two diagonals on the board that we have to check. We can use two if statements to

check the two diagonals, similar to the if statements we used for rows and columns.

If we reach the end of our function, that means that nobody has won. Here, we can just return

a space.

Step 9: Print out which player has won if a player has won.

In our main method, we can use the function we just created to check if a player has won.

Hint: We can use conditionals to check if our function returns x or o. If it returns x, then
print that player 1 has won. If it returns o, then print that player 2 has won.
Step 10: Check if the game has ended in a tie.

Tic tac toe ends in a tie if nobody has won and the board is full. We already have checked if

someone has won. Now we just need to check if the board is full.

Let’s create a function that returns true if the board is full and false if there are still empty

spots on the board. Remember, an empty spot is a dash.

Hint: We can use nested for loops to iterate through each position on the board. Inside the
inner for loop, we can use a conditional to check if board[i][j] is equal to -, and if so, return
true.

Once we finish going through the nested for loops and find that no position on the board

equals a dash, then we know that the board is full so we can return true.
Step 11: Use a loop to keep the game going.

We can create a boolean called gameEnded and initially set it to false. Inside the if statement

where we check if a player has won or if it is a tie, we can set gameEnded to true.

We can make a while loop, with its condition simply being gameEnded, so that the program

keeps asking a player to enter a row and col until there is a winner or a tie.

If we run our program, we notice that the player doesn’t alternate every round. How can we

fix this?

Hint: If there is no winner and no tie, we can switch the player1 boolean by writing the
following: player1 = !player1. The ! means not, so if player1 was true, this line sets it
to not true, or false, and if player1 was false, this line sets it to not false, or true.

After the while loop is over, we can draw the board a final time so that both players can see

the final state of the board.

ADVANTAGE OF THE GAME:


Tic-Tac-Toe: 7 benefits and advantages:
1. Teaches strategy skills.
2. Develops logical thinking.
3. Improves the ability to concentrate and focus.
4. Teaches good sportsmanship.
5. Sets the foundation for learning more complex games. 
6. Provides a simple and fun way for the family to bond.
7. Develops problem-solving skills.

DISADVANTAGE OF THE GAME:


1. It can get boring knowing that you are going to win every single time.
2. The game usually takes less than a minute to play.
3. You usually need paper and a pencil/pen to play.
4. When you know how to win, the game isn’t very challenging.
5. It can get boring if every game ends in a tie. 
6. If you’re new to the game, you could be taken advantage of by players who know
the game’s winning strategies.
7. New versions of Tic-Tac-Toe have ruined the original version.

Why is tic-tac-toe a good game for kids?


This classic game contributes to children's developmental growth in numerous ways
including their understanding of predictability, problem solving, spatial reasoning,
hand-eye coordination, turn taking, and strategizing.

A game can be programmed as a finite state machine, with clearly defined states and
state transition functions, as follows:

FIGURE 1: WORKING OF TIC TAC TOE

1.  Let's Start with a 2-Player Console Non-OO Tic-Tac-Toe


Let us start with a 2-player console (non-graphics) version of Tic-Tac-Toe, where
player 'X' and player 'O' enter their moves successively, as shown below :
Player 'X', enter your move (row[1-3] column[1-3]): 2 2
| |
-----------
| X |
-----------
| |

Player 'O', enter your move (row[1-3] column[1-3]): 1 1


O | |
-----------
| X |
-----------
| |

Player 'X', enter your move (row[1-3] column[1-3]): 1 3


O | | X
-----------
| X |
-----------
| |

Player 'O', enter your move (row[1-3] column[1-3]): 3 1


O | | X
-----------
| X |
-----------
O | |

Player 'X', enter your move (row[1-3] column[1-3]): 2 2


This move at (2,2) is not valid. Try again...
Player 'X', enter your move (row[1-3] column[1-3]): 2 3
O | | X
-----------
| X | X
-----------
O | |

Player 'O', enter your move (row[1-3] column[1-3]): 2 1


O | | X
-----------
O | X | X
-----------
O | |

Player 'O' won!


How it works?

Non-OO programs (like C programs) are organized in methods (or functions), which
access common global variables. In non-OO Java, all the variables/methods shall be
declared static (i.e., they belong to the class instead of instances). The program starts
at the main() method. No instances are created.
A board game (such as Tic-tac-toe) is typically programmed as a state machine.
Depending on the current-state and the player's move, the game transits into the next-
state. In this example, I use a variable currentState to keep track of the current-
state of the game, and define named constants to denote the various states of the
game (PLAYING, DRAW, CROSS_WON, and NOUGHT_WON).  A method
called stepGame() is defined, which will be called to transit into next state.
Two methods are defined for printing the game
board, paintBoard() and paintCell(). The paintBoard() shall
call paintCell() to print each of the 9 cells.  This seems trivial here, but will be useful
in the object-oriented design to separate the board and cells into separate classes.

2.  A Console OO Tic-Tac-Toe

Let us convert the earlier non-OO version of Tic-Tac-Toe to object-oriented. The OO


version of this simple Tic-Tac-Toe is more complex than the non-OO version, because
Tic-Tac-Toe is a rather simple application. But OO design is a necessity to build a
complex application.

What is enumeration State

In our earlier version, we used int named-constants to represent the various game


states, as follows:

// Define named constants to represent the various states of the


game
public static final int PLAYING = 0;
public static final int DRAW = 1;
public static final int CROSS_WON = 2;
public static final int NOUGHT_WON = 3;

// The current state of the game


public static int currentState = PLAYING; // Assigned to a named
constant, which is easier to read
// and understand,
instead of an int number 0

This approach of using int named-constants is better than hardcoding the numbers in


the programming statements, but it is not ideal. This is because you may inadvertently
assign an int value outside the valid range to the variable currentState. For
example,

currentState = 99; // A logical error but can compile

JDK 5 introduces a new feature called enumeration, which is a special class for


storing an enumeration (list) of fixed items. In our case, we can define an enumeration
called State as follows:

/**
* The enum State defines the various game states of the TTT game
*/
public enum State { // to save as "State.java"
PLAYING, DRAW, CROSS_WON, NOUGHT_WON
}

To reference an item in an enum,


use enumName.itemName (e.g., State.PLAYING and State.DRAW), just like
referencing static variables of a class (e.g., Math.PI).
You can create an instance for an enum (just like creating an instance of a class) and
assign a value into it. We shall now declare the variable currentState as an instance
of State, which can take the value
of State.PLAYING, State.DRAW, State.CROSS_WON, and State.NOUGHT_WON.

State currentState; // declare variable currentState as


an instance of enum Gamee
currentState = Gtate.PLAYING; // assign a value (an enum item) to
the variable currentState

Take note that you can only assign a value defined in the enumeration (such
as State.PLAYING, State.DRAW), and NOT an arbitrary int value in the earlier
example. In other words, enum is SAFE!
Enumerations Seed
We shall also create an enum called Seed as follows.

/**
* This enum is used by:
* 1. Player: takes value of CROSS or NOUGHT
* 2. Cell content: takes value of CROSS, NOUGHT, or NO_SEED.
*
* We also attach a display icon (text or image) for each of the
item,
* and define the related variable/constructor/getter.
*
* Ideally, we should define two enums with inheritance, which is,
* however, not supported.
*/
public enum Seed { // to save as "Seed.java"
CROSS("X"), NOUGHT("O"), NO_SEED(" ");

// Private variable
private String icon;
// Constructor (must be private)
private Seed(String icon) {
this.icon = icon;
}
// Public Getter
public String getIcon() {
return icon;
}
}

This enum is used in two properties:


1. Player: uses values CROSS and NOUGHT.
2. Cell Content: uses values CROSS, NOUGHT, and NO_SEED.
(Ideally, we should create 2 enums with inheritance, but enum inheritance is not
supported in Java.)
Again, you need to use Seed.NO_SEED, Seed.CROSS, Seed.NOUGHT to refer to these
values, just like any public static final constants.
We also attach an icon to each of the enum items, by defining a private variable, a
private constructor and a public getter (as in a regular class). We can get the icon
via enumItem.getIcon().
We shall declare the variables currentPlayer and content as instances of
enum Player and CellContent.

private Seed currentPlayer; // declare variable currentPlayer as an


instance of enum Seed
currentPlayer = Seed.CROSS; // assign a value (an enum item) to the
variable currentPlayer

private Seed content; // cell's content


content = Seed.NO_SEED;
In brief, an enum is just a special class with a list of named-constants. But enum is safe
with additional features!
Classes Board and Cell

FIGURE 2 : FLOWCHART FOR GAME BOARD

Next, let's design the OO classes needed for our Tic-Tac-Toe game. Each class shall
maintain its own attributes and operations (variables and methods), and it can paint
itself in a graphics program.
We begin with two classes, a class Cell for each individual cell of the game board, and
a class Board for the 3x3 game board.
The Cell class has an instance variable called content (with package access), of the
type enum Seed. You can only assign a value from the enum's constants, such
as Seed.NO_SEED, Seed.CROSS, and Seed.NOUGHT, into content.
A Cell can paint() itself. You can use newGame() to reset all its properties, ready for
a new game.
The Board class composes of nine Cell instances, arranged in an 3×3 array
called cells (with package access), of the type Cell[][]. A Board can paint() itself,
and supports the state transition functions such
as initGame(), newGame() and stepGame() (see game state diagram).

3.  A Graphical Tic-Tac-Toe with Simple-OO

Let's rewrite the "console" version into a "graphics" version - a Java Swing application,
as illustrated. In this initial design, we do not separate the cell and board into dedicated
classes, but include them in the main class. We used an inner class GamePanel (that
extends JPanel) to do the custom drawing, and an anonymous inner class
for MouseListener.
The content-pane (of the top-level container JFrame) is set to BorderLayout.
The DrawCanvas (JPanel) is placed at the CENTER; while a status-bar (a JLabel) is
placed at the SOUTH (PAGE_END).
The class diagram is as follows:

FIGURE 3: GRAPHICAL
REPRESENTATION OF GAME
PROGRAM CODE:

import java.util.Scanner;
/**
* Tic-Tac-Toe: Two-player, console-based, non-graphics, non-OO version.
* All variables/methods are declared as static (i.e., class)
* in this non-OO version.
*/
public class TTTConsoleNonOO {
// Define named constants for:
// 1. Player: using CROSS and NOUGHT
// 2. Cell contents: using CROSS, NOUGHT and NO_SEED
public static final int CROSS = 0;
public static final int NOUGHT = 1;
public static final int NO_SEED = 2;

// The game board


public static final int ROWS = 3, COLS = 3; // number of rows/columns
public static int[][] board = new int[ROWS][COLS]; // EMPTY, CROSS, NOUGHT

// The current player


public static int currentPlayer; // CROSS, NOUGHT

// Define named constants to represent the various states of the game


public static final int PLAYING = 0;
public static final int DRAW = 1;
public static final int CROSS_WON = 2;
public static final int NOUGHT_WON = 3;
// The current state of the game
public static int currentState;

public static Scanner in = new Scanner(System.in); // the input Scanner

/** The entry main method (the program starts here) */


public static void main(String[] args) {
// Initialize the board, currentState and currentPlayer
initGame();

// Play the game once


do {
// currentPlayer makes a move
// Update board[selectedRow][selectedCol] and currentState
stepGame();
// Refresh the display
paintBoard();
// Print message if game over
if (currentState == CROSS_WON) {
System.out.println("'X' won!\nBye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won!\nBye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw!\nBye!");
}
// Switch currentPlayer
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game over
}

/** Initialize the board[][], currentState and currentPlayer for a new


game*/
public static void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = NO_SEED; // all cells empty
}
}
currentPlayer = CROSS; // cross plays first
currentState = PLAYING; // ready to play
}

/** The currentPlayer makes one move (one step).


Update board[selectedRow][selectedCol] and currentState. */
public static void stepGame() {
boolean validInput = false; // for input validation
do {
if (currentPlayer == CROSS) {
System.out.print("Player 'X', enter your move (row[1-3] column[1-
3]): ");
} else {
System.out.print("Player 'O', enter your move (row[1-3] column[1-
3]): ");
}
int row = in.nextInt() - 1; // array index starts at 0 instead of 1
int col = in.nextInt() - 1;
if (row >= 0 && row < ROWS && col >= 0 && col < COLS
&& board[row][col] == NO_SEED) {
// Update board[][] and return the new game state after the move
currentState = stepGameUpdate(currentPlayer, row, col);
validInput = true; // input okay, exit loop
} else {
System.out.println("This move at (" + (row + 1) + "," + (col + 1)
+ ") is not valid. Try again...");
}
} while (!validInput); // repeat if input is invalid
}

/**
* Helper function of stepGame().
* The given player makes a move at (selectedRow, selectedCol).
* Update board[selectedRow][selectedCol]. Compute and return the
* new game state (PLAYING, DRAW, CROSS_WON, NOUGHT_WON).
* @return new game state
*/
public static int stepGameUpdate(int player, int selectedRow, int
selectedCol) {
// Update game board
board[selectedRow][selectedCol] = player;
// Compute and return the new game state
if (board[selectedRow][0] == player // 3-in-the-row
&& board[selectedRow][1] == player
&& board[selectedRow][2] == player
|| board[0][selectedCol] == player // 3-in-the-column
&& board[1][selectedCol] == player
&& board[2][selectedCol] == player
|| selectedRow == selectedCol // 3-in-the-diagonal
&& board[0][0] == player
&& board[1][1] == player
&& board[2][2] == player
|| selectedRow + selectedCol == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == player
&& board[1][1] == player
&& board[2][0] == player) {
return (player == CROSS) ? CROSS_WON : NOUGHT_WON;
} else {
// Nobody win. Check for DRAW (all cells occupied) or PLAYING.
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == NO_SEED) {
return PLAYING; // still have empty cells
}
}
}
return DRAW; // no empty cell, it's a draw
}
}

/** Print the game board */


public static void paintBoard() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
paintCell(board[row][col]); // print each of the cells
if (col != COLS - 1) {
System.out.print("|"); // print vertical partition
}
}
System.out.println();
if (row != ROWS - 1) {
System.out.println("-----------"); // print horizontal partition
}
}
System.out.println();
}

/** Print a cell having the given content */


public static void paintCell(int content) {
switch (content) {
case CROSS: System.out.print(" X "); break;
case NOUGHT: System.out.print(" O "); break;
case NO_SEED: System.out.print(" "); break;
}
}
}

OUTPUT:
RESULT :
THUS THE JAVA APPLICATION USING TIC TAC TOE GAME WAS DEVELOPED AND EXECUTED
SUCCESFULLY

**Thank You**

You might also like