Joe Rawlings Software Engineer

5Mar/110

Scala Day 1 Tic-Tac-Toe

I've been reading the book 7 Languages in 7 Weeks and I have been really enjoying it so far. I've finally hit the Scala section for which I have some long-term interest in. The first day had a couple of trivial problems, including a Tic-Tac-Toe one that I provided my amateur solution for :) As I go through more, I will be posting my solutions.

If any readers have any suggestions, please speak up. Also, if you couldn't tell, I come from a mostly java background :)

import collection.mutable.ArrayBuffer
import util.Random

object TicTacToe extends Application {
  val board = ArrayBuffer("-")

  val winningIndexTuples = List(List(0, 1, 2),
                                List(3, 4, 5),
                                List(6, 7, 8),
                                List(0, 4, 8),
                                List(2, 4, 6),
                                List(0, 3, 6),
                                List(1, 4, 7),
                                List(2, 5, 8))

  // 8 plus the one in the cell
  for (x <- 1 to 8) {
    board += "-"
  }

  var turn = true
  var winner = false

  var rnd = -1

  println(board)

  while((board contains "-") && !winner) {

    do {
      rnd = Random nextInt 9
    } while(board(rnd) == 0 || board(rnd) == 1)

    if(turn) { board.update(rnd, "X")}
    else { board.update(rnd, "O")}

    turn = !turn;

    winner = checkBoard
  }

  println(board)

  def checkBoard = {
    val winner = checkWinner("X") || checkWinner("O")
    if(winner) { println("winner!") }
    winner
  }

  def checkWinner(player : String) = {
    winningIndexTuples.exists(winningIndexTuple => winningIndexTuple.forall(board(_) == player))
  }
}
Comments (0) Trackbacks (1)

Leave a comment

(required)