This post contains a total of 12+ Hand-Picked Java Tic Tac Toe examples with source code. All the Tic Tac Toe programs are made using Java Programming Language.
You can use the source code of these programs for educational use with credits to the original owner.
Related Posts
Click a Code to Copy it.
1. By Toader Alin Ionut
Made by Toader Alin Ionut. A simple Tic Tac Toe program made using Java. ( Source )
import java.util.HashSet;
import java.util.Scanner;
import java.io.*;
public class ttt {
static HashSet<Integer> our_set = new HashSet<Integer>();
static HashSet<Integer> comp_set = new HashSet<Integer>();
public static void main(String[] args) {
char [][] board = {
{' ', '|',' ','|',' '},
{'-', '|','-','|','-'},
{' ', '|',' ','|',' '},
{'-', '|','-','|','-'},
{' ', '|',' ','|',' '},
};
System.out.println("Tic-Tac-Toe Game");
print_board(board);
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("Enter values from, 1-9: ");
int user_position = sc.nextInt();
while(our_set.contains(user_position)||comp_set.contains(user_position)) {
System.out.println();
System.out.print("Retry, enter values from, 1-9: ");
user_position = sc.nextInt();
}
p_holder(board,user_position,"You");
String res = check_winner();
if(res.length()>0) {
System.out.println(res);
break;
}
int cpu_position = gen_random();
while(our_set.contains(cpu_position)||comp_set.contains(cpu_position)) {
cpu_position = gen_random();
}
p_holder(board,cpu_position,"Comp");
res = check_winner();
if(res.length()>0) {
System.out.println(res);
break;
}
}
}
static String check_winner() {
HashSet<Integer> r1 = new HashSet<Integer>();
r1.add(1);r1.add(2);r1.add(3);
HashSet<Integer> r2 = new HashSet<Integer>();
r2.add(4);r2.add(5);r2.add(6);
HashSet<Integer> r3 = new HashSet<Integer>();
r3.add(7);r1.add(8);r1.add(9);
HashSet<Integer> c1 = new HashSet<Integer>();
c1.add(1);c1.add(4);r1.add(7);
HashSet<Integer> c2 = new HashSet<Integer>();
c2.add(2);c2.add(5);c2.add(8);
HashSet<Integer> c3 = new HashSet<Integer>();
c3.add(3);r1.add(6);r1.add(9);
HashSet<Integer> d1 = new HashSet<Integer>();
d1.add(1);d1.add(5);r1.add(9);
HashSet<Integer> d2 = new HashSet<Integer>();
d2.add(3);d2.add(5);d2.add(7);
HashSet<HashSet> set = new HashSet<HashSet>();
set.add(r1);set.add(r2);set.add(r3);
set.add(c1);set.add(c2);set.add(c3);
set.add(d1);set.add(d2);
for(HashSet c:set) {
if(our_set.contains(c)) {
return "You won";
}
else if(comp_set.contains(c)) {
return "You lost";
}
if(our_set.size()+comp_set.size()==9) {
return "Draw";
}
}
return "";
}
static int gen_random() {
int max=9;
int min=1;
int range = max-min+1;
int res = (int)(Math.random()*range) + min;
return res;
}
static void print_board(char[][] board) {
for(int r=0;r<board.length;r++) {//r=rows, c=columns
for(int c=0;c<board.length;c++) {
System.out.print(board[r][c]);
}
System.out.println();
}
}
static void p_holder(char[][] board, int position, String user) {
char symb = 'X';
if(user.equals("You")) {
symb = 'X';
our_set.add(position);
}
else if(user.equals("Comp")) {
symb='O';
comp_set.add(position);
}
switch(position) {
case 1:
board[0][0]=symb;
break;
case 2:
board[0][2]=symb;
break;
case 3:
board[0][4]=symb;
break;
case 4:
board[2][0]=symb;
break;
case 5:
board[2][2]=symb;
break;
case 6:
board[2][4]=symb;
break;
case 7:
board[4][0]=symb;
break;
case 8:
board[4][2]=symb;
break;
case 9:
board[4][4]=symb;
break;
default:
System.out.println("Invalid Input");
}
print_board(board);
}
}
2. By Hadi Najafi
Made by Hadi Najafi. ( Source )
package javalike;
import java.util.*;
//https://t.me/javalike Java Tutorial
/**
* Play TicTacToe - using 2D arrays, and a class from scratch
* 1) Look at print board (note static X and O variables)
* 2) Go over new code for reading in a move and checking if its occupied or not
* 3) Write check winner code for X and then generalize it
*
*/
public class TicTacToe
{
// Do we need static class variables?
// what should our instance variables be?
private String[][] board;
static String X = "X";
static String O = "O";
/**
* Constructor for objects of class TicTacToe
*/
public TicTacToe()
{
// initialize instance variables
board = new String[3][3];
}
/**
* Print out the tictactoe board
*/
public void printBoard()
{
System.out.println();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == null) {
System.out.print("_");
} else {
System.out.print(board[i][j]);
}
if (j < 2) {
System.out.print("|");
} else {
System.out.println();
}
}
}
System.out.println();
}
/* Check if player wins. Check right after X makes a play
*
*/
public Boolean checkWinner(String play) {
int playInRow = 0;
int playD1 = 0;
int playD2 = 0;
int[] playInColumn = new int[board[0].length]; // assumes square board
for (int i = 0; i < board.length; i++) {
playInRow = 0;
for (int j = 0; j < board[i].length; j++) {
if (null == board[i][j]) {
continue;
}
if (board[i][j].equals(play)) {
playInRow++;
playInColumn[j]++;
if (i == j) {
playD1++;
} else if (2 == i + j) {
playD2++;
}
}
}
if (playInRow == 3) {
return true;
}
}
if (3 == playD1 || 3 == playD2) {
return true;
}
for (int i = 0; i < playInColumn.length; i++) {
if (playInColumn[i] == 3) {
return true;
}
}
return false;
}
/*
* makeMove gets a legal coordinate for the move that is not occupied
* and marks it with the play string
*/
public void makeMove(Scanner stdin, String play) {
int r;
int c;
Boolean goodInput = false;
while(!goodInput) {
r = -1;
c = -1;
System.out.println ("Enter coordinates to play your " + play);
if (stdin.hasNextInt()) { // must be integers
r = stdin.nextInt();
}
if (stdin.hasNextInt()) {
c = stdin.nextInt();
}
else {
stdin.nextLine(); // consume a line without an integer
System.out.println("Both inputs must be integers between 0 and 2.");
continue;
}
// must be in the right coordinate range
if ((r < 0) || (r > 2) || (c < 0) || (c > 2)) {
System.out.println("Both inputs must be integers between 0 and 2.");
continue;
}
// make sure the space is not occupied
else if (board[r][c] != null ){
System.out.println("That location is occupied");
continue;
}
else {
board[r][c] = play;
return;
}
}
return;
}
public static void main(String[] args) {
TicTacToe ttt = new TicTacToe(); // allocate a board
Scanner stdin = new Scanner(System.in); // read from standard in
int moves = 0;
System.out.println("Let's play TicTacToe -- X goes first");
ttt.printBoard();
while (moves < 9) {
ttt.makeMove(stdin, ttt.X);
moves++;
if (moves > 4) {
if (ttt.checkWinner(X)) {
System.out.println(X + " You Win!!!");
break;
}
}
ttt.printBoard();
ttt.makeMove(stdin, ttt.O);
moves++;
if (moves > 4) {
if (ttt.checkWinner(O)) {
System.out.println(O + " You Win!!!");
break;
}
}
ttt.printBoard();
}
}
}
3. By Robert Atkins
Made by Robert Atkins. Simple Java Tic Tac Toe game. ( Source )
import java.util.Scanner;
import java.util.HashMap;
import java.util.Random;
public class TicTacToe
{
private String Winner = "";
String Line = "";
private boolean gameOver = false;
private String playerMarker = "X";
private String aiMarker = "O";
Scanner in = new Scanner(System.in);
private String a="1",b="2",c="3",d="4",e="5",f="6",g="7",h="8",i="9";
public HashMap<Integer,String> game = new HashMap<Integer,String>();
public static void main(String[] args) {
System.out.print(new Board().build(new TicTacToe().game));
}
/**
* constructs the game itself during initialization
*/
public TicTacToe(){
game.put(1,a);
game.put(2,b);
game.put(3,c);
game.put(4,d);
game.put(5,e);
game.put(6,f);
game.put(7,g);
game.put(8,h);
game.put(9,i);
}
public TicTacToe(int x){
while(!gameOver) {
buildBoard();
playerGuess();
gameOver=GameOver();
if (gameOver==true) {
break;
}
System.out.println();
AIGuess();
gameOver = GameOver();
System.out.println();
}
buildBoard();
if (Winner.equals("Player")) {
System.out.println("Congratulations, you won the game!");
return;
}if(Winner.equals("AI")) {
System.out.println("Sorry, the computer won! Better luck next time!");
return;
}
else {
System.out.println("It's a tie!");
}
}
/**
* determines whether the game has been completed in either a tie or win, by the
* possible win conditions.
* @return
* returns a boolean flag after checking conditions
*/
public boolean GameOver() {
int index = 1;
int x=index;
for(int i = 1;i<=3;i++) {
if(game.get(x).equals(game.get(x+3)) && game.get(x+3).equals(game.get(x+6))){
whoWon(x);
return true;
}else {
x++;
}
}
x=index;
for(int i=1;i<=3;i++) {
if(game.get(x).equals(game.get(x+1)) && game.get(x+1).equals(game.get(x+2))) {
whoWon(x);
return true;
}else {
x+=3;
}
}
if(game.get(1).equals(game.get(5)) && game.get(5).equals(game.get(9))){
whoWon(1);
return true;
}if (game.get(3).equals(game.get(5)) && game.get(5).equals(game.get(7))){
whoWon(3);
return true;
}
else {
int counter = 0;
for(int i =1; i<=9; i++) {
if(game.get(i).equals("X") || game.get(i).equals("O")) {
counter++;
}
}
if(counter==9) {
return true;
}
return false;
}
}
/**
* creates a choice for the AI and checks to make sure its viable.
* @return the value chosen 6
*/
public int AIGuess() {
int guess = new Random().nextInt(9)+1;
if (isOkToPlay(guess)) {
placeMarker(guess,aiMarker);
return 1;
}else
return AIGuess();
}
/**
* places a marker on the board for either the player or the AI.
* @param a the position at which the marker is to be played
* @param marker the object to be played whether it be the player marker "X"
* or the AI marker "O"
*/
public void placeMarker(int a,String marker) {
game.replace(a, marker);
}
/**
* determines if the specified area has been played on or not.
* @param a the area that was chosen to play on
* @return a boolean value representing whether it is ok to play or not.
*/
public boolean isOkToPlay(int a) {
if (game.get(a).equals("X") || game.get(a).equals("O")) {
return false;
}else {
return true;
}
}
/**
* gathers the user input and checks to see if it is ok to play or not.
* @return a recursion statement so that the method will run again, otherwise if its
* ok to play it returns a 1.
*/
public int playerGuess() {
int guess;
System.out.println("Please enter a number to place an \"x\" on the board at the "+
"location designated by the number! you cannot place a mark \non a spot that already"
+ " has a X or O.");
guess = in.nextInt();
if ((guess>9) || (guess<1)) {
System.out.println("Error: you must enter a number between 1 and 9!");
return playerGuess();
}else if(isOkToPlay(guess)) {
placeMarker(guess,playerMarker);
return 1;
}else {
System.out.println("Error: that position has already been played!");
return playerGuess();
}
}
/**
* determines who won the game
* @param x is used to determine who won by using in conjunction with the GameOver
* method only the value that was determined to have won the game would be assigned
* to x so we use x as a key to access the winners marker.
*/
public void whoWon(int x) {
if (game.get(x).equals("X")) {
Winner = "Player";
}if(game.get(x).equals("O")) {
Winner = "AI";
}
}
}
public class Board{
public String build(HashMap<Integer,String> game) {
String board = "";
String blank = "";
for(int i = 1; i <=9; i++){
if((i%3)==0){
board += game.get(i) + "\n";
if (i!=9)
board += placeLine(9, blank);
}else
board += game.get(i)+ " | ";
}
return board;
}
public String placeLine(int x, String line){
if(x==0) {
line +="\n";
return line;
}
else{
line += "-";
return placeLine(x-1, line);
}
}
}
/*
1 | 2 | 3
----------
4 | 5 | 6
----------
7 | 8 | 9
*/
4. By Sher Thblay
Made by Sher Thblay. ( Source )
import java.util.*;
public class Main {
// stores scores
public static int player1Score = 0 ;
public static int player2Score = 0 ;
public static int drawScore = 0 ;
public static String player1 = ".";
public static String player2 = ".";
public static String[][] gameBoard = {
{".",".","."},
{".",".","."},
{".",".","."}};
public static HashMap<Integer, int[]> moves = new HashMap<>();
public static void moveSet(){
int[][] move = {{0,0},{0,1},{0,2},
{1,0},{1,1},{1,2},
{2,0},{2,1},{2,2}};
for(int i = 1 ; i < 10 ; i++)
moves.put(i,move[i-1]);
}
// for printing ==========
public static String h(String a,int b){
String result = "";
for(int i = 0 ; i < b ; i ++)result+=a;
return result;
}
public static void gamePrint(String[][] board){
for(int i = 0 ; i < 3 ; i ++){
for(int x = 0 ;x <3 ;x ++)
System.out.print("+"+h("-",3));
System.out.print("+\n");
for(int j = 0 ; j < 3 ; j ++)
System.out.print("| "+board[i][j]+" ");
System.out.print("|\n");
}
for(int x = 0 ;x <3 ;x ++)
System.out.print("+"+h("-",3));
System.out.print("+\n");
}
//==============
public static boolean GameRun(){
// check both diagonals
int full = 0;
String diagonal1 = "";
String diagonal2 = "";
boolean repeat = true;
for(int i = 0 ; i < 3 ; i ++ ){
// check horizontal
String horizontal = "";
// check vertical
String vertical = "";
//check diagonal
for(int j = 0 ; j < 3 ; j++){
horizontal += gameBoard[i][j];
vertical += gameBoard[j][i];
// if count all x and o to the board if 9 return False
if(!gameBoard[i][j].equals("."))full+=1;
}
if(horizontal.equals("xxx") || horizontal.equals("ooo") ||
vertical.equals("xxx") || vertical.equals("ooo"))
return false;
// check both cross
diagonal1 += gameBoard[i][i];
diagonal2 += gameBoard[i][2-i];
}
if(diagonal1.equals("xxx") ||diagonal1.equals("ooo") ||
diagonal2.equals("xxx") || diagonal2.equals("ooo"))
return false;
// if full add drawscore
if(full == 9)
drawScore +=1 ;
return full != 9;
}
public static void main(String[] args) {
String running = "x";
while(running.equals("x")){
moveSet();
Scanner players = new Scanner(System.in);
//pick 1st player [x or o]
while(!player1.equals("x") && !player1.equals("o")){
System.out.print("pick [x or o]");
player1 = players.nextLine();
}
// automatic player2
player2 = player1.equals("o")?"x":"o";
// if o then player1 is first else player 2
String first[] = {
player1.equals("o")? player1:player2 ,
player1.equals("x")? player1:player2
};
int count = 0 ;
// compare last draw score
int lastDraw = drawScore;
// last letter to win the game to identify which player
String last = "";
System.out.println("Player1 : "+player1);
System.out.println("Player2 : "+player2);
while(GameRun()){
int[] move;
// if the move is not valid the repeat
do{
System.out.print("Player : "+first[count%2]+"\nPick [1-9] :");
int pick = new Scanner(System.in).nextInt();
// using key and value using hashmap
move = moves.get(pick);
}while(gameBoard[move[0]][move[1]] != ".");
// if Done changePlayer and keep track the last player
gameBoard[move[0]][move[1]] = first[count%2] ;
last =first[count%2] ;
count +=1;
//player1 = player1.equals("x")?"o":"x";
gamePrint(gameBoard);
}
// System.out.println(validMove(gameBoard,9));
// if drawScore is the same as before
// then increment player score else increase the draw score
// if draw score increases then dont increase player score
if(lastDraw == drawScore)
if(player1.equals(last))
player1Score++ ;
else
player2Score++;
System.out.println("Player1 score :" + player1Score );
System.out.println("Player2 score :" + player2Score );
System.out.println("draw score :"+ drawScore );
// exit the game
System.out.print("\n[x:continue] Try Again ?");
running = new Scanner(System.in).nextLine();
System.out.println("============");
//resets the game
for(int i = 0 ; i < 3 ;i++ )
for(int j = 0 ; j < 3 ; j++)
gameBoard[i][j] =".";
// end
}
}
}
5. By Igor Castro
Made by Igor Castro. ( Source )
import java.util.Scanner;
public class Program
{
public class TTT{
private char board[][];
private char playerMark;
public void TTT(){
}
public void initializeBoard(){
// checa as linhas
for(int i = 0; i < 3;i++){
// checa as colunas
for(int j = 0; j< 3; j++){
board[i][j] = '-';
}
}
}
public void drawBoard(){
System.out.println("-------------");
for(int i=0;i < 3; i++){
System.out.print("| ");
for(int j= 0;j < 3; j++){
System.out.print(board[i][j]+" | ");
}
System.out.println();
System.out.println("-------------");
}
}
public boolean isFull(){
}
public boolean checkForWin(){
return (checkRowsForWin() || checkColumnsForWin() || checkDiagForWin());
}
public boolean checkRowsForWin(){
for(int i= 0; i< 3; i++){
if(checkRowColWin(board[i][0],board[i][1],board[i][2]==true)){
return true;
}else{
return false;
}
}
}
public boolean checkColumnsForWin(){
for(int j= 0;j < 3;j++){
if(checkRowColWin(board[0][j],board[1][j],board[2][j]==true)){
return true;
}else{
return false;
}
}
}
public boolean checkDiagForWin(){
return (checkRowColWin(board[0][0],board[1][1],board[2][2]) || checkRowColWin(board[0][2],board[1][1],board[2][0]));
}
public boolean checkRowColWin(char c1, char c2, char c3){
return (c1!='-' && c1==c2 && c2==c3);
}
public void changePlayer(){
if(playerMark=='X'){
playerMark = '0';
}else{
playerMark = 'X';
}
}
public boolean placeMark(int row, int col){
if(row > 0 && col < 3){
if(board[row][col]=='-'){
board[row][col] = playerMark;
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TTT game = new TTT();
game.initializeBoard();
System.out.println("Jogo da Velha");
// GameLoop
do
{
System.out.println("Estado atual da mesa:");
// pinta a mesa
game.drawBoard();
int row;
int col;
do
{
System.out.println("Player "+game.getplayerMark()+"Entre com os valores da linha e coluna:");
row = scan.nextInt() - 1;
col = scan.nextInt() - 1;
}while(!game.placeMark(row,col));
game.changePlayer();
}while(!game.checkForWin() && !game.isFull());
if(game.isFull && !game.checkForWin()){
System.out.println("O jogo e moleza!");
}else{
System.out.println(" Status atual do jogo:");
game.drawBoard();
game.changePlayer();
System.out.println(Character.toUpperCase(game.getplayerMark())+"Wins!");
}
}
}
6. By Lucas Ostrander
Made by Lucas Ostrander. Tic-Tac-Toe: Two-player console, non-graphics, non-OO version. All variables/methods are declared as static (belong to the class) in the non-OO version. ( Source )
import java.util.Scanner;
public class TTTConsoleNonOO2P {
// Name-constants to represent the seeds and cell contents
public static final int EMPTY = 0;
public static final int CROSS = 1;
public static final int NOUGHT = 2;
// Name-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 game board and the game status
public static final int ROWS = 3, COLS = 3; // number of rows and columns
public static int[][] board = new int[ROWS][COLS]; // game board in 2D array
// containing (EMPTY, CROSS, NOUGHT)
public static int currentState; // the current state of the game
// (PLAYING, DRAW, CROSS_WON, NOUGHT_WON)
public static int currentPlayer; // the current player (CROSS or NOUGHT)
public static int currntRow, currentCol; // current seed's row and column
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 game-board and current status
initGame();
// Play the game once
do {
playerMove(currentPlayer); // update currentRow and currentCol
updateGame(currentPlayer, currntRow, currentCol); // update currentState
printBoard();
// Print message if game-over
if (currentState == CROSS_WON) {
System.out.println("'X' won! Bye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won! Bye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw! Bye!");
}
// Switch player
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game-over
}
/** Initialize the game-board contents and the current states */
public static void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = EMPTY; // all cells empty
}
}
currentState = PLAYING; // ready to play
currentPlayer = CROSS; // cross plays first
}
/** Player with the "theSeed" makes one move, with input validation.
Update global variables "currentRow" and "currentCol". */
public static void playerMove(int theSeed) {
boolean validInput = false; // for input validation
do {
if (theSeed == 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] == EMPTY) {
currntRow = row;
currentCol = col;
board[currntRow][currentCol] = theSeed; // update game-board content
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 until input is valid
}
/** Update the "currentState" after the player with "theSeed" has placed on
(currentRow, currentCol). */
public static void updateGame(int theSeed, int currentRow, int currentCol) {
if (hasWon(theSeed, currentRow, currentCol)) { // check if winning move
currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON;
} else if (isDraw()) { // check for draw
currentState = DRAW;
}
// Otherwise, no change to currentState (still PLAYING).
}
/** Return true if it is a draw (no more empty cell) */
// TODO: Shall declare draw if no player can "possibly" win
public static boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == EMPTY) {
return false; // an empty cell found, not draw, exit
}
}
}
return true; // no empty cell, it's a draw
}
/** Return true if the player with "theSeed" has won after placing at
(currentRow, currentCol) */
public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
return (board[currentRow][0] == theSeed // 3-in-the-row
&& board[currentRow][1] == theSeed
&& board[currentRow][2] == theSeed
|| board[0][currentCol] == theSeed // 3-in-the-column
&& board[1][currentCol] == theSeed
&& board[2][currentCol] == theSeed
|| currentRow == currentCol // 3-in-the-diagonal
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed
|| currentRow + currentCol == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}
/** Print the game board */
public static void printBoard() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
printCell(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 with the specified "content" */
public static void printCell(int content) {
switch (content) {
case EMPTY: System.out.print(" "); break;
case NOUGHT: System.out.print(" O "); break;
case CROSS: System.out.print(" X "); break;
}
}
}
7. By Dhaaval
Made by Dhaaval. ( Source )
public class Program
{
public static void main(String[] args) {
//Function to show the Tic Tac Toe Frame
void showframe(int posx, int posy)
{
int hr=196, vr=179; // These are ascii character which display the lines
int crossbr=197; // Another ascii character
int x=posx, y=posy;
int i,j;
gotoxy(35,4); cprintf("TIC TAC TOE");
gotoxy(35,5); for(i=0;i<11;i++) cprintf("%c",223);
for(i=0;i<2;i++)
{
for(j=1;j<=11;j++)
{
gotoxy(x,y);
printf("%c",hr);
x++;p; x++;
}
x=posx; y+=2;
}
x=posx+3; y=posy-1;
for(i=0;i<2;i++)
{
for(j=1;j<=5;j++)
{
gotoxy(x,y);
printf("%c",vr);
y++;
}
x+=4;y=posy-1;
}
x=posx+3; y=posy;
gotoxy(x,y);
printf("%c",crossbr);
x=posx+7; y=posy;
gotoxy(x,y);
printf("%c",crossbr);
x=posx+3; y=posy+2;
gotoxy(x,y);
printf("%c",crossbr);
x=posx+7; y=posy+2;
gotoxy(x,y);
printf("%c",crossbr);
}
Hide Copy Code
//Function to show the character in the specified box
void showbox(char ch, int box)
{
switch(box)
{
case 1 : gotoxy(_x+1,_y-1); printf("%c",ch); break; //1st box
case 2 : gotoxy(_x+5,_y-1); printf("%c",ch); break; //2nd box
case 3 : gotoxy(_x+9,_y-1); printf("%c",ch); break; //3rd box
case 4 : gotoxy(_x+1,_y+1); printf("%c",ch); break; //4th box
case 5 : gotoxy(_x+5,_y+1); printf("%c",ch); break; //5th box
case 6 : gotoxy(_x+9,_y+1); printf("%c",ch); break; //6th box
case 7 : gotoxy(_x+1,_y+3); printf("%c",ch); break; //7th box
case 8 : gotoxy(_x+5,_y+3); printf("%c",ch); break; //8th box
case 9 : gotoxy(_x+9,_y+3); printf("%c",ch); break; //9th box
}
}
Hide Shrink Copy Code
//Function to insert the specified character into the array
void putintobox(char arr[3][3], char ch, int box)
{
switch(box)
{
case 1 : if(arr[0][0] != 'X' && arr[0][0]!= 'O')
{ arr[0][0] = ch;
showbox(ch,1);
}
break;
case 2 : if(arr[0][1] != 'X' && arr[0][1]!= 'O')
{ arr[0][1] = ch;
showbox(ch,2);
}
break;
case 3 : if(arr[0][2] != 'X' && arr[0][2]!= 'O')
{ arr[0][2] = ch;
showbox(ch,3);
}
break;
case 4 : if(arr[1][0] != 'X' && arr[1][0]!= 'O')
{ arr[1][0] = ch;
showbox(ch,4);
}
break;
case 5 : if(arr[1][1] != 'X' && arr[1][1]!= 'O')
{ arr[1][1] = ch;
showbox(ch,5);
}
break;
case 6 : if(arr[1][2] != 'X' && arr[1][2]!= 'O')
{ arr[1][2] = ch;
showbox(ch,6);
}
break;
case 7 : if(arr[2][0] != 'X' && arr[2][0]!= 'O')
{ arr[2][0] = ch;
showbox(ch,7);
}
break;
case 8 : if(arr[2][1] != 'X' && arr[2][1]!= 'O')
{ arr[2][1] = ch;
showbox(ch,8);
}
break;
case 9 : if(arr[2][2] != 'X' && arr[2][2]!= 'O')
{ arr[2][2] = ch;
showbox(ch,9);
}
break;
}//end of switch
}
void gotobox(int box)
Hide Copy Code
//Function to show the curson on the box specified
//uses the position to check the coordinates
void gotobox(int box)
{
switch(box)
{
case 1 : gotoxy(_x+1,_y-1); break;
case 2 : gotoxy(_x+5,_y-1); break;
case 3 : gotoxy(_x+9,_y-1); break;
case 4 : gotoxy(_x+1,_y+1); break;
case 5 : gotoxy(_x+5,_y+1); break; //5th box
case 6 : gotoxy(_x+9,_y+1); break; //6th box
case 7 : gotoxy(_x+1,_y+3); break; //7th box
case 8 : gotoxy(_x+5,_y+3); break; //8th box
case 9 : gotoxy(_x+9,_y+3); break;
}
}
int navigate(char a[3][3], int box, int player, int key)
Hide Shrink Copy Code
//Function to handle the navigation
int navigate(char arr[3][3], int box, int player, int key)
{
switch(key)
{
case UPARROW : if( (box!=1) || (box!=2) || (box
}
}
8. By Asadbek
Made by Asadbek. ( Source )
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TicTacToe newGame = new TicTacToe();
newGame.work();
}
}
class TicTacToe{
private int[][] arr1 = {{1,2,3},{4,5,6},{7,8,9}};
private String[][] arr2 = {{"1","2","3"},{"4","5","6"},{"7","8","9"}};
private String x = "X";
private String o = "O";
public int count = 0;
boolean bool = false;
Scanner input = new Scanner(System.in);
public void printBoard(){
System.out.println("-------------------");
for (int j = 0; j <= 2; j++){
for(int i = 0; i <= arr2.length - 1; i++) {
System.out.print("| " + arr2[j][i] + " ");
}
System.out.println("|");
System.out.println("-------------------");
}
}
public void query(){
int change;
String xoro;
bool = turn();
if (bool) {
xoro = x;
System.out.println("X's turn");
}else {
xoro = o;
System.out.println("O's turn");
}
System.out.print("Enter the number you want to replace with: ");
change = input.nextInt();
switch(change){
case 1:
if(arr2[0][0] == x || arr2[0][0] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[0][0] = xoro;
break;
case 2:
if(arr2[0][1] == x || arr2[0][1] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[0][1] = xoro;
break;
case 3:
if(arr2[0][2] == x || arr2[0][2] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[0][2] = xoro;
break;
case 4:
if(arr2[1][0] == x || arr2[1][0] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[1][0] = xoro;
break;
case 5:
if(arr2[1][1] == x || arr2[1][1] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[1][1] = xoro;
break;
case 6:
if(arr2[1][2] == x || arr2[1][2] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[1][2] = xoro;
break;
case 7:
if(arr2[2][0] == x || arr2[2][0] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[2][0] = xoro;
break;
case 8:
if(arr2[2][1] == x || arr2[2][1] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[2][1] = xoro;
break;
case 9:
if(arr2[2][2] == x || arr2[2][2] == o){
System.out.println("Cannot change modified field!");
count++;
break;}
arr2[2][2] = xoro;
break;
}
}
private boolean turn(){
while ( true ){
count++;
if ( count % 2 == 0)
return false;
else
return true;
}
}private boolean WinOrLose(){
for(int m = 0; m < arr2.length; m++){
for(int l = 0; l < arr2.length; l++) {
if (arr2[m][0] == arr2[m][1] && arr2[m][0] == arr2[m][2]) {
return true;
} else if(arr2[0][l] == arr2[1][l] && arr2[0][l] == arr2[2][l])
return true;
else if (arr2[0][0] == arr2[1][1] && arr2[0][0] == arr2[2][2])
return true;
else if (arr2[0][2] == arr2[1][1] && arr2[0][2] == arr2[2][0])
return true;
}
}
return false;
}
public void work() {
while (true) {
boolean b;
printBoard();
query();
b = WinOrLose();
if (b && bool) {
System.out.println("\n\nX wins!");
printBoard();
break;
} else if (b && !bool) {
System.out.println("\n\nO wins!");
printBoard();
break;
}
}
}
}
9. By Sumit Sinha
Made by Sumit Sinha. ( Source )
//Use three classes Player,Board, and TicTacToe and Put the codes in their respective classes.
public class Player {
private String name;
private char Symbol;
public Player(String name, char Symbol){
setName(name);
setSymbol(Symbol);
}
public void setName(String name){
if(!name.isEmpty()){
this.name = name;
}
}
public void setSymbol(char Symbol){
if(Symbol!='\0'){
this.Symbol = Symbol;
}
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.Symbol;
}
}
public class Board {
private char board[][];
private int boardSize = 3;
private char p1Symbol, p2Symbol;
private int count;
public final static int PLAYER_1_WINS = 1;
public final static int PLAYER_2_WINS = 2;
public final static int DRAW = 3;
public final static int INCOMPLETE = 4;
public final static int INVALID = 5;
public Board(char p1Symbol, char p2Symbol){
board = new char[boardSize][boardSize];
for(int i=0;i<boardSize;i++){
for(int j=0;j<boardSize;j++){
board[i][j] = ' ';
}
}
this.p1Symbol = p1Symbol;
this.p2Symbol = p2Symbol;
}
public int move(char symbol, int x, int y) {
if(x<0 || x >= boardSize || y < 0 || y >= boardSize || board[x][y]!=' '){
return INVALID;
}
board[x][y] = symbol;
count++;
//check Row
if(board[x][0] == board[x][1] && board[x][0] == board[x][2]){
return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
}
//Check Column
if(board[0][y] == board[1][y] && board[0][y] == board[2][y]){
return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
}
//Check 1st Diagonal
if(board[0][0]!=' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]){
return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
}
//Check 2nd Diagonal
if(board[0][2]!=' ' && board[0][2] == board[1][1] && board[0][2] == board[2][0]){
return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
}
if(count==boardSize*boardSize){
return DRAW;
}
return INCOMPLETE;
}
public void print() {
System.out.println("--------------------");
for(int i=0;i<boardSize;i++) {
for (int j = 0; j < boardSize; j++) {
System.out.print("| " + board[i][j] + " |");
}
System.out.println();
}
System.out.println();
System.out.println("--------------------");
}
}
import java.util.Scanner;
public class TicTacToe {
private Player player1,player2;
private Board board;
public static void main(String[] args) {
TicTacToe t = new TicTacToe();
t.startGame();
}
public void startGame(){
Scanner s = new Scanner(System.in);
//take Input
player1 = takePlayerInput(1);
player2 = takePlayerInput(2);
while(player1.getSymbol()==player2.getSymbol()){
System.out.println("Symbol Already taken !! Please Pick Another Symbol !");
char Symbol = s.next().charAt(0);
player2.setSymbol(Symbol);
}
//Create Board
board = new Board(player1.getSymbol(),player2.getSymbol());
//Conduct the Game
int status = Board.INCOMPLETE;
boolean player1Turn = true;
while (status==Board.INCOMPLETE || status==Board.INVALID){
if(player1Turn) {
System.out.println("Player 1 - " + player1.getName() + "'s turn");
System.out.println("Enter x:");
int x = s.nextInt();
System.out.println("Enter y:");
int y = s.nextInt();
status = board.move(player1.getSymbol(),x,y);
if(status!=Board.INVALID){
player1Turn = false;
board.print();
}
else{
System.out.println("Invalid Move!! Try Again!");
}
}
else{
System.out.println("Player 2 - " + player1.getName() + "'s turn");
System.out.println("Enter x:");
int x = s.nextInt();
System.out.println("Enter y:");
int y = s.nextInt();
status = board.move(player2.getSymbol(),x,y);
if(status!=Board.INVALID){
player1Turn = true;
board.print();
}
else{
System.out.println("Invalid Move!! Try Again!");
}
}
}
if(status==Board.PLAYER_1_WINS){
System.out.println("Player 1 - " + player1.getName() + " wins !!");
}
else if(status==Board.PLAYER_2_WINS){
System.out.println("Player 2 - " + player2.getName() + " wins !!");
}
else{
System.out.println("Draw !!");
}
}
public Player takePlayerInput(int num){
Scanner s = new Scanner(System.in);
System.out.println("Enter Player " + num + "'s name");
String name = s.nextLine();
System.out.println("Enter Player" + num + "'s Symbol" ) ;
char Symbol = s.next().charAt(0);
Player p = new Player(name,Symbol);
return p;
}
}
10. By Komodo64
Made by Komodo64. Java Tic Tac Toe using oop. ( Source )
import java.util.Random;
import java.util.Scanner;
class BoardEvaluator
{
private final Board board;
private final char p1, p2;
private static final int NONE = 0;
private static final int PLAYER_1_WON = 1;
private static final int PLAYER_2_WON = 2;
private static final int DRAW = 3;
public BoardEvaluator(Board board, char p1, char p2)
{
this.board = board;
this.p1 = p1;
this.p2 = p2;
}
public int checkBoard()
{
// Check Rows
for (int r = 0; r < 3; r++) {
if (board.slot(r, 0) == p1 &&
board.slot(r, 1) == p1 &&
board.slot(r, 2) == p1)
return PLAYER_1_WON;
if (board.slot(r, 0) == p2 &&
board.slot(r, 1) == p2 &&
board.slot(r, 2) == p2)
return PLAYER_2_WON;
}
// Check Columns
for (int c = 0; c < 3; c++) {
if (board.slot(0, c) == p1 &&
board.slot(1, c) == p1 &&
board.slot(2, c) == p1)
return PLAYER_1_WON;
if (board.slot(0, c) == p2 &&
board.slot(1, c) == p2 &&
board.slot(2, c) == p2)
return PLAYER_2_WON;
}
// Check diagonals for player 1
if ((board.slot(0, 0) == p1 && board.slot(1, 1) == p1 &&
board.slot(2, 2) == p1) || (board.slot(0, 2) == p1 &&
board.slot(1, 1) == p1 && board.slot(2, 0) == p1))
return PLAYER_1_WON;
// Check diagonals for player 2
if ((board.slot(0, 0) == p2 && board.slot(1, 1) == p2 &&
board.slot(2, 2) == p2) || (board.slot(0, 2) == p2 &&
board.slot(1, 1) == p2 && board.slot(2, 0) == p2))
return PLAYER_2_WON;
// Check if board has any empty slots, if not, it's a draw.
return !board.isFull() ? NONE : DRAW;
}
// Find out if the game is over
public boolean checkWinner()
{
switch (checkBoard()) {
case PLAYER_1_WON:
System.out.println("[Game Over}: You won the game!");
return true;
case PLAYER_2_WON:
System.out.println("[Game Over]: The computer won the game!");
return true;
case DRAW:
System.out.println("[Game Over]: Draw!");
return true;
default:
return false;
}
}
}
class Screen
{
private final Board board;
public Screen(Board board)
{
this.board = board;
}
public void showBoard()
{
System.out.println("\t-------------");
for (int r = 0; r < 3; r++) {
System.out.printf("\t| %c | %c | %c |%n",
board.slot(r, 0), board.slot(r, 1),
board.slot(r, 2));
System.out.println("\t-------------");
}
}
}
class Board
{
private char[][] grid;
public Board()
{
grid = new char[3][3];
clear();
}
public void clear()
{
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
grid[r][c] = ' ';
}
public boolean place(int r, int c, char piece)
{
if (isValidSlot(r, c) && isEmptySlot(r, c)) {
grid[r][c] = piece;
return true;
}
return false;
}
public char slot(int r, int c)
{
return isValidSlot(r, c) ? grid[r][c] : ' ';
}
public boolean isEmptySlot(int r, int c)
{
return (isValidSlot(r, c) && slot(r, c) == ' ');
}
private boolean isValidSlot(int r, int c)
{
return (r >= 0 && r < 3 &&
c >= 0 && c < 3);
}
public boolean isFull()
{
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
if (grid[r][c] == ' ')
return false;
return true;
}
}
class Computer
{
private final Board board;
private final char piece = 'O';
public Computer(Board board)
{
this.board = board;
}
public void place()
{
Random rand = new Random();
int r, c;
do {
r = rand.nextInt(3);
c = rand.nextInt(3);
} while (!board.isEmptySlot(r, c));
board.place(r, c, piece);
}
public char checkPiece()
{
return piece;
}
}
class Player
{
private final Board board;
private final char piece = 'X';
private final Scanner sc;
public Player(Board board)
{
this.board = board;
sc = new Scanner(System.in);
}
public void place()
{
int r, c;
do {
System.out.print("Enter row and col: ");
r = sc.nextInt();
c = sc.nextInt();
} while (!board.place(--r, --c, piece));
}
public void leave()
{
System.out.println("Closing Scanner...");
sc.close();
}
public char checkPiece()
{
return piece;
}
}
class TicTacToe
{
Board board = new Board();
Screen screen = new Screen(board);
Computer computer = new Computer(board);
Player player = new Player(board);
BoardEvaluator boardEvaluator;
public TicTacToe()
{
boardEvaluator = new BoardEvaluator(board,
player.checkPiece(), computer.checkPiece());
screen.showBoard();
for (;;) {
player.place();
screen.showBoard();
if (boardEvaluator.checkWinner())
break;
System.out.println("Computer's Turn... ");
computer.place();
screen.showBoard();
if (boardEvaluator.checkWinner())
break;
}
player.leave();
}
public static void main(String[] argv)
{
new TicTacToe();
}
}
11. By Ravil Singh
Made by Ravil Singh. ( Source )
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class TicTacToe extends JFrame
{
JLabel bg=new JLabel(new ImageIcon(getClass().getResource("image/t2.jpg")));
JPanel [] pa=new JPanel[3];
JLabel msg=new JLabel("First palyer turn...");
JButton [] bt=new JButton[9];
JButton reset=new JButton("Reset");
public TicTacToe()
{
super("Tic Tac Toe");
setSize(600,650);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT-ON-CLOSE);
setResizable(false);
add(bg);
addPanels();
setVisible(true);
}
private void addPanels()
{
bg.setLayout(null);
for(int i=0;i<3;i++)
{
pa[i]=new JPanel();
bg.add(pa[i]);
}
pa[0].setBounds(100,30,400,40);
pa[1].setBounds(100,100,400,400);
pa[2].setBounds(100,530,400,40);
addInfo();
}
private void addInfo()
{
pa[0].add(msg);
msg.setFont(new Font("elephant",0,25));
msg.setForeground(Color.blue);
pa[2].add(reset);
pa[2].setOpaque(false);
reset.setFont(new Font("arial",0,25));
addButtons();
}
private void addButtons()
{
pa[1].setLayout(new GridLayout(3,3));
for(int i=0;i<9;i++)
{
bt[i]=new JButton();
bt[i].setBackground(Color.yellow);
pa[1].add(bt[i]);
}
}
public static void main(String[] args) {
new TicTacToe();
}
}
12. By Henri u
Made by Henri u. ( Source )
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Controller extends Application {
Model model;
View view;
public void start(Stage prime){
model = new Model();
view = new View(model);
// Setting up restart button functionality
view.restartButton.setOnAction(e->{
model.restarting();
for(int x=0;x<3;x++)
for(int y=0;y<3;y++){
view.buttonBoard[x][y].setDisable(false);
view.buttonBoard[x][y].setText("");
view.buttonBoard[x][y].setStyle("-fx-background-color: #86c1b9;");
}
view.update();
});
// Setting up button Board functionality
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
view.buttonBoard[x][y].setOnAction(e -> buttonBoardHandler(e));
}
}
Scene scene = new Scene(view, 499,399);
scene.getStylesheets().add("sheet.css");
prime.setScene(scene);
prime.setTitle("Tic-tac-toe");
prime.show();
}
public static void main(String args[]){
launch(args);
}
void buttonBoardHandler(ActionEvent e){
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
if(view.buttonBoard[x][y].equals(e.getSource())){
view.buttonBoard[x][y].setDisable(true);
model.playing(x,y,model.getTurn());
view.update();
}
}
}
}
}
/**
* Author: Henri Mwadiavita Umba
*
* Program: TicTacToe game
*
* Purpose: Create a Tic-tac-toe gui
*
* Date: May 2, 2017
*/
public class Model {
byte boardGame[][]; // Holds the game where were are playing on
int turn; // Controls how's turn it is
int score[]; // Keeps score of the wins
// All the game methods
public byte[][] getBoardGame(){return boardGame;}
public int getTurn(){return turn;}
public int[] getScore(){return score;}
// set method for testing purpose
public void setBoardGame(byte[][] b){boardGame = b;}
public void setScore(int[] s){score = s;}
// Default constructor
public Model(){
boardGame = new byte[3][3];
turn = -1;
score = new int[2];
}
// Places the X's and O's on the board
public void playing(int x, int y,int turn){
// Places a play of turn at at
boardGame[y][x] = (byte)turn;
// Switch turns
this.turn = turn * -1;
}
// Checks if their is a win
public String winning(){
if(boardGame[0][0]== boardGame[1][0]&& boardGame[0][0]== boardGame[2][0]&&boardGame[0][0]!=0)
return "VL";
else if(boardGame[0][1]== boardGame[1][1]&& boardGame[0][1]== boardGame[2][1]&&boardGame[0][1]!=0)
return "VC";
else if(boardGame[0][2]== boardGame[1][2]&& boardGame[0][2]== boardGame[2][2]&&boardGame[0][2]!=0)
return "VR";
else if(boardGame[0][0]== boardGame[0][1]&& boardGame[0][0]== boardGame[0][2]&&boardGame[0][0]!=0)
return "HT";
else if(boardGame[1][0]== boardGame[1][1]&& boardGame[1][0]== boardGame[1][2]&&boardGame[1][0]!=0)
return "HC";
else if(boardGame[2][0]== boardGame[2][1]&& boardGame[2][0]== boardGame[2][2]&&boardGame[2][0]!=0)
return "HB";
else if(boardGame[0][2]== boardGame[1][1]&& boardGame[0][2]== boardGame[2][0]&&boardGame[0][2]!=0)
return "DR";
else if(boardGame[0][0]== boardGame[1][1]&& boardGame[0][0]== boardGame[2][2]&&boardGame[0][0]!=0)
return "DF";
return null;
}
// Starts a new game and keeps the scores
public void restarting(){
byte b[][] = {{0,0,0},{0,0,0},{0,0,0}};
setBoardGame(b);
}
}
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
public class View extends GridPane {
Button [][] buttonBoard;
Button restartButton;
TextField xTextField;
TextField oTextField;
Label label;
GridPane buttonsGridPane;
Model model;
View(Model model){
// Initiating All attributes
this.model = model;
buttonBoard = new Button[3][3];
restartButton = new Button();
xTextField = new TextField();
oTextField = new TextField();
buttonsGridPane = new GridPane();
// Create the gameBoard (buttonBoard)
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
buttonBoard[x][y]= new Button();
buttonBoard[x][y].setPrefSize(Integer.MAX_VALUE, Integer.MAX_VALUE);
buttonBoard[x][y].setStyle("-fx-background-color: #86c1b9;");
buttonsGridPane.add(buttonBoard[x][y],x,y);
}
}
buttonsGridPane.setVgap(10);
buttonsGridPane.setHgap(10);
this.add(buttonsGridPane,0,0,5,1);
// Creating restart button
restartButton.setText("Restart");
restartButton.setPrefSize(Integer.MAX_VALUE, Integer.MAX_VALUE);
restartButton.getStyleClass().add("button-fire");
System.out.println(restartButton.getStyle());
this.add(restartButton,0,1);
label = new Label("X's:");
label.setMinSize(25,25);
this.add(label,1,1);
label = new Label("O's:");
label.setMinSize(25,25);
this.add(label,3,1);
xTextField.setPrefSize(Integer.MAX_VALUE, 25);
xTextField.setEditable(false);
xTextField.setText("0");
this.add(xTextField,2,1);
oTextField.setPrefSize(Integer.MAX_VALUE, 25);
oTextField.setEditable(false);
oTextField.setText("0");
this.add(oTextField,4,1);
this.setHgap(10);
this.setVgap(10);
this.setPadding(new Insets(10));
update();
}
void update(){
// setting what goes on the buttonBoards buttons
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
if(model.getBoardGame()[y][x]==1){
buttonBoard[x][y].setText("X");
}else if(model.getBoardGame()[y][x]==-1){
buttonBoard[x][y].setText("O");
}
}
}
String win = model.winning();
if(win != null){
for(int x=0;x<3;x++)
for(int y=0;y<3;y++){
buttonBoard[x][y].setDisable(true);
}
if(model.getTurn()==-1)
model.getScore()[0]++;
else
model.getScore()[1]++;
if(win.equals("HT")){
buttonBoard[0][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][0].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("HC")){
buttonBoard[0][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][1].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("HB")){
buttonBoard[0][2].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][2].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][2].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("VL")){
buttonBoard[0][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[0][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[0][2].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("VC")){
buttonBoard[1][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][2].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("VR")){
buttonBoard[2][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][2].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("DF")){
buttonBoard[0][0].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][2].setStyle("-fx-background-color: #ba8baf");
}else if(win.equals("DR")){
buttonBoard[0][2].setStyle("-fx-background-color: #ba8baf");
buttonBoard[1][1].setStyle("-fx-background-color: #ba8baf");
buttonBoard[2][0].setStyle("-fx-background-color: #ba8baf");
}
}
// Setting up Scores
xTextField.setText(model.getScore()[0]+"");
oTextField.setText(model.getScore()[1]+"");
}
}
13. By Ravil Singh
Made by Ravil Singh. ( Source )
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
JLabel bg = new JLabel(new ImageIcon(getClass().getResource("images/t2.jpg")));
ImageIcon icon1 = new ImageIcon(getClass().getResource("images/user1.png"));
ImageIcon icon2 = new ImageIcon(getClass().getResource("images/user2.png"));
JPanel[] pa = new JPanel[3];
JLabel msg = new JLabel("First Player Click To Start");
JButton Reset = new JButton("Reset");
JButton[] bt = new JButton[9];
int user = 1;
int count = 0;
boolean winnerFound = false;
AudioClip clip1 = Applet.newAudioClip(getClass().getResource("Sounds/1.wav"));
AudioClip clip2 = Applet.newAudioClip(getClass().getResource("Sounds/2.wav"));
AudioClip clip3 = Applet.newAudioClip(getClass().getResource("Sounds/3.wav"));
ImageIcon Icon;
public TicTacToe() {
super("Tic Tac Toe");
setSize(600, 650);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setResizable(false);
add(bg);
addPanels();
clip1.loop();
setVisible(true);
findWinner(Icon);
}
private void findWinner(ImageIcon icon) {
if (bt[0].getIcon() == icon && bt[1].getIcon() == icon && bt[2].getIcon() == icon)
announceWinner(0, 1, 2, icon);
else if (bt[3].getIcon() == icon && bt[4].getIcon() == icon && bt[5].getIcon() == icon)
announceWinner(3, 4, 5, icon);
else if (bt[6].getIcon() == icon && bt[7].getIcon() == icon && bt[8].getIcon() == icon)
announceWinner(6, 7, 8, icon);
else if (bt[0].getIcon() == icon && bt[3].getIcon() == icon && bt[6].getIcon() == icon)
announceWinner(0, 3, 6, icon);
else if (bt[1].getIcon() == icon && bt[4].getIcon() == icon && bt[7].getIcon() == icon)
announceWinner(1, 4, 7, icon);
else if (bt[2].getIcon() == icon && bt[5].getIcon() == icon && bt[8].getIcon() == icon)
announceWinner(2, 5, 8, icon);
else if (bt[0].getIcon() == icon && bt[4].getIcon() == icon && bt[8].getIcon() == icon)
announceWinner(0, 4, 8, icon);
else if (bt[2].getIcon() == icon && bt[4].getIcon() == icon && bt[6].getIcon() == icon)
announceWinner(2, 4, 6, icon);
}
private void announceWinner(int i, int j, int k, ImageIcon Ic) {
bt[i].setBackground(Color.red);
bt[j].setBackground(Color.red);
bt[k].setBackground(Color.red);
if (Ic == icon1)
msg.setText("First Player Win's");
else
msg.setText("Second Player Win's");
winnerFound = true;
}
private void addPanels() {
for (int i = 0; i < 3; i++) {
pa[i] = new JPanel();
bg.add(pa[i]);
}
pa[0].setBounds(100, 30, 400, 40);
pa[1].setBounds(100, 100, 400, 400);
pa[2].setBounds(100, 530, 400, 40);
addInfo();
Reset.addActionListener(new ResetListener());
}
private void addInfo() {
pa[0].add(msg);
msg.setFont(new Font("elephant", Font.PLAIN, 25));
msg.setForeground(Color.RED);
pa[2].add(Reset);
pa[2].setOpaque(false);
addButtons();
}
private void addButtons() {
pa[1].setLayout(new GridLayout(3, 3));
TicListener listener = new TicListener();
for (int i = 0; i < 9; i++) {
bt[i] = new JButton();
bt[i].setBackground(Color.yellow);
bt[i].addActionListener(listener);
pa[1].add(bt[i]);
}
}
class TicListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
JButton bb = (JButton) evt.getSource();
Icon icon = bb.getIcon();
if (icon != null || winnerFound) {
clip3.play();
return;
}
if (user == 1) {
bb.setIcon(icon1);
msg.setText("Second Players Turn");
user = 2;
findWinner(icon1);
} else {
bb.setIcon(icon2);
msg.setText("First Players Turn");
user = 1;
findWinner(icon2);
}
clip2.play();
count++;
if (count == 9 && !winnerFound) {
msg.setText("It's a Draw");
msg.setForeground(Color.red);
}
}
}
class ResetListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
user = 1;
msg.setText("First Player Turn");
for (JButton tt : bt) {
tt.setIcon(null);
tt.setBackground(Color.yellow);
}
winnerFound = false;
count = 0;
msg.setForeground(Color.blue);
}
}
public static void main(String[] args) {
new TicTacToe();
}
}