Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Last active February 6, 2018 03:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/c910f66152eb44cc42cc3187cf12fa56 to your computer and use it in GitHub Desktop.
Save ssaurel/c910f66152eb44cc42cc3187cf12fa56 to your computer and use it in GitHub Desktop.
Board for a Tic-Tac-Toe game on SSaurel's Blog
package com.ssaurel.tictactoe;
import java.util.Random;
public class Board {
private static final Random RANDOM = new Random();
private char[] elts;
private char currentPlayer;
private boolean ended;
public Board() {
elts = new char[9];
newGame();
}
public boolean isEnded() {
return ended;
}
public char play(int x, int y) {
if (!ended && elts[3 * y + x] == ' ') {
elts[3 * y + x] = currentPlayer;
changePlayer();
}
return checkEnd();
}
public void changePlayer() {
currentPlayer = (currentPlayer == 'X' ? 'O' : 'X');
}
public char getElt(int x, int y) {
return elts[3 * y + x];
}
public void newGame() {
for (int i = 0; i < elts.length; i++) {
elts[i] = ' ';
}
currentPlayer = 'X';
ended = false;
}
public char checkEnd() {
for (int i = 0; i < 3; i++) {
if (getElt(i, 0) != ' ' &&
getElt(i, 0) == getElt(i, 1) &&
getElt(i, 1) == getElt(i, 2)) {
ended = true;
return getElt(i, 0);
}
if (getElt(0, i) != ' ' &&
getElt(0, i) == getElt(1, i) &&
getElt(1, i) == getElt(2, i)) {
ended = true;
return getElt(0, i);
}
}
if (getElt(0, 0) != ' ' &&
getElt(0, 0) == getElt(1, 1) &&
getElt(1, 1) == getElt(2, 2)) {
ended = true;
return getElt(0, 0);
}
if (getElt(2, 0) != ' ' &&
getElt(2, 0) == getElt(1, 1) &&
getElt(1, 1) == getElt(0, 2)) {
ended = true;
return getElt(2, 0);
}
for (int i = 0; i < 9; i++) {
if (elts[i] == ' ')
return ' ';
}
return 'T';
}
public char computer() {
if (!ended) {
int position = -1;
do {
position = RANDOM.nextInt(9);
} while (elts[position] != ' ');
elts[position] = currentPlayer;
changePlayer();
}
return checkEnd();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment