Connect 4 is a game where opponents take turns dropping red or black discs into a 7 x 6 vertically suspended grid.

By | June 22, 2023

The game ends either when one player creates a line of four consecutive discs of their color (horizontally, vertically, or diagonally), or when there are no more spots left in the grid.

Design and implement Connect 4.

To design and implement Connect 4, we can follow these steps:

  1. Define the game board:
    • Create a 2D array with 7 columns and 6 rows to represent the game board.
    • Each cell in the array can have three possible values: empty, red, or black.
    • Initialize all cells to the empty value.
  2. Implement the game logic:
    • Create a Connect4 class to handle the game.
    • Include member variables to track the current player, the game board, and the game status (ongoing, win, or draw).
    • Implement methods to:
      • Start a new game.
      • Make a move by dropping a disc into a column.
      • Check for a win condition.
      • Check for a draw condition.
      • Switch the current player.
      • Print the game board.
      • Run the game loop until it ends.
  3. Implement the move logic:
    • When a player makes a move, find the lowest available row in the selected column and place their disc there.
    • Update the game board with the player’s disc.
    • Check for a win condition after each move.
    • If a win condition is met, declare the current player as the winner and end the game.
    • If no win condition is met and the game board is full, declare the game as a draw and end the game.

Here’s an example implementation of Connect 4 in Python:

class Connect4:
    def __init__(self):
        self.board = [[' ' for _ in range(7)] for _ in range(6)]
        self.current_player = 'R'  # 'R' for red, 'B' for black
        self.status = 'ongoing'
    def start_game(self):
        self.board = [[' ' for _ in range(7)] for _ in range(6)]
        self.current_player = 'R'
        self.status = 'ongoing'
    def make_move(self, column):
        if self.status != 'ongoing':
            print("Game over. Please start a new game.")
            return
        if column < 0 or column >= 7:
            print("Invalid column. Please choose a column between 0 and 6.")
            return
        for row in range(5, -1, -1):
            if self.board[row][column] == ' ':
                self.board[row][column] = self.current_player
                break
        else:
            print("Column is full. Please choose another column.")
            return
        if self.check_win_condition():
            self.status = 'win'
        elif self.check_draw_condition():
            self.status = 'draw'
        else:
            self.switch_player()
    def check_win_condition(self):
        # Check horizontal lines
        for row in range(6):
            for col in range(4):
                if (
                    self.board[row][col] == self.current_player and
                    self.board[row][col+1] == self.current_player and
                    self.board[row][col+2] == self.current_player and
                    self.board[row][col+3] == self.current_player
                ):
                    return True
        # Check vertical lines
        for row in range(3):
            for col in range(7):
                if (
                    self.board[row][col] == self.current_player and
                    self.board[row+1][col] == self.current_player and
                    self.board[row+2][col] == self.current_player and
                    self.board[row+3][col] == self.current_player
                ):
                    return True
        # Check diagonal lines (top-left to bottom-right)
        for row in range(3):
            for col in range(4):
                if (
                    self.board[row][col] == self.current_player and
                    self.board[row+1][col+1] == self.current_player and
                    self.board[row+2][col+2] == self.current_player and
                    self.board[row+3][col+3] == self.current_player
                ):
                    return True
        # Check diagonal lines (bottom-left to top-right)
        for row in range(3, 6):
            for col in range(4):
                if (
                    self.board[row][col] == self.current_player and
                    self.board[row-1][col+1] == self.current_player and
                    self.board[row-2][col+2] == self.current_player and
                    self.board[row-3][col+3] == self.current_player
                ):
                    return True
        return False
    def check_draw_condition(self):
        for row in range(6):
            for col in range(7):
                if self.board[row][col] == ' ':
                    return False
        return True
    def switch_player(self):
        if self.current_player == 'R':
            self.current_player = 'B'
        else:
            self.current_player = 'R'
    def print_board(self):
        print("\n  0 1 2 3 4 5 6")
        print("---------------")
        for row in range(6):
            print('|', end='')
            for col in range(7):
                print(self.board[row][col] + '|', end='')
            print("\n---------------")
    def play(self):
        print("Welcome to Connect 4!")
        self.print_board()
        while self.status == 'ongoing':
            column = int(input(f"\n{self.current_player}, enter the column (0-6) to make a move: "))
            self.make_move(column)
            self.print_board()
        if self.status == 'win':
            print(f"\n{self.current_player} wins!")
        elif self.status == 'draw':
            print("\nThe game is a draw.")
        print("\nThanks for playing!")
# Example usage
game = Connect4()
game.play()

You can run the above Python code to play Connect 4 in the console. The game starts by calling the play() method of the Connect4 class. Players take turns entering the column number (0-6) to drop their disc. The game continues until there is a win or a draw. After the game ends, players can start a new game by calling the start_game() method.

Asked by SalesForce

Leave a Reply

Your email address will not be published. Required fields are marked *