Created
March 27, 2015 16:30
-
-
Save pumpkincouture/322284841716bfa7771e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class GameWinnerDetector { | |
protected String findBoardWinner(int boardLength) { | |
for (int index = 0; index < boardLength; index++) { | |
addGamePiecesToList(index); | |
} | |
return checkIfWinnerExists(); | |
} | |
protected abstract void addGamePiecesToList(int index); | |
protected abstract String checkIfWinnerExists(); | |
} | |
public class LeftDiagonalWinnerDetector extends GameWinnerDetector { | |
private Board board; | |
private WinnerValidator winnerValidator; | |
private String[] lineValues; | |
public LeftDiagonalWinnerDetector(Board board, WinnerValidator winnerValidator) { | |
this.board = board; | |
this.winnerValidator = winnerValidator; | |
this.lineValues = new String[board.getMatrix().length]; | |
} | |
@Override | |
protected void addGamePiecesToList(int index) { | |
lineValues[index] = winnerValidator.getValueAtIndex(board, index, index); | |
} | |
@Override | |
protected String checkIfWinnerExists() { | |
return winnerValidator.checkDiagonalsForWin(board, lineValues); | |
} | |
} | |
public class WinnerValidator { | |
public String checkDiagonalsForWin(Board board, String[] lineValues) { | |
if (isWinningCombo(board, lineValues)) { | |
return lineValues[0]; | |
} | |
return ""; | |
} | |
public String checkRowsAndColumnsForWin(Board board, String[][] lineValues) { | |
for (int i = 0; i < board.getMatrix().length; i++) { | |
if (isWinningCombo(board, lineValues[i])) { | |
return lineValues[i][0]; | |
} | |
} return ""; | |
} | |
public String getValueAtIndex(Board board, int startingIndex, int endingIndex) { | |
return board.getMatrix()[startingIndex][endingIndex]; | |
} | |
public boolean isWinningCombo(Board board, String[] lineValues) { | |
String first = lineValues[0]; | |
for (String value : lineValues) { | |
if (value != first || value == board.getBoardEmptySpace()) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment