Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Tictactoe
- {
- public static char [][] theBoard = new char[3][3];
- public static int c,r;
- public static Scanner scan = new Scanner(System.in);
- public static char turn = 'X';
- public static void main(String agr[])
- {
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- theBoard[i][j] = '*';
- }
- }
- System.out.println(" TIC TAC TOE!");
- System.out.print("-------------");
- play();
- }
- public static void play()
- {
- boolean playing = true;
- printBoard();
- while(playing)
- {
- System.out.println("Enter a row (1|2|3)");
- r = scan.nextInt() - 1;
- System.out.println("Enter a column (1|2|3)");
- c = scan.nextInt() - 1;
- theBoard[r][c] = turn;
- if(gameOver(r,c))
- {
- playing = false;
- System.out.println("Game Over!");
- System.out.print("Player " + turn + " wins!");
- }
- printBoard();
- if(turn == 'X')
- {
- turn = 'O';
- }
- else
- {
- turn = 'X';
- }
- }
- }
- public static void printBoard() {
- for (int i = 0; i < 3; i++) {
- System.out.println();
- for (int j = 0; j < 3; j++){
- if (j == 0)
- System.out.print("| ");
- System.out.print(theBoard[i][j] + " | ");
- }
- }
- System.out.println();
- }
- public static boolean gameOver(int r,int c)
- {
- //Check for | or - victory
- if(theBoard[0][c] == theBoard[1][c] && theBoard[0][c] == theBoard[2][c])
- {
- return true;
- }
- if(theBoard[r][0] == theBoard[r][1] && theBoard[r][0] == theBoard[r][2])
- {
- return true;
- }
- //check for \ or / victory
- if(theBoard[0][0] == theBoard[1][1] && theBoard[0][0] == theBoard[2][2] && theBoard[1][1] != '*')
- {
- return true;
- }
- if(theBoard[0][2] == theBoard[1][1] && theBoard[0][2] == theBoard[2][0] && theBoard[1][1] != '*')
- {
- return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement