Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Array._
- var gameBoard = List.fill[Char](3,3)(' ')
- def makeRow(row: List[Char]) {
- var left = " " + row(0) + " |"
- var middle = " " + row(1) + " |"
- var right = " " + row(2) + " "
- println(left.concat(middle).concat(right))
- }
- def render() {
- (1 to 30).foreach(_ => println("\n"))
- val divider = "---+---+---"
- makeRow(gameBoard(0))
- println(divider)
- makeRow(gameBoard(1))
- println(divider)
- makeRow(gameBoard(2))
- }
- def gameHasMetEndCondition(Player: Char) : Boolean = {
- if (gameBoard(0).forall(x => (x.equals(Player)))
- || gameBoard(1).forall(x => (x.equals(Player)))
- || gameBoard(2).forall(x => (x.equals(Player)))
- || List(gameBoard(0)(0), gameBoard(1)(0), gameBoard(2)(0)).forall(x => (x.equals(Player)))
- || List(gameBoard(0)(1), gameBoard(1)(1), gameBoard(2)(1)).forall(x => (x.equals(Player)))
- || List(gameBoard(2)(0), gameBoard(2)(1), gameBoard(2)(2)).forall(x => (x.equals(Player)))
- || List(gameBoard(0)(0), gameBoard(1)(1), gameBoard(2)(2)).forall(x => (x.equals(Player)))
- || List(gameBoard(2)(0), gameBoard(1)(1), gameBoard(0)(2)).forall(x => (x.equals(Player)))) return true
- return false
- }
- class Player(playerMarker: Char) {
- val marker = playerMarker
- var name = ""
- }
- var playerOne = new Player('X')
- var playerTwo = new Player('O')
- println("Welcome to TicTacToe. First player, what’s your name?")
- playerOne.name = readLine
- println("Second player, what’s your name?")
- playerTwo.name = readLine
- for (turn <- 1 to 9) {
- render
- var currentPlayer = if (turn % 2 < 1) playerTwo else playerOne
- if (gameHasMetEndCondition(currentPlayer.marker)) {
- // Threw an exception here because I’m not sure how to break
- // out of a loop. Looks as though it can’t actually be done
- // this way in Scala.
- throw new Exception("Game has ended")
- }
- println((currentPlayer.name).concat(", make your move."))
- var row = readLine.toInt
- var column = readLine.toInt
- gameBoard = gameBoard.updated(row, gameBoard(row).updated(column, currentPlayer.marker))
- }
- println("It’s a tie. Everyone’s a winner.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement