Advertisement
Guest User

Untitled

a guest
Apr 7th, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.11 KB | None | 0 0
  1. import Array._
  2.  
  3. var gameBoard = List.fill[Char](3,3)(' ')
  4.  
  5. def makeRow(row: List[Char]) {
  6.   var left = " " + row(0) + " |"
  7.   var middle = " " + row(1) + " |"
  8.   var right = " " + row(2) + " "
  9.   println(left.concat(middle).concat(right))
  10. }
  11.  
  12. def render() {
  13.   (1 to 30).foreach(_ => println("\n"))
  14.   val divider = "---+---+---"
  15.   makeRow(gameBoard(0))
  16.   println(divider)
  17.   makeRow(gameBoard(1))
  18.   println(divider)
  19.   makeRow(gameBoard(2))
  20. }
  21.  
  22. def gameHasMetEndCondition(Player: Char) : Boolean = {
  23.   if (gameBoard(0).forall(x => (x.equals(Player)))
  24.       || gameBoard(1).forall(x => (x.equals(Player)))
  25.       || gameBoard(2).forall(x => (x.equals(Player)))
  26.       || List(gameBoard(0)(0), gameBoard(1)(0), gameBoard(2)(0)).forall(x => (x.equals(Player)))
  27.       || List(gameBoard(0)(1), gameBoard(1)(1), gameBoard(2)(1)).forall(x => (x.equals(Player)))
  28.       || List(gameBoard(2)(0), gameBoard(2)(1), gameBoard(2)(2)).forall(x => (x.equals(Player)))
  29.       || List(gameBoard(0)(0), gameBoard(1)(1), gameBoard(2)(2)).forall(x => (x.equals(Player)))
  30.       || List(gameBoard(2)(0), gameBoard(1)(1), gameBoard(0)(2)).forall(x => (x.equals(Player)))) return true
  31.   return false
  32. }
  33.  
  34. class Player(playerMarker: Char) {
  35.   val marker = playerMarker
  36.   var name = ""
  37. }
  38.  
  39. var playerOne = new Player('X')
  40. var playerTwo = new Player('O')
  41.  
  42. println("Welcome to TicTacToe. First player, what’s your name?")
  43. playerOne.name = readLine
  44. println("Second player, what’s your name?")
  45. playerTwo.name = readLine
  46.  
  47. for (turn <- 1 to 9) {
  48.   render
  49.  
  50.   var currentPlayer = if (turn % 2 < 1) playerTwo else playerOne
  51.  
  52.   if (gameHasMetEndCondition(currentPlayer.marker)) {
  53.     // Threw an exception here because I’m not sure how to break
  54.     // out of a loop. Looks as though it can’t actually be done
  55.     // this way in Scala.
  56.     throw new Exception("Game has ended")
  57.   }
  58.  
  59.   println((currentPlayer.name).concat(", make your move."))
  60.   var row = readLine.toInt
  61.   var column = readLine.toInt
  62.   gameBoard = gameBoard.updated(row, gameBoard(row).updated(column, currentPlayer.marker))
  63.  
  64. }
  65.  
  66. println("It’s a tie. Everyone’s a winner.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement