hissroth
hissroth

Reputation: 251

Pieces doesn't stack after one loop on my connect4

I'm working on a connect4 and I have an issue on the piece slide down part. When I launch the game, the pieces stacked themself only once like that.

000000
000000
000000
000000
000000
PP0000
XX0000

But after that, it doesn't stack anymore. If the user chose to put a piece on the first or second row it won't stack the piece over the actual one. I tried to figure out where the issue was coming from but I don't see it and beeing new in python doesn't help a lot.

board = []

for x in range(0, 7):
    board.append(["O"] * 6)

def print_board(board):
    for row in board:
        print(" ".join(row))

def user_one(board):
    status = 0
    clm = 0
    first_x = int(input("Enter a Row: "))
    for i in board:
        while i == "0":
            clm += 1
        if board[clm - 1][first_x - 1] == "P":
            board[clm - 2][first_x - 1] = "X"
        else:
            board[clm - 1][first_x - 1] = "X"
    status = 1
    print_board(board)

def user_two(board):
    status = 0
    clm = 0
    second_p = int(input("Enter a Row: "))
    for i in board:
        while i == "0":
            clm += 1
        if board[clm - 1][second_p - 1] == "X":
            board[clm - 2][second_p - 1] = "P"
        else:
            board[clm - 1][second_p - 1] = "P"
    status = 2
    print_board(board)

def launch_game(board):
    while True:
        user_one(board)
        user_two(board)

launch_game(board)

Upvotes: 0

Views: 55

Answers (1)

skymon
skymon

Reputation: 870

I think overall was a bit of confusion between column and row. I took your code and modified it a little bit. So this should work:

board = []

for x in range(0, 7):
    board.append(["O"] * 6)

def print_board(board):
    for row in board:
        print(" ".join(row))

def user_one(board):
    clm = 0
    selected_column = int(input("Enter a column: "))

    for i in reversed(range(len(board))):
        if board[i][selected_column-1] == "O":
            board[i][selected_column-1] = "X"
            break

    print_board(board)

def user_two(board):
    clm = 0
    selected_column = int(input("Enter a column: "))
    for i in reversed(range(len(board))):
        if board[i][selected_column-1] == "O":
            board[i][selected_column-1] = "P"
            break
    print_board(board)

def launch_game(board):
    while True:
        user_one(board)
        user_two(board)

launch_game(board)

You can still improve on removing unused variables, names and refactoring the functions (so that you only have one for your piece slide down).

Upvotes: 1

Related Questions