Skip to content

Instantly share code, notes, and snippets.

@erlinis
Last active August 29, 2015 14:09
Show Gist options
  • Save erlinis/4b4b5cd89e533b3b7a87 to your computer and use it in GitHub Desktop.
Save erlinis/4b4b5cd89e533b3b7a87 to your computer and use it in GitHub Desktop.
TicTacToe Game
class TicTacToe {
private def rows = 3
private def cols = 3
private def board
private def currentPlayer
private def winner = ""
TicTacToe(firstPlayer="X"){
this.currentPlayer = firstPlayer
this.board = new Object[rows][cols]
this.winner = ""
}
def play(row, col){
if(winner){
println "Sorry, there's is already a winner, it is << ${winner} >>"
} else {
if(!isBoardComplete()){
if (isAValidMove(row, col)) {
makeAMove(row,col)
} else {
println "Invalid move. Try again!"
}
}
}
}
private changePlayer(){
currentPlayer = (currentPlayer == "X")? "0" : "X"
}
private isAValidMove(row, col){
(row < 3) && (col < 3) && (board[row][col] == null)
}
private makeAMove(int row, int col){
writeAMove(row, col)
printBoard()
checkWinner()
changePlayer()
}
private writeAMove(row, col){
board[row][col] = currentPlayer
}
def checkWinner(){
if( verifyWinInRows() || verifyWinInCols() || verifyWinInDiagonals() ){
winner = currentPlayer
println "Congrats! << ${winner} >> you are the winner "
}
}
private verifyWinInRows(){
for(row in 0..(rows-1) ) {
if (checkMoves(board[row][0], board[row][1], board[row][2])){
return true;
}
}
return false
}
private verifyWinInCols(){
for(col in 0..(cols-1) ) {
if(checkMoves(board[0][col], board[1][col], board[2][col])){
return true
}
}
return false
}
private verifyWinInDiagonals(){
(checkMoves(board[0][0], board[1][1], board[2][2]) || checkMoves(board[0][2], board[1][1], board[2][0]))
}
private checkMoves(cell1, cell2, cell3){
(cell1 != null) && (cell1 == cell2 ) && (cell2 == cell3)
}
def isBoardComplete(){
String dashboard = "\n"
for(row in 0..(rows-1) ) {
for(col in 0..(cols-1) ) {
if (board[row][col] == null) {
return false
}
}
}
return true
}
def printBoard(){
String dashboard = "\n"
for(row in 0..(rows-1) ) {
for(col in 0..(cols-1) ) {
dashboard += " | " + (board[row][col]?:"-")
}
dashboard += " |\n"
}
println dashboard
println "-- " * 10
}
}
TicTacToe game = new TicTacToe("0")
println " = New game = "
while(game.winner == "" && !game.isBoardComplete()){
def move = System.console().readLine("What your move $game.currentPlayer ?")
def moveArray = move?.split(",")
if (moveArray){
def rowEntered = moveArray[0].toInteger()
def colEntered = moveArray[1].toInteger()
println "< $game.currentPlayer > wants play row: $rowEntered, col: $colEntered"
game.play(rowEntered, colEntered)
}
}
println " * Game Over * "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment