Scala中的Connect-Four游戏

时间:2015-05-04 19:02:13

标签: scala

我必须使用scala制作一个连接四游戏。我已经附加了代码,但每次游戏运行并进入第3行时,它只会继续更改第二行条目而不是转到下一行。任何帮助,将不胜感激。我在another thread上找到了此代码,但无法弄清楚如何让它工作:

// makes the board
val table = Array.fill(9,8)('-') 
var i = 0; 
while(i < 8){ 
  table(8)(i) = (i+'0').toChar 
  i = i+1;
}

// prints starting board
def printBoard(table: Array[Array[Char]]) { 
  table.foreach( x => println(x.mkString(" ")))
}


//player 1 moves
def playerMove1(){
  val move = readInt
  var currentRow1 = 7
  while (currentRow1 >= 0)
    if (table(currentRow1)(move) != ('-')) {
      currentRow1 = (currentRow1-1)
      table(currentRow1)(move) = ('X')
      return (player2)}
    } else {
      table(currentRow1)(move) =  ('X')
      return (player2)
    }
}

//player 2 moves
def playerMove2(){
  val move = readInt
  var currentRow2 = 7
  while (currentRow2 >= 0)
    if (table(currentRow2)(move) != ('-')) {
      currentRow2 = (currentRow2-1)
      table(currentRow2)(move) = ('O')
      return (player1)}
    } else {
      table(currentRow2)(move) =  ('O')
      return (player1)
    }
}

//player 1
def player1(){
    printBoard(table)
    println("Player 1 it is your turn. Choose a column 0-7")
    playerMove1()
}

//player 2
def player2(){
    printBoard(table)
    println("Player 2 it is your turn. Choose a column 0-7")
    playerMove2()
}

for (turn <- 1 to 32){
    player1
    player2
}

1 个答案:

答案 0 :(得分:2)

我已尝试让您的代码可读和编译,并尝试修复某些逻辑。

但是,我从未与Scala合作过,所以这只是你想要继续的第一个草图...

某些功能可以合并,currentRow需要修复。见这里:

object ConnectFour{
  val table = Array.fill(9,8)('-') 
  val currentRow = Array.fill(8)(8)

  def main(args: Array[String]) {
    var i = 0; 
    while(i < 8) {
      table(8)(i) = (i+'0').toChar 
      i = i+1;
    }

    player(1)
  }

  def printBoard(table: Array[Array[Char]]) { 
    table.foreach( x => println(x.mkString(" ")))
  }

  def player(playerNr : Int){
    printBoard(table)
    println("Player " + playerNr + " it is your turn. Choose a column 0-7")
    var column = readAndVerifyInt

    var nextUser = 1 : Int
    var symbol = 'O' : Char

    if(playerNr == 1) {
        symbol = 'X'
        nextUser = 2
    }

    var curR = currentRow(column)
    while (curR >= 0) {
      if (table(curR)(column) != ('-')) {
        curR = curR-1
        currentRow(column) = curR
      }
      table(curR)(column) = symbol
      player(nextUser)
    }
  }

  def readAndVerifyInt() : Int = {
      var column = readInt
      if (column >= 0 && column <= 7) {
          return column
      } else {
          println(" > Please try again")
          return readAndVerifyInt
      }
  }
}