TicTacToe Java
TicTacToe Java
tellapart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// Strategy pattern.
// The computer player's behavior/strategy can be replaced by inheriting from the
interface below
// Also, the human player's behavior inherits from the same interface
// This also makes it easy to modify the game for 2 human players, 2 computer
players etc.
interface MoveMethod {
public int move();
}
public SimpleMoveStrategy(TicTacToe t) {
game = t;
}
public HumanMove(TicTacToe t) {
game = t;
}
String move_str;
int move_int = 0;
boolean valid_input = false;
while (!valid_input) {
System.out.print("Where to ? ");
move_str = TicTacToe.getUserInput();
if (Character.isDigit(move_str.toCharArray()[0])) {
move_int = Integer.parseInt(move_str);
if ((move_int <= (TicTacToe.N) * (TicTacToe.N))
&& move_int >= 1) {
valid_input = true;
break;
}
}
if (!valid_input) {
System.out.println("Invalid input");
continue;
}
}
return move_int;
}
class TicTacToe {
protected static final int N = 3;
private static final int HSPACE = 20;
protected int[][] board;
private static BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
class Player {
private String name;
private int player_type;
private int player_order;
private MoveMethod move_strategy;
if ((pos - 1) / 3 == 0) {
str += "upper ";
} else if ((pos - 1) / 3 == 1) {
str += "middle ";
} else
str += "lower ";
if ((pos - 1) % 3 == 0)
str += "left";
else if ((pos - 1) % 3 == 1)
str += "middle";
else
str += "right";
return str;
}
public TicTacToe() {
board = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}
if (board[x_coord][y_coord] == 0) {
board[x_coord][y_coord] = p_type;
return true;
} else {
System.out.println("Invalid move");
return false;
}
}
// draw
w = WinConfig.DRAW;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
if (board[i][j] == 0)
w = WinConfig.NONE;
}
return w;
if (i != N - 1) {
s += " | ";
}
}
s += String.format("%" + HSPACE + "s", "");
if (i == N - 1) {
s += "\n";
} else {
s += " | ";
}
}
return s;
}
System.out
.println("Please make your move selection by entering a
number 1-9 corresponding to the movement key on the right.\n");
System.out.println(game.toString());
move2 = game.getplayer2().getMove();
System.out.println("");
System.out.println("You have put an X in the "
+ TicTacToe.getPosDescription(move1)
+ ". I will put a O in the "
+ TicTacToe.getPosDescription(move2) + ".");
game.setMove(move2, game.getplayer2().getPlayerType());
if (game.isWinningConfig() == WinConfig.WIN) {
System.out.println("");
System.out.println(game.toString());
System.out.println("I won. Thanks for playing.");
break;
}
System.out.println(game.toString());
}
}
}