Connect Four is a two-player game played with discs of two colours (red and blue)

Connect Four is a two-player game played with discs of two colours (red and blue). The two players select a color, then take turns dropping their coloured discs from the top into a vertically suspended grid. The pieces fall straight down, occupying the next available space within the column. The object of the game is to get four of the same coloured discs next to each other vertically or horizontally or diagonally before one’s opponent can do so.In this computer version, the grid is represented by a two-dimensional array with 7 columns and 6 rows. The program prompts two players to drop a red or blue disk alternately. Whenever a disk is dropped, the program re-displays the board on the screen and determines the status of the game: • Win: if a player has four of his discs next to each other either vertically, horizontally or diagonally. • Draw: neither player has won and no more discs can be dropped because all cells in the grid are full. • Continue: neither player has won and the game can continue

The correct answer and explanation is:

Answer:

The following Python program simulates a two-player Connect Four game as described:

ROWS, COLS = 6, 7

def create_board():
    return [[" " for _ in range(COLS)] for _ in range(ROWS)]

def display_board(board):
    for row in board:
        print("|" + "|".join(row) + "|")
    print("-" * (2 * COLS + 1))

def drop_disk(board, col, color):
    for row in range(ROWS-1, -1, -1):
        if board[row][col] == " ":
            board[row][col] = color
            return True
    return False

def is_winner(board, color):
    # Check horizontal
    for r in range(ROWS):
        for c in range(COLS - 3):
            if board[r][c:c+4] == [color] * 4:
                return True

    # Check vertical
    for r in range(ROWS - 3):
        for c in range(COLS):
            if all(board[r+i][c] == color for i in range(4)):
                return True

    # Check diagonals (bottom-left to top-right)
    for r in range(ROWS - 3):
        for c in range(COLS - 3):
            if all(board[r+i][c+i] == color for i in range(4)):
                return True

    # Check diagonals (top-left to bottom-right)
    for r in range(3, ROWS):
        for c in range(COLS - 3):
            if all(board[r-i][c+i] == color for i in range(4)):
                return True

    return False

def is_draw(board):
    return all(cell != " " for row in board for cell in row)

def play_game():
    board = create_board()
    turn = 0
    while True:
        display_board(board)
        player = "Red" if turn % 2 == 0 else "Blue"
        color = "R" if turn % 2 == 0 else "B"
        col = int(input(f"{player}, choose a column (0-{COLS-1}): "))
        
        if col < 0 or col >= COLS or not drop_disk(board, col, color):
            print("Invalid move. Try again.")
            continue
        
        if is_winner(board, color):
            display_board(board)
            print(f"{player} wins!")
            break
        
        if is_draw(board):
            display_board(board)
            print("It's a draw!")
            break
        
        turn += 1

play_game()

Explanation :

This program creates a Connect Four game with a grid represented by a 6×7 two-dimensional array. Each cell in the array is initialized with a space (" ") to indicate it is empty. The display_board function visually represents the board on the console.

The drop_disk function allows a player to drop a disc into a specified column. It checks from the bottom-most row upwards to find the next available cell in the column. If the column is full, the move is rejected.

The is_winner function checks for four consecutive discs of the same color in horizontal, vertical, and diagonal directions using nested loops and list comprehensions. Diagonal checks are implemented separately for two directions: bottom-left to top-right and top-left to bottom-right.

The is_draw function determines if the board is full by checking that no cell is empty.

The main play_game function alternates turns between two players. Each turn, the player chooses a column to drop their disc. The board is updated and displayed after every move. The game then checks for a win condition or draw. If neither occurs, the game continues.

If a player wins, their color is displayed as the winner, and the game terminates. If the board becomes full with no winner, the game declares a draw. This ensures all game states—win, draw, and continue—are handled.

Scroll to Top