2014-11-22 69 views
0

我想在斯卡拉连接四场比赛。目前,我已经打印出棋盘并向玩家1要求移动,一旦玩家1选择一个数字,棋盘就会在玩家1选择的列中用X打印出来。然后玩家2挑选一个数字。我的问题是,一旦我选择了一个玩家的字母填充整个列的数字,并且你在其上创建了一个数字。斯卡拉连接四场比赛

继承人发生了什么

. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
. X . O X . . . 
0 1 2 3 4 5 6 7 


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

/* printGrid: Print out the grid provided */ 
def printGrid(table: Array[Array[Char]]) { 
table.foreach(x => println(x.mkString(" "))) 
    } 


/*//place of pieces X 
def placeMarker(){ 
val move = readInt 
//var currentRow = 7 
while (currentRow >= 0) 
    if (table(currentRow)(move) != ('.')){ 
     currentRow = (currentRow-1) 
     table(currentRow)(move) = ('X') 
      return (player2)} 
     else{ 
     table(currentRow)(move) = ('X') 
      return (player2) 
      } 
    } 

//place of pieces O 
def placeMarker2(){ 
    val move = readInt 
    //var currentRow = 7 
    while (currentRow >= 0) 
     if (table(currentRow)(move) != ('.')){ 
      currentRow = (currentRow-1) 
      table(currentRow)(move) = ('O') 
       return (player1)} 
     else{ 
      table(currentRow)(move) = ('O') 
       return (player1) 
      } 
     } 
*/ 

def placeMarker1(){ 
val move = readInt 
var currentRow = 7 
while (currentRow >= 0) 
    if (table(currentRow)(move) !=('.')) 
     {currentRow = (currentRow-1)} 
    else{table(currentRow)(move) = ('X')} 
} 

def placeMarker2(){ 
val move = readInt 
var currentRow = 7 
while (currentRow >= 0) 
    if (table(currentRow)(move) !=('.')) 
     {currentRow = (currentRow-1)} 
    else{table(currentRow)(move) = ('O')} 
} 

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

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

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

回答

0

你的全局状态是搞乱您一个例子:var currentRow = 7

,而不是试图跟踪所有列全球“currentRow”的,我会建议其中之一:

  1. currentRows数组中的每列保留一个单独的“currentRow”。
  2. 每次您放置一块以找到最低的空插槽时,只需遍历该列即可。

实际上,它看起来像你最初在做第二个建议,但是你注释掉了你的本地currentRow变量并且声明了全局(实例级)变量。

+0

因此,当我在函数placeMarker1/placeMaker2中使用var CurrentRows = 7时,它只允许我从底部开始到第二行,而不是继续向上。你认为我应该继续它的功能@daowen – acolisto 2014-11-22 03:35:22

+0

@acolisto - 那是因为逻辑不好。为什么你有一个循环,如果你永远不会超过1次迭代? (条件的两个分支(if/else)里面都有一个'return')。真正的分支只应该*递减currentRow,然后循环将继续做它的事情:if(table(currentRow)(移动)!=('。')){currentRow =(currentRow-1)}其他{...} – DaoWen 2014-11-22 03:46:51

+0

@acolisto - 您仍然需要'else'分支中的'return'。换句话说,一旦你放置这件作品,你就完成了,所以你回来了。 – DaoWen 2014-11-22 04:30:43