diff options
author | Guillermo Ramos | 2012-05-06 14:40:34 +0200 |
---|---|---|
committer | Guillermo Ramos | 2012-05-06 14:40:34 +0200 |
commit | e17d06cbdd0eae3fcc193c345f787a28cb031cea (patch) | |
tree | e5132ca97a5016354b46c4302cb1854fda879a8d /scala/ttt.scala | |
parent | 201bbad350345a63520338e74da96d4d31c8ebbc (diff) | |
download | 7l-e17d06cbdd0eae3fcc193c345f787a28cb031cea.tar.gz |
[Scala] Día 1
Diffstat (limited to 'scala/ttt.scala')
-rw-r--r-- | scala/ttt.scala | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/scala/ttt.scala b/scala/ttt.scala new file mode 100644 index 0000000..f7fba1c --- /dev/null +++ b/scala/ttt.scala @@ -0,0 +1,74 @@ +class Board(var layout: Array[Char]) { + if (!layout.mkString.matches("[xo ]{9}")) { + println("Invalid layout") + layout = " ".toArray + } + + def this() { + this(" ".toArray) + } + + def show { + println("\n --- ") + println("|" + layout.mkString.substring(0,3) + "|") + println("|" + layout.mkString.substring(3,6) + "|") + println("|" + layout.mkString.substring(6,9) + "|") + println(" --- ") + } + + def status:Char = { + // Horizontal + if (layout(0) == layout(1) && layout(1) == layout(2)) + return layout(0) + else if (layout(3) == layout(4) && layout(4) == layout(5)) + return layout(3) + else if (layout(6) == layout(7) && layout(7) == layout(8)) + return layout(7) + + // Vertical + else if (layout(0) == layout(3) && layout(3) == layout(6)) + return layout(0) + else if (layout(1) == layout(4) && layout(4) == layout(7)) + return layout(1) + else if (layout(2) == layout(5) && layout(5) == layout(8)) + return layout(2) + + // Diagonal + else if (layout(0) == layout(4) && layout(4) == layout(8)) + return layout(0) + else if (layout(2) == layout(4) && layout(4) == layout(6)) + return layout(2) + + return if (layout.contains(' ')) ' ' else 't' + } + + def play { + var st = status + var player = 'x' + var input = "" + + reset + show + while (st == ' ') { + print("Player " + player + "> ") + input = readLine + if (input.matches("[0-8]") && layout(input.toInt) == ' ') { + layout(input.toInt) = player + show + player = if (player == 'x') 'o' else 'x' + } + st = status + } + if (status == 't') + println("There is a tie!") + else + println("The winner is " + status + "!") + } + + def reset { + layout = " ".toArray + } +} + +var playBoard = new Board +playBoard.play |