在Scala中连接四个游戏

时间:2014-11-22 03:16:38

标签: arrays scala

我试图在scala中创建一个连接四游戏。目前我打印出棋盘并要求玩家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
}

1 个答案:

答案 0 :(得分:0)

你的全球状态让你烦恼:var currentRow = 7

我不建议在所有列中跟踪全局“currentRow”,而是建议使用以下两种方法之一:

  1. currentRows数组中的每列保留单独的“currentRow”。
  2. 每次放置一个片段以查找最低的空插槽时,只需遍历列。
  3. 实际上,看起来你最初是在做第二个建议,但是你注释掉了你的本地currentRow变量并且声明了一个全局(实例级)变量。

寻找你感兴趣的贴纸↓↓↓
豫ICP备18024241号-1