-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.java
77 lines (70 loc) · 2.18 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
import java.util.Scanner;
public class TicTacToe {
private Player player1, player2;
private Board board;
public static void main(String args[]) {
TicTacToe t = new TicTacToe();
t.startGame();
}
public void startGame() {
Scanner s = new Scanner(System.in);
// Players input
player1 = takePlayerInput(1);
player2 = takePlayerInput(2);
while (player1.getSymbol() == player2.getSymbol()) {
System.out.println("Symbol Already taken !! Pick another symbol !!");
char symbol = s.next().charAt(0);
player2.setSymbol(symbol);
}
// Create Board
board = new Board(player1.getSymbol(), player2.getSymbol());
// Conduct the Game
boolean player1Turn = true;
int status = Board.INCOMPLETE;
while (status == Board.INCOMPLETE || status == Board.INVALID) {
if (player1Turn) {
System.out.println("Player 1 - " + player1.getName() + "'s turn");
System.out.println("Enter x: ");
int x = s.nextInt();
System.out.println("Enter y: ");
int y = s.nextInt();
status = board.move(player1.getSymbol(), x, y);
if (status != Board.INVALID) {
player1Turn = false;
board.print();
} else {
System.out.println("Invalid Move !! Try Again !!");
}
} else {
System.out.println("Player 2 - " + player2.getName() + "'s turn");
System.out.println("Enter x: ");
int x = s.nextInt();
System.out.println("Enter y: ");
int y = s.nextInt();
status = board.move(player2.getSymbol(), x, y);
if (status != Board.INVALID) {
player1Turn = true;
board.print();
} else {
System.out.println("Invalid Move !! Try Again !!");
}
}
}
if (status == Board.PLAYER_1_WINS) {
System.out.println("Player 1 - " + player1.getName() + " wins !!");
} else if (status == Board.PLAYER_2_WINS) {
System.out.println("Player 2 - " + player2.getName() + " wins !!");
} else {
System.out.println("Draw !!");
}
}
private Player takePlayerInput(int num) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Player " + num + " name: ");
String name = s.nextLine();
System.out.println("Enter Player " + num + " symbol: ");
char symbol = s.next().charAt(0);
Player p = new Player(name, symbol);
return p;
}
}