Skip to content

Commit 92af0e6

Browse files
authored
Add files via upload
1 parent 1707b5c commit 92af0e6

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

TicTacToe/TicTacToe.java

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import java.util.Scanner;
2+
3+
public class TicTacToe{
4+
public static void main(String[] args){
5+
char[][] board = new char[3][3];
6+
initialize(board);
7+
startGame(board, 'X');
8+
}
9+
10+
public static void initialize(char[][] board){
11+
for(int row=0;row<board.length;row++){
12+
for(int col=0;col<board[0].length;col++){
13+
board[row][col] = ' ';
14+
}
15+
}
16+
}
17+
18+
public static void printBoard(char[][] board){
19+
for(int row=0;row<board.length;row++){
20+
System.out.println("-----------");
21+
for(int col=0;col<board[0].length;col++){
22+
System.out.print(board[row][col] + " | ");
23+
}
24+
System.out.println();
25+
}
26+
System.out.println("-----------");
27+
}
28+
29+
public static void startGame(char[][] board, char player){
30+
int c = 0;
31+
boolean gameOver = false;
32+
Scanner input = new Scanner(System.in);
33+
34+
while(!gameOver){
35+
36+
if(c == board.length * board.length){
37+
System.err.println("Match Draw");
38+
break;
39+
}
40+
printBoard(board);
41+
42+
System.out.print("Player " + player + " Enter position: ");
43+
int row = input.nextInt();
44+
int col = input.nextInt();
45+
System.out.println();
46+
47+
if(board[row][col] == ' '){
48+
board[row][col] = player;
49+
c++;
50+
gameOver = haveWon(board, player);
51+
52+
if(gameOver){
53+
System.out.println("Player " + player + " has won!");
54+
}
55+
else{
56+
player = (player == 'X') ? 'O' : 'X';
57+
}
58+
}
59+
else{
60+
System.err.println("Invalid Position. Try Again!");
61+
}
62+
}
63+
printBoard(board);
64+
65+
}
66+
67+
public static boolean haveWon(char[][] board, char player){
68+
// row
69+
for(int row=0;row<board.length;row++){
70+
if(board[row][0] == player && board[row][1] == player && board[row][2] == player){
71+
return true;
72+
}
73+
}
74+
75+
// column
76+
for(int col=0;col<board[0].length;col++){
77+
if(board[0][col] == player && board[1][col] == player && board[2][col] == player){
78+
return true;
79+
}
80+
}
81+
82+
// diagonal
83+
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
84+
return true;
85+
}
86+
87+
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
88+
return true;
89+
}
90+
91+
return false;
92+
}
93+
94+
}

0 commit comments

Comments
 (0)