import sys

def create_board():
    # 6 rows, 7 columns
    return [[' ' for _ in range(7)] for _ in range(6)]

def print_board(board):
    print("\n  1 2 3 4 5 6 7")
    print(" -----------------")
    for row in board:
        print("|" + "|".join(row) + "|")
    print(" -----------------")

def is_valid_move(board, col):
    # col is 0-indexed internally
    return 0 <= col < 7 and board[0][col] == ' '

def drop_piece(board, col, piece):
    # Gravity: find the lowest empty row
    for row in range(5, -1, -1):
        if board[row][col] == ' ':
            board[row][col] = piece
            return row, col

def check_winner(board, row, col, piece):
    # Directions to check: (row_delta, col_delta)
    directions = [
        (0, 1),  # Horizontal
        (1, 0),  # Vertical
        (1, 1),  # Diagonal \
        (1, -1)  # Diagonal /
    ]
    
    for dr, dc in directions:
        count = 1
        # Check in positive direction
        r, c = row + dr, col + dc
        while 0 <= r < 6 and 0 <= c < 7 and board[r][c] == piece:
            count += 1
            r += dr
            c += dc
        # Check in negative direction
        r, c = row - dr, col - dc
        while 0 <= r < 6 and 0 <= c < 7 and board[r][c] == piece:
            count += 1
            r -= dr
            c -= dc
        if count >= 4:
            return True
    return False

def is_board_full(board):
    return all(board[0][col] != ' ' for col in range(7))

def main():
    board = create_board()
    players = [('Player 1', 'R'), ('Player 2', 'Y')]
    turn = 0

    print("Welcome to Connect Four!")
    
    while True:
        print_board(board)
        name, piece = players[turn % 2]
        print(f"{name}'s turn ({piece})")
        
        try:
            choice = int(input("Choose column (1-7): ")) - 1
            if not is_valid_move(board, choice):
                print("Invalid move! Column is full or out of range.")
                continue
        except ValueError:
            print("Please enter a valid number.")
            continue

        row, col = drop_piece(board, choice, piece)
        
        if check_winner(board, row, col, piece):
            print_board(board)
            print(f"Game Over! {name} wins!")
            sys.exit()
            
        if is_board_full(board):
            print_board(board)
            print("Game Over! It's a draw!")
            sys.exit()
            
        turn += 1

if __name__ == "__main__":
    main()
