Search code examples
pythonpython-3.x

How to return false if a list column is full


I'm making a Connect Four game in 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. The grid is a list of lists provided from a previous function.


Solution

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

    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.