In a game of Connect4:
- we start with an empty grid
- two players place pieces X and O on the grid
- the first player to achieve 4 pieces in a line wins!
- this is a text based console game
Here is the code I wrote to print each cell in the grid:
def asText(grid: Grid) = {
def asText(x:Int, y:Int) = {
val isTop = y == 0 && x != grid.x + 1 && x != 0
val newLine = x == grid.x + 1
val isBottom = y == grid.y + 1 && x != 0
val isLeft = x == 0
val isX = grid.pieces.contains(Piece("X", x,y))
val isY = grid.pieces.contains(Piece("O", x,y))
List(isTop, newLine, isBottom, isLeft, isX, isY) match {
case true::_ => "-"
case _::true::_ => "|\n"
case _::_::true::_ => "-"
case _::_::_::true::_ => "|"
case _::_::_::_::true::_ => "X"
case _::_::_::_::_::true::_ => "O"
case _ => "."
}
}
val v = for {
y <- 0 to grid.y + 1
x <- 0 to grid.x + 1
text = asText(x, y)
} yield text
v.mkString("")
}
I don't like this _::_::_::_::_::true::_
but can't think of a way to improve it. Can this style be improved? Is there a more Scala idiomatic style to do this?
Example output:
|------|
|XO....|
|......|
|......|
|......|
|......|
|......|
|......|
|------|
Edit: As requested
case class Piece(symbol:String, x:Int, y:Int)
case class Grid(x:Int = 6, y:Int = 7, pieces:List[Piece] = List())