Skip to content

Instantly share code, notes, and snippets.

@mallman
Created April 14, 2015 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mallman/4845a3c45745e59a4c9d to your computer and use it in GitHub Desktop.
Save mallman/4845a3c45745e59a4c9d to your computer and use it in GitHub Desktop.
Atomic Scala Summary 2 Exercise 8
class Cell {
var entry = ' '
def set(e:Char):String = {
if(entry==' ' && (e=='X' || e=='O')) {
entry = e
"successful move"
} else
"invalid move"
}
}
class Grid {
val cells = Vector(
Vector(new Cell, new Cell, new Cell),
Vector(new Cell, new Cell, new Cell),
Vector(new Cell, new Cell, new Cell)
)
def play(e:Char, x:Int, y:Int):String = {
if(x < 0 || x > 2 || y < 0 || y > 2)
"invalid move"
else {
val move = cells(x)(y).set(e)
if (winner) {
println("We have a winner! :)")
} else if (cells.forall(_.forall(_.entry != ' '))) {
println("We have a draw! :(")
}
move
}
}
def winner(): Boolean = {
def winnerLine(line: Seq[Cell]): Boolean =
line.forall(_.entry == 'X') || line.forall(_.entry == 'O')
val range: Range = (0 until cells.size)
val transposition: Seq[Seq[Cell]] = (0 to 2).map { i =>
(0 to 2).map { j => cells(j)(i) }
}
val diagonalLeft = (0 to 2).map { i => cells(i)(i) }
val diagonalRight = (0 to 2).map { i => cells(i)(cells.size - i - 1) }
cells.exists(winnerLine) || transposition.exists(winnerLine) ||
winnerLine(diagonalLeft) || winnerLine(diagonalRight)
}
}
val grid = new Grid
grid.play('X', 1, 1)
grid.play('O', 1, 2)
grid.play('X', 2, 1)
grid.play('O', 2, 2)
grid.play('X', 0, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment