class Langton(matrix:Array[Array[Char]], ant:Ant) {
  import Langton._
  val rows=matrix.size
  val cols=matrix(0).size

  def isValid = 0 <= ant.row && ant.row < cols && 0 <= ant.col  && ant.col < rows
  def isBlack=matrix(ant.row)(ant.col)==BLACK
  def changeColor(c:Char)={matrix(ant.row)(ant.col)=c; matrix}

  def evolve():Langton={
    val (newCol, newAnt)=if(isBlack) (WHITE, ant.turnLeft) else (BLACK, ant.turnRight)
    new Langton(changeColor(newCol), newAnt.move)
  }
  override def toString()=matrix map (_.mkString("")) mkString "\n"	
}

case class Ant(row:Int, col:Int, d:Int=0) {
  def turnLeft=Ant(row,col,(d-1)&3)
  def turnRight=Ant(row,col,(d+1)&3)
  def move=d match {
    case 0 => Ant(row-1,col,d)