Created
February 16, 2017 22:14
-
-
Save anjarfr/5f9bf0b56bea5590d750795bb3353c1d to your computer and use it in GitHub Desktop.
This file contains 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
package objectstructures; | |
import java.util.ArrayList; | |
import TicTacCell; | |
public class TicTacBoard { | |
public ArrayList<TicTacCell> board; | |
public char player; | |
public char c; | |
public int countrow = 0; | |
public int countcol = 0; | |
public TicTacBoard() { | |
player = 'x'; | |
for (int i = 0; i<3; i++) { | |
board.add(new TicTacCell()); | |
} | |
} | |
public char getCell(int x, int y) { | |
return board.get(x*(y-1) + y*(x-1)); | |
} | |
public boolean setCell(char c, int x, int y) { | |
if (isOccupied()) { | |
return false; | |
} else { | |
board.get(x*(y-1) + y*(x-1)).setValue(c); | |
return true; | |
} | |
} | |
public char getCurrentPlayer() { | |
return player; | |
} | |
public boolean play(int x, int y) { | |
if (! isFinished()) { | |
setCell(getCurrentPlayer(),x,y); | |
if (getCurrentPlayer() == 'x') { | |
player = 'o'; | |
} else { | |
player = 'x'; | |
} | |
} | |
} | |
boolean isWinner(char c, int countrow, int countcol) { | |
for (int i=0; i<3; i++) { | |
for (int j=0; j<3; j++) { | |
if (getCell(i,j) == c ) { | |
countrow+=1; | |
} | |
if (getCell(j,i) == c ) { | |
countcol+=1; | |
} | |
} | |
if (countrow == 3 || countcol == 3) { | |
return true; | |
} | |
countrow = 0; | |
countcol = 0; | |
} | |
if ((getCell(0,0) == c && getCell(1,1) == c && getCell(2,2) == c) || (getCell(2,0) == c && getCell(1,1) == c && getCell(2,0) == c)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
private boolean isFinished() { | |
for (i=0; i<9; i++) { | |
if (! board.get(i).isOccupied()) { | |
return false; | |
} | |
} | |
if (hasWinner()) { | |
return true; | |
} else { | |
return true; | |
} | |
} | |
private boolean hasWinner() { | |
if (isWinner()) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment