-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTicTacToe.java
83 lines (78 loc) · 2.44 KB
/
TicTacToe.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
import java.util.Scanner;
public class TICTACTOE {
public static void main(String[] args) {
char[][] board=new char[3][3];
Scanner ob=new Scanner(System.in);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j]=' ';
}
}
boolean gameOver=false;
char player='X';
while(!gameOver){
BoardFull(board);
// printBoard(board);
int r=ob.nextInt();
int c=ob.nextInt();
if(board[r][c]==' '){
board[r][c]=player;
gameOver=HasWon(board,player);
if(gameOver){
System.out.println("Congratualtions!! "+player+"\nYou have won the game");
break;
}
else{
if(player=='X'){
player='O';
System.out.println("It's"+player+"chance");
}
else{
player='X';
System.out.println("It's"+player+"chance");
}
}
}else{
System.out.println("Please enter the proper eye");
}
}
printBoard(board);
ob.close();
}
public static void printBoard(char[][] board){
for(int i=0;i<board.length;i++){
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j]+"|");
}
System.out.println();
}
}
public static boolean HasWon(char[][] board,char player){
for(int i=0;i<board.length;i++)
if(board[i][0]==player &&board[i][1]==player && board[i][2]==player )
return true;
for(int i=0;i<board[0].length;i++)
if(board[0][i]==player &&board[1][i]==player && board[2][i]==player )
return true;
// for(int i=0;i<board.length;i++)
if(board[0][0]==player &&board[1][1]==player && board[2][2]==player )
return true;
if(board[2][0]==player &&board[1][1]==player && board[0][2]==player )
return true;
return false;
}
public static void BoardFull(char[][] board){
int count=0;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]!=' '){
count++;
}
}
}
if(count==9){
System.out.println("The match is draw");
System.exit(0);
}
}
}