Created
May 4, 2012 04:39
-
-
Save jomontanari/2592066 to your computer and use it in GitHub Desktop.
Scala Day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WinCombo(position1 : Int, position2 : Int, position3 : Int) { | |
def isMatch(positions : Array[Int]) : Boolean = { | |
positions.contains(position1) && positions.contains(position2) && positions.contains(position3) | |
} | |
} | |
class Judge { | |
val winningCombos = List( | |
new WinCombo(1, 2, 3), | |
new WinCombo(4, 5, 6), | |
new WinCombo(7, 8, 9), | |
new WinCombo(1, 4, 7), | |
new WinCombo(2, 5, 8), | |
new WinCombo(3, 6, 9), | |
new WinCombo(1, 5, 9), | |
new WinCombo(3, 5, 7)) | |
def isWinner(positions : Array[Int]) : Boolean = { | |
winningCombos.foreach{ combo => | |
if (combo.isMatch(positions)) return true | |
} | |
false | |
} | |
} | |
def playTicTacToe { | |
println("Enter the current moves for X:") | |
val xMoves = getPositions(Console.readLine().split(",")) | |
println("Enter the current moves for Y:") | |
val yMoves = getPositions(Console.readLine().split(",")) | |
val judge = new Judge() | |
val xWon = judge.isWinner(xMoves) | |
val yWon = judge.isWinner(yMoves) | |
if (xWon == yWon) { | |
Console.println("It's a draw!") | |
} else { | |
Console.println("The winner is ...") | |
if (xWon) Console.println("X") | |
if (yWon) Console.println("Y") | |
} | |
} | |
def getPositions(moves : Array[String]) : Array[Int] = { | |
moves.map(move => Integer.parseInt(move)) | |
} | |
playTicTacToe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment