Skip to content

Commit f3ecbe5

Browse files
Tictactoe is added
1 parent abc9dee commit f3ecbe5

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.util.Scanner;
2+
3+
public class Tictactoe {
4+
public static void main(String[] args) {
5+
// System.out.println("hello");
6+
Scanner sc = new Scanner(System.in);
7+
int n = 3;
8+
String arr[][] = new String[n][n];
9+
for (int i = 0; i < n; i++) {
10+
for (int j = 0; j < n; j++) {
11+
arr[i][j] = " ";
12+
}
13+
}
14+
15+
boolean gameOver = false;
16+
String player = "x";
17+
while (!gameOver) {
18+
printBoard(arr, n);
19+
System.out.print("Enter your index " + player + ": ");
20+
String ind = sc.nextLine();
21+
arr[Integer.parseInt(ind.charAt(0) + "")][Integer.parseInt(ind.charAt(1) + "")] = player;
22+
if (haveWon(arr, n, player)) {
23+
gameOver = true;
24+
System.out.println("Player " + player + " has won!");
25+
}
26+
player = player.equals("x") ? "o" : "x";
27+
}
28+
printBoard(arr, n);
29+
sc.close();
30+
}
31+
32+
static void printBoard(String arr[][], int n) {
33+
for (int i = 0; i < n; i++) {
34+
for (int j = 0; j < n; j++) {
35+
System.out.print(" | " + arr[i][j] + " | ");
36+
}
37+
System.out.println();
38+
}
39+
}
40+
41+
static boolean haveWon(String arr[][], int n, String player) {
42+
for (int i = 0; i < n; i++) { // row
43+
if (arr[i][0] == player && arr[i][1] == player && arr[i][2] == player) {
44+
return true;
45+
}
46+
47+
}
48+
49+
for (int i = 0; i < n; i++) { // col
50+
if (arr[0][i] == player && arr[1][i] == player && arr[2][i] == player) {
51+
return true;
52+
}
53+
}
54+
55+
if (arr[0][2] == player && arr[1][1] == player && arr[2][0] == player) {
56+
return true;
57+
}
58+
59+
if (arr[0][0] == player && arr[1][1] == player && arr[2][2] == player) {
60+
return true;
61+
}
62+
63+
return false;
64+
}
65+
}

0 commit comments

Comments
 (0)