Hello coders, Welcome to my new Tic Tac Toe Java Code Against Computer tutorial and in this tutorial, you will learn to make Tic Tac Toe game in Java where game will take place between human and computer. The program’s Source code is given at the end of the tutorial to download.
I am pretty sure all of you must have played Tic Tac Toe game in your childhood. But today lets make this game in Java and play with computer.
But before proceeding to coding part, we must have to know logic behind Tic Tac game so let’s see what Tic Tac Toe game is and how it is played.
An Introduction To Tic Tac Toe Game between Human And Computer
What is Tic Tac Toe game?
- Tic Tac Toe is a two player game where each player is assigned a marking symbol X or O.
- In a 3×3 grid, each player have to place their symbol.
- The player who succeeds in placing three of their marks in a diagonal, horizontal, or vertical row is the winner.
Rules Of Playing Tic Tac Toe Game
The Tic Tac Toe game takes place in following steps.
- In first step, we have to consist a 3×3 grid.
- It is a two player game so each player is assigned with a symbol X or O.
- In first turn, the first player(whosesoever turn) will place his/her marking symbol in any of the 9 cells.
- In second turn, the second player will place his/her marking symbol in any of available 8 cells.
- This process will go on until any of the players will make three successive square grids of the same sign either vertically, horizontally or diagonally.
- If the player having X marking symbol will achieve the above result then he/she will win or if the player having O marking symbol will achieve the above result then he/she will win.
- If the grid contains no free cell left and none of the above conditions arrived, the Game will end with a Draw.
So guys, now you have a general idea of tic tac toe game. Are you excited to create this awesome game in java? I know you are waiting for coding part so without wasting time let’s get started.
How To Create Tic Tac Toe Game Against Computer In Java?
Tic Tac Toe is a two player game which is played by generally two humans but in this tutorial you will learn to make this game which will played by human and computer.
Let’s see tic tac toe code in java.
Printing The Board
First of all we will print a 3×3 board grid. This board is consists of 2D array. Let’s see how to do that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class TicTacToeGame { public static void main(String[] args) { char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; printBoard(board); } private static void printBoard(char[][] board) { System.out.print((board[0][0])); System.out.print("|"); System.out.print((board[0][1])); System.out.print("|"); System.out.println((board[0][2])); System.out.println("-----"); System.out.print((board[1][0])); System.out.print("|"); System.out.print((board[1][1])); System.out.print("|"); System.out.println((board[1][2])); System.out.println("-----"); System.out.print((board[2][0])); System.out.print("|"); System.out.print((board[2][1])); System.out.print("|"); System.out.println((board[2][2])); } } |
What We Did?
- We have created board using 2d array of character types.
- We have defined a function printBoard() which will print the board.
Function To Place The Player’s Moves
Here we will create a function that will used to place the movement of players.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
private static void placeMove(char[][] board, String position, char symbol) { switch(position) { case "1": board[0][0] = symbol; break; case "2": board[0][1] = symbol; break; case "3": board[0][2] = symbol; break; case "4": board[1][0] = symbol; break; case "5": board[1][1] = symbol; break; case "6": board[1][2] = symbol; break; case "7": board[2][0] = symbol; break; case "8": board[2][1] = symbol; break; case "9": board[2][2] = symbol; break; default: System.out.println(":("); } |
Checking The Validation Of Movement
Now we will check the validation of movements of players.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
private static boolean isValidMove (char[][] board, String position) { switch(position) { case "1": return (board[0][0] == ' '); case "2": return (board[0][1] == ' '); case "3": return (board[0][2] == ' '); case "4": return (board[1][0] == ' '); case "5": return (board[1][1] == ' '); case "6": return (board[1][2] == ' '); case "7": return (board[2][0] == ' '); case "8": return (board[2][1] == ' '); case "9": return (board[2][2] == ' '); default: return false; } |
Asking For Human Move
Now we will create a function that will used to ask and place the user’s move.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static void playerTurn(char[][] board, Scanner scanner) { String userInput; while (true) { System.out.println("Enter Your Move!!"); userInput = scanner.nextLine(); if (isValidMove(board, userInput)){ break; } else { System.out.println(userInput + " is not a valid move."); } } placeMove(board, userInput, 'X'); } |
What We Did?
- We have asked the user to enter their input.
- Then checked user’s input is valid or not. If the user input will be valid then it will display the board filled with user’s marking symbol(X) at the place of user input. Otherwise it will display a message that the input from user is not a valid move.
Placing Computer Move
Now we have to place the computer move on the board. so the code is here.
1 2 3 4 5 6 7 8 9 10 11 12 |
private static void computerTurn(char[][] board) { Random rand = new Random(); int computerMove; while (true) { computerMove = rand.nextInt(9) + 1; if (isValidMove(board, Integer.toString(computerMove))) { break; } } System.out.println("Computer choose " + computerMove); placeMove(board, Integer.toString(computerMove), 'O'); } |
What We Did?
- Computer will choose random path so we have used random class of java to achieve this task.
- So to use random class we have imported Random class on top of our program.
- Computer will choose random number from 1-9 so we have used rand.nextInt(9) + 1.Â
- Then we have checked validation of computer move. If computer move is valid then it place computer marking symbol at the computer move on the board.
Displaying The Winning Result
In this part we will display the winning result of players.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
private static boolean isGameFinished(char[][] board) { if (hasContestantWon(board, 'X')) { printBoard(board); System.out.println("Player wins!"); return true; } if (hasContestantWon(board, 'O')) { printBoard(board); System.out.println("Computer wins!"); return true; } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j] == ' ') { return false; } } } printBoard(board); System.out.println("The game ended in a tie!"); return true; } private static boolean hasContestantWon(char[][] board, char symbol) { if ((board[0][0] == symbol && board [0][1] == symbol && board [0][2] == symbol) || (board[1][0] == symbol && board [1][1] == symbol && board [1][2] == symbol) || (board[2][0] == symbol && board [2][1] == symbol && board [2][2] == symbol) || (board[0][0] == symbol && board [1][0] == symbol && board [2][0] == symbol) || (board[0][1] == symbol && board [1][1] == symbol && board [2][1] == symbol) || (board[0][2] == symbol && board [1][2] == symbol && board [2][2] == symbol) || (board[0][0] == symbol && board [1][1] == symbol && board [2][2] == symbol) || (board[0][2] == symbol && board [1][1] == symbol && board [2][0] == symbol) ) { return true; } return false; } |
What We Did?
- We have defined a method hasContastantWon() that will check the winner contestant.
- And in the isGameFinished() function We have used if statement to check the winning result of players.
- If the hasContastantWon() method will return X marking symbol then human will win, and if hasContastantWon() method will return O marking symbol then computer will win otherwise the game will end with a tie.
Use A Loop To Keep The Game Going
Now at last we will write following code inside main() method to repeat all the process until the game is finished.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
while (true) { playerTurn(board, scanner); if (isGameFinished(board)){ break; } printBoard(board); computerTurn(board); if (isGameFinished(board)){ break; } printBoard(board); } scanner.close(); |
Complete Code Of Tic Tac Toe Java Code Against Computer
Here is the complete code of 3×3 tic-tac-toe game in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
import java.util.Random; import java.util.Scanner; public class TicTacToeGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; printBoard(board); while (true) { playerTurn(board, scanner); if (isGameFinished(board)){ break; } printBoard(board); computerTurn(board); if (isGameFinished(board)){ break; } printBoard(board); } scanner.close(); } private static boolean isGameFinished(char[][] board) { if (hasContestantWon(board, 'X')) { printBoard(board); System.out.println("Player wins!"); return true; } if (hasContestantWon(board, 'O')) { printBoard(board); System.out.println("Computer wins!"); return true; } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j] == ' ') { return false; } } } printBoard(board); System.out.println("The game ended in a tie!"); return true; } private static boolean hasContestantWon(char[][] board, char symbol) { if ((board[0][0] == symbol && board [0][1] == symbol && board [0][2] == symbol) || (board[1][0] == symbol && board [1][1] == symbol && board [1][2] == symbol) || (board[2][0] == symbol && board [2][1] == symbol && board [2][2] == symbol) || (board[0][0] == symbol && board [1][0] == symbol && board [2][0] == symbol) || (board[0][1] == symbol && board [1][1] == symbol && board [2][1] == symbol) || (board[0][2] == symbol && board [1][2] == symbol && board [2][2] == symbol) || (board[0][0] == symbol && board [1][1] == symbol && board [2][2] == symbol) || (board[0][2] == symbol && board [1][1] == symbol && board [2][0] == symbol) ) { return true; } return false; } private static void computerTurn(char[][] board) { Random rand = new Random(); int computerMove; while (true) { computerMove = rand.nextInt(9) + 1; if (isValidMove(board, Integer.toString(computerMove))) { break; } } System.out.println("Computer chose " + computerMove); placeMove(board, Integer.toString(computerMove), 'O'); } private static boolean isValidMove (char[][] board, String position) { switch(position) { case "1": return (board[0][0] == ' '); case "2": return (board[0][1] == ' '); case "3": return (board[0][2] == ' '); case "4": return (board[1][0] == ' '); case "5": return (board[1][1] == ' '); case "6": return (board[1][2] == ' '); case "7": return (board[2][0] == ' '); case "8": return (board[2][1] == ' '); case "9": return (board[2][2] == ' '); default: return false; } } private static void playerTurn(char[][] board, Scanner scanner) { String userInput; while (true) { System.out.println("Enter Your Move!!"); userInput = scanner.nextLine(); if (isValidMove(board, userInput)){ break; } else { System.out.println(userInput + " is not a valid move."); } } placeMove(board, userInput, 'X'); } private static void placeMove(char[][] board, String position, char symbol) { switch(position) { case "1": board[0][0] = symbol; break; case "2": board[0][1] = symbol; break; case "3": board[0][2] = symbol; break; case "4": board[1][0] = symbol; break; case "5": board[1][1] = symbol; break; case "6": board[1][2] = symbol; break; case "7": board[2][0] = symbol; break; case "8": board[2][1] = symbol; break; case "9": board[2][2] = symbol; break; default: System.out.println(":("); } } private static void printBoard(char[][] board) { System.out.print((board[0][0])); System.out.print("|"); System.out.print((board[0][1])); System.out.print("|"); System.out.println((board[0][2])); System.out.println("-----"); System.out.print((board[1][0])); System.out.print("|"); System.out.print((board[1][1])); System.out.print("|"); System.out.println((board[1][2])); System.out.println("-----"); System.out.print((board[2][0])); System.out.print("|"); System.out.print((board[2][1])); System.out.print("|"); System.out.println((board[2][2])); } } |
So now it’s time to play this Tic Tac Toe game. Here is the Output.
Tic Tac Toe Java Code Against Computer Source Code Download
Guys, If you want to download the source code of the above program, then you can download the source code by clicking on the below download button.
So guys we have successfully completed Tic Tac Toe Java Code Against Computer Tutorial. I hope you have enjoyed this tutorial of making Tic Tac Toe Java 2d array against computer game. But still if you have any query then feel free to ask in comment section. And don’t forget to stay tuned with Tutorials field to learn this type of awesome games and tutorials. HAPPY CODING.
People Are Also Reading…
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Menu Driven Program in Java Using Switch Case
- Calculator Program in Java Swing/JFrame with Source Code
- Registration Form in Java With Database Connectivity
- How to Create Login Form in Java Swing
- Text to Speech in Java
- How to Create Splash Screen in Java
- Java Button Click Event
- 11 Best Site to Learn Java Online for Free