Connect Four game in Scala

2019-09-13 05:55发布

问题:

I'm trying to make a connect four game in scala. Currently i have the board print out and ask player 1 for a move, once player 1 choses a number a board prints out with an X in the column where player 1 chose. then player 2 picks a number. My problem is that once i pick a number that player's letter fills the whole column and you ant build on top of that.

heres an example of what happens

. 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:

Your global state is messing you up: var currentRow = 7

Instead of trying to keep track of a global "currentRow" across all columns, I'd recommend one of two things:

  1. Keep a separate "currentRow" for each column in a currentRows array.
  2. Just iterate through the column each time you place a piece to find the lowest empty slot.

Actually, it looks like you were originally doing the second suggestion, but you commented out your local currentRow variables and declared a global (instance-level) one instead.



标签: arrays scala