Commit fa272f56 authored by Son Pham's avatar Son Pham

All the files 2

parent c7a321ec
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>homework-2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7
This is a drill. Bobby take this file.
/**
* CSCI205 - Software Design and Engineering
* Name: Robert Cowen & Son Pham
*
* Work: homework-2
* Created: Nov 11, 2014, 10:23:41 PM
*/
import java.awt.EventQueue;
import view.TTTMainView;
import controller.TTTController;
/**
* @author skp011
*
*/
public class TTTMainGame {
/**
* Run the main view and use the controller to control the view
*
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TTTMainView frame = new TTTMainView();
TTTController ctrl = new TTTController(frame);
frame.setVisible(true);
}
});
}
}
/**
* CSCI205 - Software Design and Engineering
* Name: Robert Cowen & Son Pham
*
* Work: homework-2
* Created: Nov 11, 2014, 10:23:41 PM
*/
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import model.Board;
import model.Board.State;
import model.BoardUtility;
import model.Game;
import model.Mark;
import model.enumeration.ComputerType;
import model.enumeration.GameType;
import model.player.AIPlayer;
import model.player.AutoPlayable;
import view.TTTBoardPanel;
import view.TTTMainView;
/**
* @author skp011
*
*/
public class TTTController implements ActionListener {
/** The size of the board is set to 3x3 */
public final static int SIZE = 3;
/** Instantiate a game */
private Game theGame;
/** Instantiate the view */
private TTTMainView theView;
/**
* Update the board
*/
public void updateBoard() {
TTTBoardPanel panel = theView.getBoardPanel();
Board board = theGame.getTheBoard();
for (int row = 0; row < SIZE; row++)
for (int col = 0; col < SIZE; col++) {
if (board.getMark(row, col) == Mark.NONE) {
panel.getButton(row, col).setText("");
} else if (board.getMark(row, col) == Mark.X) {
panel.getButton(row, col).setText("X");
} else {
panel.getButton(row, col).setText("O");
}
}
}
/**
* Construc the controller by passing theView and set up actionListener for
* the buttons
*
* @param theView
*/
public TTTController(TTTMainView theView) {
/** Set the view equals the passed TTTMainView parameter */
this.theView = theView;
/** Set the game equals the passed Game parameter */
this.theGame = new Game();
/** Add action listener to all the button */
for (int row = 0; row < SIZE; row++)
for (int col = 0; col < SIZE; col++)
this.theView.getButton(row, col).addActionListener(this);
/** Add action listener to New Game and Train AI */
theView.getControlPanel().getBtnNewGame().addActionListener(this);
theView.getControlPanel().getBtnTrainAI().addActionListener(this);
}
/**
* Handles the controller if the game is draw
*
* @return true if the user wants to keep playing, false otherwise;
*/
private int handleDraw() {
/** Increase the number of label draw */
int draws = Integer.parseInt(theView.getDrawLabel().getText());
draws++;
theView.getDrawLabel().setText(String.valueOf(draws));
/** Ask the user if they want to play again */
return JOptionPane.showConfirmDialog(null,
"It'a tie!\nDo you want to play again?", "It's a tie!",
JOptionPane.YES_NO_OPTION);
}
/**
* Handles the controller if the game is draw
*
* @return true if the user wants to keep playing, false otherwise;
*/
private int handleWin() {
if (theGame.getCurrentPlayer().getMyMark() == Mark.X) {
/** Change the text of XWins */
int xWin = Integer.parseInt(theView.getxWinLabel().getText());
xWin++;
theView.getxWinLabel().setText(String.valueOf(xWin));
} else if (theGame.getCurrentPlayer().getMyMark() == Mark.O) {
/** Change the text of OWins */
int oWin = Integer.parseInt(theView.getoWinLabel().getText());
oWin++;
theView.getoWinLabel().setText(String.valueOf(oWin));
}
/** Ask the users if they want to play again? */
return JOptionPane.showConfirmDialog(null,
"Player " + theGame.getCurrentPlayer()
+ " won!\nDo you want to play again?", "Player "
+ theGame.getCurrentPlayer() + " won!",
JOptionPane.YES_NO_OPTION);
}
/**
* Handles the controller if the turn is switch
*/
@SuppressWarnings("unused")
private void handleSwitchTurn() {
/** Switch the player in the model */
theGame.switchPlayer();
/** Change the label for NEXT player */
theView.getNextLabel().setText(
theGame.getCurrentPlayer().getMyMark().toString());
}
private void updateViewFromModel() {
// Update the board with new marks
this.updateBoard();
// If the game is a win, increment the WIN by 1
if (theGame.getState() == State.WIN) {
if (handleWin() == JOptionPane.YES_OPTION) {
theGame.newGame(); // new game
/** If the AIPlayer is opponent, add the current game to its processor */
if (theGame.getAIPlayer() instanceof AIPlayer) {
((AIPlayer)theGame.getAIPlayer()).setGame(theGame);
}
updateBoard();
} else {
theView.dispose();
}
// If the game is a draw, increment the DRAW by 1
} else if (theGame.getState() == State.DRAW) {
if (handleDraw() == JOptionPane.YES_OPTION) {
theGame.newGame(); // new game
/** If the AIPlayer is opponent, add the current game to its processor */
if (theGame.getAIPlayer() instanceof AIPlayer) {
((AIPlayer)theGame.getAIPlayer()).setGame(theGame);
}
updateBoard();
} else {
theView.dispose();
}
} else {
if (theGame.isPlayable()) {
theGame.switchPlayer();
}
if (theGame.getCurrentPlayer() instanceof AutoPlayable) {
int pos = ((AutoPlayable) theGame.getCurrentPlayer()).getMove();
while (!theGame.getTheBoard().isEmpty(pos)) {
pos = ((AutoPlayable) theGame.getCurrentPlayer()).getMove();
}
theView.getButton(pos).doClick();
if (theGame.getAIPlayer() instanceof AIPlayer) {
((AIPlayer) theGame.getAIPlayer()).createNode(pos);
}
}
}
updateNextLabel();
}
/**
*
*/
private void updateNextLabel() {
/** Set the next label to appropriate player */
JLabel nextLabel = theView.getNextLabel();
if (theGame.getCurrentPlayer().getMyMark() == Mark.X) {
nextLabel.setText("X");
} else {
nextLabel.setText("O");
}
}
/**
* Handles any possible action
*/
@Override
public void actionPerformed(ActionEvent evt) {
if (theGame.getAIPlayer() instanceof AIPlayer) {
boolean check = ((AIPlayer) theGame.getAIPlayer()).getCurrentNode() == ((AIPlayer) theGame.getAIPlayer()).getHeadNode();
System.out.println("Check head node:" + check);
}
/** Make a JButton instance that stores the event source */
JButton btnClicked = (JButton) evt.getSource();
if (btnClicked == theView.getControlPanel().getBtnNewGame()) {
JComboBox<GameType> gameTypeBox = theView.getPlayerPanel()
.getGameChoices();
theGame.setGameType((GameType) gameTypeBox.getSelectedItem());
JComboBox<ComputerType> compTypeBox = theView.getPlayerPanel()
.getComputerChoices();
theGame.setComputerType((ComputerType) compTypeBox
.getSelectedItem());
theGame.newGame();
/** If the AIPlayer is opponent, add the current game to its processor */
if (theGame.getAIPlayer() instanceof AIPlayer) {
((AIPlayer)theGame.getAIPlayer()).setGame(theGame);
}
updateBoard();
updateNextLabel();
} else if (btnClicked == theView.getControlPanel().getBtnTrainAI()
&& theGame.getComputerType() == ComputerType.AI_PLAYER) {
JTextField trainText = theView.getControlPanel()
.getTrainPractices();
try {
int trainingTimes = Integer.parseInt(trainText.getText());
((AIPlayer) theGame.getAIPlayer()).trainAI(trainingTimes);
} catch (Exception e) {
// Do nothing
}
} else {
/** Check every Board button to determine the source of the even */
for (int row = 0; row < SIZE; row++)
for (int col = 0; col < SIZE; col++) {
if (evt.getSource() == theView.getButton(row, col)) {
if (theGame.getTheBoard().placeMark(
theGame.getCurrentPlayer(), row, col)) {
if (theGame.getAIPlayer() instanceof AIPlayer) {
((AIPlayer)theGame.getAIPlayer()).createNode(BoardUtility.convertPosToInt(row, col, SIZE));
}
// Update the state of the board
theGame.updateGameState();
updateViewFromModel();
}
}
}
}
}
}
package model;
import java.util.ArrayList;
import model.player.Player;
/**
* CSCI205 - Software Design and Engineering
* Name: Robert Cowen & Son Pham
*
* Work: homework-2
* Created: Nov 11, 2014, 10:23:41 PM
*/
/**
* @author skp011
*
*/
public class Board {
/** Assume the size of Tic Tac Toe board is 3 */
public static final int SIZE = 3;
/** Create the possible states of the board */
public static enum State {
NEW, PLAYING, WIN, DRAW;
}
/** Instantiate a 3x3 board */
private Mark[][] board;
/** Initialize a variable that tells the State */
private State state;
/** Initialize playerX */
private Player playerX;
/** Initialize playerO */
private Player playerO;
/**
* Constructs a new blank board with state NEW
*/
public Board() {
this.board = new Mark[3][3];
this.state = State.NEW;
this.clear();
}
/**
* Clears the board and sets the states to NEW
*/
public void clear() {
for (int row = 0; row < SIZE; row++)
for (int col = 0; col < SIZE; col++)
board[row][col] = Mark.NONE;
state = State.NEW;
}
/**
* Gets the current mark at row and col
*
* @param row
* @param col
* @return
*/
public Mark getMark(int row, int col) {
return board[row][col];
}
/** Gets the current state of the board */
public State getState() {
return state;
}
/**
* Checks if a position in the board is empty or not
*
* @param row
* @param col
* @return
*/
public boolean isEmpty(int row, int col) {
if (board[row][col] == Mark.NONE) {
return true;
}
return false;
}
/**
* Checks if a position in the board is empty or not
*
* @param row
* @param col
* @return
*/
public boolean isEmpty(int pos) {
int[] position = BoardUtility.convertIntToPos(pos, SIZE);
return isEmpty(position[0],position[1]);
}
/**
* Place the mark in the position if possible
*
* @param mark
* @param row
* @param col
* @return true if the move is successful, false if the movie is failed
*/
public boolean placeMark(Mark mark, int row, int col) {
try {
if (board[row][col] == Mark.NONE) {
board[row][col] = mark;
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Place the mark of the player in the position if possible
*
* @param mark
* @param row
* @param col
* @return true if the move is successful, false if the movie is failed
*/
public boolean placeMark(Player player, int row, int col) {
return this.placeMark(player.getMyMark(), row, col);
}
/**
* Check if the mark contains a horizontal win
*
* @param mark
* @return true if there's a full line that contains the mark
*/
private boolean horizontalWinFor(Mark mark) {
for (int row = 0; row < SIZE; row++) {
if (mark == board[row][0] && mark == board[row][1]
&& mark == board[row][2])
return true;
}
return false;
}
/**
* Check if the mark contains a horizontal win
*
* @param mark
* @return true if there's a full line that contains the mark
*/
private boolean verticalWinFor(Mark mark) {
for (int col = 0; col < SIZE; col++) {
if (mark == board[0][col] && mark == board[1][col]
&& mark == board[2][col])
return true;
}
return false;
}
/**
* check if there's any diagonal that contains the mark
*
* @param mark
* @return
*/
private boolean diagonalWinFor(Mark mark) {
if (mark == board[0][0] && mark == board[1][1] && mark == board[2][2]) {
return true;
}
if (mark == board[2][0] && mark == board[1][1] && mark == board[0][2]) {
return true;
}
return false;
}
/**
* Checks if the current board is win for certain Mark
*
* @param mark
* @return true if the mark has a winning line
*/
public boolean isWinFor(Mark mark) {
return horizontalWinFor(mark) || verticalWinFor(mark)
|| diagonalWinFor(mark);
}
/**
* Check if the player wins the board
*
* @param player
* @return
*/
public boolean isWinFor(Player player) {
return isWinFor(player.getMyMark());
}
/**
* check if the board is full or not
*
* @return true if the board if full, false other wise
*/
public boolean isFull() {
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++) {
if (board[row][col] == Mark.NONE)
return false;
}
return true;
}
/**
* Updates the board state everytime there's a new mark placed on the board
*/
public void updateBoardState() {
state = State.PLAYING;
// change state to WIN if either player win
if (this.isWinFor(Mark.X) || this.isWinFor(Mark.O)) {
state = State.WIN;
}
// if neither player wins and the board is full, the state is DRAW
else if (this.isFull()) {
state = State.DRAW;
}
}
/**
* CHeck if the board is still playable
*
* @return true if the board is still playable, false otherwise.
*/
public boolean isPlayable() {
if (state == State.PLAYING || state == State.NEW) {
return true;
} else {
return false;
}
}
/**
* Returns an array of empty positions that can still be played
*
* @return array of empty position.
*/
public ArrayList<Integer> getEmptyPosition() {
ArrayList<Integer> arrayOfEmpty = new ArrayList<Integer>();
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (board[row][col] == Mark.NONE) {
arrayOfEmpty.add(BoardUtility.convertPosToInt(row, col,
SIZE));
}
}
}
return arrayOfEmpty;
}
/**
* A string representation of the object return a string in the format
* |X|O|X| |O|X|O| |X|O|X|
*/
@Override
public String toString() {
String s = "";
s += "state = " + this.getState();
s += "\n";
for (int row = 0; row < SIZE; row++) {
s += "|";
for (int col = 0; col < SIZE; col++) {
if (this.getMark(row, col) == Mark.NONE) {
s += " ";
} else {
s += this.getMark(row, col);
}
s += "|";
}
s += "\n";
}
return s;
}
}
/**
* CSCI205 - Software Design and Engineering
* Name: Robert Cowen & Son Pham
*
* Work: homework-2
* Created: Nov 11, 2014, 10:23:41 PM
*/
package model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import model.player.Player;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* This class tests some method belonging to Board class
*
* @author skp011
*
*/
public class BoardTest {
/** Initialize a testing board */
private Board board1;
@Before
/** Make a testing board with some mark on it
* |X| |O|
* |O|X|O|
* | | | |
*/
public void before() {