Monday 29 December 2014

Tic Tac Game in java

Structure of the Problem Requirements 

In this project we will implement the code of Tic Tac Toe game in Java. Before this we implement the same project in C++. The Game is very interesting and the player who successfully complete the straight line will be winner.Your Partner will be second player and you play with that. Here is the complete source code of this project which help you in better understanding. 

Source Code   

TicTacToe.Java

package LEP.uzair.tictactoegame.bord;
public class TicTacToe {

   private char[][] board;
   private char currentPlayerMark;
     public TicTacToe() {
       board = new char[3][3];
       currentPlayerMark = 'x';
       initializeBoard();
   }
       // Set/Reset the board back to all empty values.
   public void initializeBoard() {
     
       // Loop through rows
       for (int i = 0; i < 3; i++) {
         
           // Loop through columns
           for (int j = 0; j < 3; j++) {
               board[i][j] = '-';
           }
       }
   }
      // Print the current board (may be replaced by GUI implementation later)
   public void printBoard() {
   
       System.out.println("      -------------");
       
       for (int i = 0; i < 3; i++) {
           System.out.print( " > "+Integer.toString(i+1)+"->| ");
           for (int j = 0; j < 3; j++) {
               System.out.print(board[i][j] + " | ");
           }
           System.out.println();
           System.out.println("      -------------");
         
       }
       System.out.println("        1^  2^  3^");
       System.out.println("       -----------");
   }
     // Loop through all cells of the board and if one is found to be empty (contains char '-') then return false.
   // Otherwise the board is full.
   public boolean isBoardFull() {
       boolean isFull = true;
     
       for (int i = 0; i < 3; i++) {
           for (int j = 0; j < 3; j++) {
               if (board[i][j] == '-') {
                   isFull = false;
               }
           }
       }
     
       return isFull;
   }
      // Returns true if there is a win, false otherwise.
   // This calls our other win check functions to check the entire board.
   public boolean checkForWin() {
       return (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin());
   }
      // Loop through rows and see if any are winners.
   private boolean checkRowsForWin() {
       for (int i = 0; i < 3; i++) {
           if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) {
               return true;
           }
       }
       return false;
   }
      // Loop through columns and see if any are winners.
   private boolean checkColumnsForWin() {
      for (int i = 0; i < 3; i++) {
           if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) {
               return true;
           }
       }
       return false;
   }
    // Check the two diagonals to see if either is a win. Return true if either wins.
   private boolean checkDiagonalsForWin() {
       return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true));
   }
     // Check to see if all three values are the same (and not empty) indicating a win.
    private boolean checkRowCol(char c1, char c2, char c3) {
        return ((c1 != '-') && (c1 == c2) && (c2 == c3));
    }
    // Change player marks back and forth.
   public void changePlayer() {
       if (currentPlayerMark == 'x') {
           currentPlayerMark = 'o';
       }
       else {
           currentPlayerMark = 'x';
       }
   }
  // Places a mark at the cell specified by row and col with the mark of the current player.
    public boolean placeMark(int row, int col) {
     
       // Make sure that row and column are in bounds of the board.
       if ((row >= 0) && (row < 3)) {
           if ((col >= 0) && (col < 3)) {
               if (board[row][col] == '-') {
                   board[row][col] = currentPlayerMark;
                   return true;
               }
           }
       }
     
       return false;
   }
}  

Start.Java


package LEP.uzair.tictactoegame.main;
import java.util.Scanner;

import LEP.uzair.tictactoegame.bord.TicTacToe;


public class Start {
int count=0;
public void StartGame(){
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
char mainYesOrNo = 'Y';
while (mainYesOrNo =='Y'){
System.out.print("\t\t     ====================\n");
System.out.print("\t\t     Welcome To TicTacToe  \n");
System.out.print("\t\t             Game        \n");
if(count<1){
count=count+1;
}else{
System.out.print("\t\t             Again        \n");
}
System.out.print("\t\t     ====================\n");
System.out.print("\tQ:What do you want to do?\n\n");
if(count<2){
System.out.print("\t\t1 : Play\n\n");
count=count+1;
}else{
System.out.print("\t\t1 : Play Again\n\n");
}
System.out.print("\t\t2 : Exit\n\n");
System.out.println("\t\t\tYou Select : ");
int switchChoice = input.nextInt();
switch (switchChoice) 
{
case 1: {
play();
break;
}
case 2: { 
return;
}
default: {
System.out.println("Invalid Selection");
error();
break;
}
}
System.out.println("\n\tDo u want to run your Program Again \n\t\t\tY = yes\n\t\t\tN = No\n");
System.out.println("You Select : ");
mainYesOrNo =(input.next()).charAt(0);
if(Character.isLowerCase(mainYesOrNo )){
mainYesOrNo =Character.toUpperCase(mainYesOrNo );
}//End If
}//End While
}
private void play() {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
TicTacToe game = new TicTacToe();
game.placeMark(0,2);
game.printBoard();
for(int i =0; i<10;i++)
{
if (game.checkForWin()) {
  System.out.println("We have a winner! Congrats!");
  return;
}
else if (game.isBoardFull()) {
  System.out.println("Appears we have a draw!");
  return;
}
game.changePlayer();
int row, col;
System.out.println("Select Row in Number 1-3: ");
row=input.nextInt();
row=row-1;
System.out.println("Select Column in Number 1-3: ");
col=input.nextInt();
col=col-1;
if(game.placeMark(row, col)){
game.printBoard();
}else{
game.changePlayer();
error();
}
}
}
public static void error() {
System.out.print("\t\t     **************************\n");
System.out.print("\t\t     |--------> ERROR <--------| \n");
System.out.print("\t\t     **************************\n");
System.out.print("\t\t     You Select some thin wrong\n");
System.out.print("\t\t                OR\n");
System.out.print("\t\t  There may be some othere Problem\n");
System.out.print("\t\t It is better for you to try again...!\n");
System.out.print("\t\t     **************************\n");
}
}//End of Class Start

main.Java

package LEP.uzair.tictactoegame.main;
public class TicTacMain {
public static void main(String[] args) {
Start objectStart = new Start();
objectStart.StartGame();
}
}

Output of the Program

Tic Tac Toe Game in Java
Tic Tac Toe Game in Java
Tic Tac Toe Game in Java
Tic Tac Toe Game in Java

Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment