-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTicTacToe_Game.java
102 lines (91 loc) · 2.61 KB
/
TicTacToe_Game.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.mihir.Greedy;
import java.util.*;
public class TicTacToe_Game {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
boolean gameOver=false;
String player="0";
String[][]board=new String[3][3];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
board[i][j]=" ";
}
}
while(!gameOver){
int a=sc.nextInt();
int b=sc.nextInt();
if(board[a][b]!=" "){
System.out.println("enter valid input");
continue;
}
board[a][b]=player;
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();
}
if(player.equals("0")){
gameOver= hasWin(player,board,a,b);
if(gameOver){
System.out.println("player 0 is win");
}
player="X";
}
else if(player.equals("X")){
gameOver= hasWin(player,board,a,b);
if(gameOver){
System.out.println("player X is win");
}
player="0";
}
}
}
public static boolean hasWin(String s,String[][]board,int a,int b){
boolean ans=true;
for(int i=0;i<board.length;i++){
if(board[a][i]!=s){
ans=false;
}
}
if(ans){
return true;
}
ans=true;
for(int i=0;i<board.length;i++){
if(board[i][b]!=s){
ans= false;
}
}
if(ans){
return true;
}
ans=true;
int i=0;
int j=0;
while(i<board.length&&j<board[0].length){
if(board[i][j]!=s){
ans= false;
}
i++;
j++;
}
if(ans){
return true;
}
ans=true;
i=0;
j=board[0].length-1;
while(j>=0&&i<board.length){
if( board[i][j]!=s){
ans= false;
}
i++;
j--;
}
if(!ans){
return false;
}
return true;
}
}