Connect Four Project Python

WHAT TO KNOW - Sep 7 - - Dev Community

<!DOCTYPE html>



Connect Four Project: A Python Tutorial

<br> body {<br> font-family: Arial, sans-serif;<br> margin: 0;<br> padding: 20px;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code>h1, h2, h3 { color: #333; } pre { background-color: #f2f2f2; padding: 10px; font-family: "Courier New", Courier, monospace; overflow-x: auto; } img { max-width: 100%; height: auto; display: block; margin: 20px auto; } </code></pre></div> <p>



Connect Four Project: A Python Tutorial



Connect Four is a classic two-player board game where the objective is to get four of your checkers in a row, column, or diagonal. This project will guide you through the process of creating a Connect Four game using Python, exploring fundamental programming concepts along the way.


  1. Project Setup and Game Board Representation

1.1 Project Setup

Start by creating a new Python file (e.g., connect_four.py). This will be our primary code file for developing the game.

1.2 Representing the Game Board

We need a way to store and manage the game board. One approach is to use a list of lists, where each inner list represents a column of the board. We'll use the number 0 to represent an empty cell, 1 for Player 1's checker, and 2 for Player 2's checker.


# Initialize an empty 6x7 board
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],
]

  • Game Logic

    2.1 Player Turn and Input

    We'll need functions to handle player turns and validate user input:

    
    def player_turn(player):
    """Gets and validates player input."""
    while True:
    try:
      column = int(input(f"Player {player}, choose a column (1-7): ")) - 1
      if 0 <= column < 7 and board[0][column] == 0:  # Check valid column
        return column
      else:
        print("Invalid input. Choose an empty column.")
    except ValueError:
      print("Invalid input. Please enter a number.")
  • def drop_checker(column, player):
    """Drops a checker in the chosen column."""
    for row in range(5, -1, -1):
    if board[row][column] == 0:
    board[row][column] = player
    break


    The player_turn function prompts the current player to choose a column, validates the input (checking if it's a valid column and if it's empty), and returns the chosen column index. The drop_checker function takes the column and player's number as arguments, finds the lowest available row in the column, and places the checker there.



    2.2 Checking for a Win



    We need a function to determine if a player has won the game after each turn. This involves checking all possible winning combinations (horizontal, vertical, and diagonal):



    def check_win(player):
    """Checks if the current player has won."""
    # Check horizontal
    for row in range(6):
    for col in range(4):
    if board[row][col] == player and board[row][col + 1] == player and board[row][col + 2] == player and board[row][col + 3] == player:
    return True

    # Check vertical
    for row in range(3):
    for col in range(7):
    if board[row][col] == player and board[row + 1][col] == player and board[row + 2][col] == player and board[row + 3][col] == player:
    return True

    # Check diagonals (top-left to bottom-right)
    for row in range(3):
    for col in range(4):
    if board[row][col] == player and board[row + 1][col + 1] == player and board[row + 2][col + 2] == player and board[row + 3][col + 3] == player:
    return True

    # Check diagonals (bottom-left to top-right)
    for row in range(3, 6):
    for col in range(4):
    if board[row][col] == player and board[row - 1][col + 1] == player and board[row - 2][col + 2] == player and board[row - 3][col + 3] == player:
    return True

    return False



    The check_win function iterates through the board, checking each possible winning combination. If it finds four consecutive checkers belonging to the current player, it returns True; otherwise, it returns False.



    2.3 Checking for a Draw



    If all cells are filled without a win, the game is a draw. We need a function to check for this:



    def check_draw():
    """Checks if the board is full (draw)."""
    for row in board:
    if 0 in row:
    return False
    return True


    The check_draw function checks if any cell on the board is empty. If all cells are filled, it returns True, indicating a draw. Otherwise, it returns False.


    1. Game Loop and Display

    3.1 Game Loop

    The game loop controls the flow of the game, handling player turns, checking for a win or a draw, and displaying the board.


    def print_board():
    """Prints the current state of the board."""
    for row in board:
    print("|".join(str(cell) for cell in row))
    print()

    Main game loop

    current_player = 1
    while True:
    print_board()
    column = player_turn(current_player)
    drop_checker(column, current_player)

    if check_win(current_player):
    print_board()
    print(f"Player {current_player} wins!")
    break
    elif check_draw():
    print_board()
    print("It's a draw!")
    break

    current_player = 3 - current_player # Switch players



    The print_board function displays the board on the console. The game loop iterates until a win or a draw occurs. It handles player turns, checks for win conditions, and switches players between turns.


    1. Adding Visuals (Optional)

    To enhance the game's presentation, you can add visual elements using a library like pygame. This allows for a more engaging and interactive experience.


    import pygame

    Initialize Pygame

    pygame.init()

    Set screen dimensions

    screen_width = 700
    screen_height = 600
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Connect Four")

    Define colors

    black = (0, 0, 0)
    red = (255, 0, 0)
    yellow = (255, 255, 0)

    Define checker radius and spacing

    checker_radius = 40
    checker_spacing = 80

    Function to draw the board

    def draw_board():
    screen.fill(black)
    for row in range(6):
    for col in range(7):
    x = col * checker_spacing + checker_spacing // 2
    y = row * checker_spacing + checker_spacing // 2
    if board[row][col] == 1:
    pygame.draw.circle(screen, red, (x, y), checker_radius)
    elif board[row][col] == 2:
    pygame.draw.circle(screen, yellow, (x, y), checker_radius)

    Main game loop

    current_player = 1
    running = True
    while running:
    for event in pygame.event.get():
    if event.type == pygame.QUIT:
    running = False
    if event.type == pygame.MOUSEBUTTONDOWN:
    # Get mouse click coordinates
    x, y = pygame.mouse.get_pos()
    # Calculate column clicked
    column = x // checker_spacing
    # Drop checker if valid
    if 0 <= column < 7 and board[0][column] == 0:
    drop_checker(column, current_player)
    if check_win(current_player):
    print(f"Player {current_player} wins!")
    running = False
    elif check_draw():
    print("It's a draw!")
    running = False
    current_player = 3 - current_player # Switch players

    draw_board()
    pygame.display.flip()

    pygame.quit()



    The code above initializes Pygame, sets up the screen, defines colors, and creates functions for drawing the board and handling mouse clicks. The game loop continuously updates the display, checking for events, and responding to player input. This example uses a simple graphical representation of the board and checkers. You can customize the appearance and add more visual elements to enhance the game's aesthetics.


    1. Conclusion

    Developing a Connect Four game in Python involves understanding fundamental programming concepts like data structures, functions, conditional statements, and loops. This project demonstrates a basic implementation of the game using lists to represent the board, functions for player turns, win checks, and a game loop to control the flow. You can expand upon this foundation by adding features like a graphical user interface, different game modes, or AI opponents. The key takeaway is to break down complex tasks into smaller, manageable steps, using modular functions and clear code organization for better readability and maintainability.

    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    Terabox Video Player