Skip to content

Commit b871c68

Browse files
Tic-Tac-Toe.java
1 parent f346e22 commit b871c68

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Tic-Tac-Toe.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.*;
2+
3+
public class TicTacToe {
4+
static char[] board = {' ','1','2','3','4','5','6','7','8','9'};
5+
6+
static void show() {
7+
System.out.println(board[1]+"|"+board[2]+"|"+board[3]);
8+
System.out.println("-+-+-");
9+
System.out.println(board[4]+"|"+board[5]+"|"+board[6]);
10+
System.out.println("-+-+-");
11+
System.out.println(board[7]+"|"+board[8]+"|"+board[9]);
12+
}
13+
14+
static boolean win() {
15+
int[][] w = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}};
16+
for (int[] a : w)
17+
if (board[a[0]] == board[a[1]] && board[a[1]] == board[a[2]])
18+
return true;
19+
return false;
20+
}
21+
22+
public static void main(String[] args) {
23+
Scanner sc = new Scanner(System.in);
24+
char turn = 'X';
25+
int moves = 0;
26+
27+
while (true) {
28+
show();
29+
System.out.print("Player " + turn + " choose (1-9): ");
30+
int pos = sc.nextInt();
31+
32+
if (board[pos] == 'X' || board[pos] == 'O') continue;
33+
34+
board[pos] = turn;
35+
moves++;
36+
37+
if (win()) { show(); System.out.println(turn + " wins!"); break; }
38+
if (moves == 9) { show(); System.out.println("Draw!"); break; }
39+
40+
turn = (turn == 'X') ? 'O' : 'X';
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)