Skip to content

Instantly share code, notes, and snippets.

@scsibug
Created February 1, 2012 23:31
Show Gist options
  • Save scsibug/1720149 to your computer and use it in GitHub Desktop.
Save scsibug/1720149 to your computer and use it in GitHub Desktop.
tic-tac-toe (7 languages in 7 Weeks, Scala chapter)
import scala.Console
// Write a game that will take a tic-tac-toe board with X, O, and blank
// characters and detect the winner or whether there is a tie or no
// winner yet. Use classes where appropriate.
// Represent a board with X,O,blank plays.
class Board(positions:String) {
val winningTuples = List( (0,1,2), (3,4,5), (6,7,8), // L-to-R
(0,3,6), (1,4,7), (2,5,8), // T-to-B
(0,4,8), (2,4,6)) // Diagonal
def countWinsFor(p:Char):Int = {
val possibleWins = winningTuples.map(t => (positions.charAt(t._1), positions.charAt(t._2), positions.charAt(t._3)))
possibleWins.filter( _ == (p, p, p)).length
}
def evalGameState:GameState = {
val (x, o) = (countWinsFor('X'), countWinsFor('O'))
(x compareTo o) match {
case -1 => OWins
case 1 => XWins
case 0 => if (x == 0) NoWinner else Tie
}
}
}
trait GameState
object XWins extends GameState { override def toString = "X Wins" }
object OWins extends GameState { override def toString = "O Wins" }
object Tie extends GameState { override def toString = "Tie" }
object NoWinner extends GameState { override def toString = "No Winner" }
// Read in 9 characters. Ignore anything but " ", "X", and "O".
println("Enter a board")
object boardBuffer {
var buffer = new StringBuffer()
def accum(c:Char) { buffer.append(c) }
def board:Option[String] = {
(buffer.length >= 9) match {
case true => {
val b = buffer.substring(0,9)
buffer = new StringBuffer()
Some(b)
}
case false => None
}
}
}
while(true) {
val r = Console.readLine()
r match {
case null => println("(ignoring EOF)")
case x => x.foreach( c =>
if (c == ' ' || c == 'X' || c == 'O') {
boardBuffer.accum(c)
}
)
}
boardBuffer.board.map(s => println(new Board(s).evalGameState))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment