Jordan
Jordan

Reputation: 15

How to check connect 4 for horizontal wins

*I am trying to find code to check if four or more 1's, or 2's are next to each other in the 2d list and then return my win function as true

Here is the code below:

# Connect Four

# 2d list
numRows = 6
numCols = 7
board = [[0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0], ]


def printBoard():
    for rows in range(0, numRows):
        for cols in range(0, numCols):
            print(board[rows][cols], end=' ')
        print(" ")


def fillIn(col, player):
    col = col - 1
    for rows in range(numRows - 1, -1, -1):
        if board[rows][col] == 0:
            print("Legal Move")
            board[rows][col] = player
            break


def win():
    if horizWin() or vertWin() or diagWin():
        return True
    return False


def horizWin():
    return False


def vertWin():
    return False


def diagWin():
    pass


player = 1

while not win():
    col = int(input("Please Select A Colum 1-7: "))

    fillIn(col, player)
    printBoard()
    if player == 1:
        player = 2
    else:
        player = 1

I was following a tutorial and it abruptly stopped. So any help would be greatly appreciated :)

Upvotes: 0

Views: 153

Answers (1)

user2261062
user2261062

Reputation:

You can do something like this.

I added some debug print statements so you understand better what is happening step by step. Dissable the prints when you are comfortable on how the code works

def horizWin():
    # loop over each row in the board
    for row in board:
        print (f"Current row: {row}")
        # take a window of size 4 and slide it over the row.
        # you need to iterate from 0 to len(row)-windowsize+1
        for i in range(len(row)-4+1):
            window = row[i:i+4]
            print(f"    Current window: {window}")
            # check if all elements in the row are 1s or 2s
            # all elements are the same if the number of elements 
            # equal to the first one is the size of the window.
            # you also need to check that this element is 1 or 2 
            if window.count(window[0]) == 4 and window[0] in (1,2):
                print(f"    This window has a winning position for player {window[0]}")
                return True
    print("No winning positions found in the board")
    return False
     
    

Upvotes: 1

Related Questions