我是Scala和函數式編程的新手。我正在製作一個井字遊戲('Seven Words in Seven Weeks'(書))的第一天),我想知道如何以功能的方式做'檢查是否贏得'方法。在Scala中使用array.exists()
我想使'checkrow'部分(第一部分)像'checkcolumn'(第二部分)部分,但我正在嘗試不工作。
這裏我的(工作)代碼:
def checkGame() {
for (y <- board.indices) {
// checks a row
checkRow(y)
}
for (x <- board(0).indices) {
// checks a column
if(!board.exists(y => y(x) != 'x')){
println("You have won mate! (column: " + x + ")")
}
}
}
def checkRow(y: Integer) {
var isWon = true
for (x <- board(y).indices) {
if (board(y)(x) != 'x') {
isWon = false
}
}
if (isWon) println("You have won mate! (row: " + y + ")")
}
注:板是一個2維陣列。
我得到了什麼至今(不工作):
if(!board.exists(x => x(y) != 'x')){
println("You have won mate! (row: " + x + ")")
}
如果您使用'for'lopps和變量突變,您不會以「功能性方式」執行此操作。 – RichouHunter