我在scala中写了一个简单的tic tac toe游戏实现。
package tiktaktoe
/**
* Created by donbeo on 28/12/15.
*/
class Board {
val size = 3
// size of the board
val goal = 3
// number in line. These values are assumed to be always 3 and 3
val board = Array.fill(size, size)(0) // the board
def isValidPosition(pos: Pos): Boolean = {
if (pos._1 >= 0 && pos._2 >= 0 && pos._1 < size && pos._2 < size && board(pos._1)(pos._2) == 0) true
else false
}
def setPosition(pos: Pos, number: Int): Unit = {
if (isValidPosition(pos)) {
board(pos._1)(pos._2) = number
println(this)
val winner = winningPlayer
if (winner != 0) println("The winner is: Player " + winner)
}
else throw new Exception("Not Valid Position")
}
def winningPlayer: Int = {
if (isLine(0) != 0) isLine(0)
if (isLine(1) != 0) isLine(1)
if (isLine(2) != 0) isLine(2)
if (isColumn(0) != 0) isColumn(0)
if (isColumn(1) != 0) isColumn(1)
if (isColumn(2) != 0) isColumn(2)
if (isDiagonal != 0) isDiagonal
else 0
}
private def isLine(line: Int): Int = {
// this works only if goal = size
val number = board(line)(0)
if (number == 0) return 0
else if (board(line) == Array.fill(size)(number)) return number
else 0
}
private def isColumn(column: Int): Int = {
val number = board(0)(column)
if (number == 0) 0
else if (board(1)(column) == number && board(2)(column) == number) number
else 0
}
private def isDiagonal: Int = {
val number = board(1)(1)
if (board(2)(2) == number && board(1)(1) == number) number
else if (board(0)(2) == number && board(2)(0) == number) number
else 0
}
override def toString = "Board=\n" + board.deep.mkString("\n") + "\n"
}
class Player(number: Int) {
private def computeNextMove(board: Board): Pos = {
(2, 3)
}
def nextMove(board: Board, pos: Pos): Unit = {
board.setPosition(pos, number)
}
}
object PlayGame {
def main(args: Array[String]) {
val board = new Board
val players = List(new Player(1), new Player(2))
println("Start the game \n\n" + board)
players(0).nextMove(board, (1, 0))
players(1).nextMove(board, (1, 1))
players(0).nextMove(board, (1, 2))
players(1).nextMove(board, (0, 0))
players(0).nextMove(board, (2, 1))
players(1).nextMove(board, (2, 2))
}
}
游戏基于修改棋盘状态的功能Player.nextMove
。据我所知,最好避免scala中的可变变量。
我想知道如何在不使用可变board