-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.java
More file actions
78 lines (65 loc) · 2.15 KB
/
board.java
File metadata and controls
78 lines (65 loc) · 2.15 KB
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
import java.util.*;
class board{
public static void main(String[] args) {
char[][] board = new char[3][3];
for(int row=0;row<board.length;row++){
for(int col=0;col<board[row].length;col++){
board[row][col]=' ';
}
}
Scanner sc = new Scanner(System.in);
char player = 'X';
boolean gameover = false;
while(!gameover){
printBoard(board);
System.out.println("Player " + player +" enter");
int row = sc.nextInt();
sc.nextLine();
int col = sc.nextInt();
sc.nextLine();
if(board[row][col]== ' '){
board[row][col]=player;
gameover= Won(board,player);
if(gameover){
System.out.println("Player " + player +" is the winner");
}else{
if(player=='X'){
player='O';
}else{
player='X';
}
}
}else {
System.out.println("Invalid move");
}
}
printBoard(board);
}
public static void printBoard(char[][] board){
for(int row=0;row<board.length;row++){
for(int col=0;col<board[row].length;col++){
System.out.print(board[row][col] + "|");
}
System.out.println();
}
}
public static boolean Won(char[][] board,char player){
for(int row=0;row<board.length;row++){
if(board[row][0]==player && board[row][1]== player && board[row][2]==player){
return true;
}
}
for(int col=0;col<board.length;col++){
if(board[0][col]==player && board[1][col]== player && board[2][col]==player){
return true;
}
}
if(board[0][0]==player && board[1][1]==player && board[2][2]==player){
return true;
}
if(board[0][2]==player && board[1][1]== player && board[2][0]==player){
return true;
}
return false;
}
}