Trouble with python connect 4 column full

347 Views Asked by At

I'm making a connect 4 game on python but I'm running into an issue with my play function

def play(grid,column,checker):
    
    counter = 0
    for x in grid[0]:
        counter += 1
    if counter > column-1 :
        for row in reversed(grid):
            while row[column-1] == "empty":
                row[column-1] = checker
                print(True)
                return True
            else :
                return False 
            
            

    else:
        print(False)
        return False     

I'm trying to figure out how to make it return false if the column is full but I can't seem to get it to work. Grid is a list of lists provided from a previous function. Any advice would be greatly appreciated!

1

There are 1 best solutions below

4
David Moreau On BEST ANSWER

You don't want else return False. You want to return false if the for loop fails to find a an open slot

Try this:

Edit: I changed code to be a solution I tested

def play(grid, column, checker):
    try:    
        counter = 0
        for x in grid[0]:
            counter += 1
        if counter > column-1 :
            for row in reversed(grid):
                if row[column-1] == "empty":
                    row[column-1] = checker
                    return True

            return False
        else:
            return False  
    finally:
        print(grid)

grid = [['empty']*7 for _ in range(7)]
column = 3
assert play(grid, column, 'O') == True
assert play(grid, column, 'X') == True
assert play(grid, column, 'O') == True
assert play(grid, column, 'X') == True
assert play(grid, column, 'O') == True
assert play(grid, column, 'X') == True
assert play(grid, column, 'O') == True
assert play(grid, column, 'X') == False

Disclaimer: I did this with minimal changes and only to resolve the return False problem. I did not try to validate other logic. Also, you should change the while to an if statement as you aren't looping.