This code implements a playable text-based **Connect Four game** between...

July 5, 2025 at 07:30 PM

import time, random import string import sys ROWS, COLS = 8, 8 HUMAN, COMPUTER = 'O', 'X' TIME_LIMIT = 5 # seconds def create_board(): return [['-' for _ in range(COLS)] for _ in range(ROWS)] def print_board(board): print("\n " + ' '.join(str(i+1) for i in range(COLS))) for i, row in enumerate(board): print(f"{chr(ord('A')+i)} " + ' '.join(row)) print() def is_winner(board, player): # Check rows and columns only for row in board: for c in range(COLS - 3): if all(cell == player for cell in row[c:c+4]): return True for c in range(COLS): for r in range(ROWS - 3): if all(board[r+i][c] == player for i in range(4)): return True return False def is_full(board): return all(cell != '-' for row in board for cell in row) def get_legal_moves(board): return [(r, c) for r in range(ROWS) for c in range(COLS) if board[r][c] == '-'] def apply_move(board, move, player): r, c = move board[r][c] = player def undo_move(board, move): r, c = move board[r][c] = '-' def evaluate(board): # Simple heuristic: count open 2s and 3s def count_lines(player): score = 0 for row in board: for c in range(COLS - 3): line = row[c:c+4] if line.count(player) == 3 and line.count('-') == 1: score += 5 elif line.count(player) == 2 and line.count('-') == 2: score += 2 for c in range(COLS): for r in range(ROWS - 3): line = [board[r+i][c] for i in range(4)] if line.count(player) == 3 and line.count('-') == 1: score += 5 elif line.count(player) == 2 and line.count('-') == 2: score += 2 return score return count_lines(COMPUTER) - count_lines(HUMAN) def alpha_beta(board, depth, alpha, beta, maximizing_player, start_time): if time.time() - start_time > TIME_LIMIT - 0.1 or is_winner(board, HUMAN) or is_winner(board, COMPUTER) or depth == 0: return evaluate(board), None best_move = None moves = get_legal_moves(board) random.shuffle(moves) if maximizing_player: max_eval = -float('inf') for move in moves: apply_move(board, move, COMPUTER) eval_score, _ = alpha_beta(board, depth - 1, alpha, beta, False, start_time) undo_move(board, move) if eval_score > max_eval: max_eval = eval_score best_move = move alpha = max(alpha, eval_score) if beta <= alpha: break return max_eval, best_move else: min_eval = float('inf') for move in moves: apply_move(board, move, HUMAN) eval_score, _ = alpha_beta(board, depth - 1, alpha, beta, True, start_time) undo_move(board, move) if eval_score < min_eval: min_eval = eval_score best_move = move beta = min(beta, eval_score) if beta <= alpha: break return min_eval, best_move def parse_move(move_str): if len(move_str) < 2: return None row = ord(move_str[0].upper()) - ord('A') col = int(move_str[1]) - 1 if 0 <= row < ROWS and 0 <= col < COLS: return (row, col) return None def get_user_move(board): while True: move_str = input("Enter your move (e.g. e5): ") move = parse_move(move_str) if move and board[move[0]][move[1]] == '-': return move print("Invalid move. Try again.") def get_computer_move(board): start_time = time.time() depth = 1 best_move = None while time.time() - start_time < TIME_LIMIT - 0.1: eval_score, move = alpha_beta(board, depth, -float('inf'), float('inf'), True, start_time) if time.time() - start_time >= TIME_LIMIT: break if move is not None: best_move = move depth += 1 return best_move def main(): board = create_board() first = input("Do you want to go first? (y/n): ").lower() human_turn = first == 'y' print_board(board) while True: if human_turn: move = get_user_move(board) apply_move(board, move, HUMAN) else: print("Computer is thinking...") move = get_computer_move(board) if move: apply_move(board, move, COMPUTER) print(f"Computer moves to {chr(ord('A')+move[0])}{move[1]+1}") else: print("Computer cannot move.") print_board(board) if is_winner(board, HUMAN): print("You win!") break elif is_winner(board, COMPUTER): print("Computer wins!") break elif is_full(board): print("It's a tie!") break human_turn = not human_turn if __name__ == "__main__": main()

This code implements a playable text-based Connect Four game between a human player and the computer. Here's a breakdown of what the code does:

Core Functionality:

  1. Game Settings:

    • The game is played on an 8x8 grid (ROWS and COLS).
    • The players take turns with the human represented by 'O' (HUMAN) and the computer as 'X' (COMPUTER).
  2. Board Creation and Display:

    • The initial board is created using the create_board function, which is an 8x8 grid filled with the '-' character.
    • The print_board function displays the board on the terminal in a formatted way.
  3. Game Mechanics:

    • Players alternate making moves on the grid until someone wins or the grid is full (a tie).
    • Moves are validated and executed by the get_user_move and get_computer_move functions.
    • The computer uses the alpha-beta pruning algorithm within a time limit (TIME_LIMIT = 5 seconds) to decide its move.
  4. Win Condition:

    • The game checks for a winning condition using the is_winner function, which determines if a player has 4 consecutive symbols either:
      • Horizontally.
      • Vertically.
    • The game ends when either player wins or the board is full (tie).
  5. AI Logic:

    • The computer (AI) uses an alpha-beta pruning algorithm (alpha_beta function) to evaluate potential moves up to a certain depth, minimizing or maximizing scores based on the heuristic scoring system defined in the evaluate function.
    • The evaluate function assigns scores to specific board states based on potential "open lines" (rows/columns with 2-3 pieces and gaps), favoring the computer's chances while minimizing the human player's advantages.
  6. Inputs and Parsing:

    • Human moves are input as coordinates (e.g., e5 for row E and column 5) and validated with the parse_move function.
    • The computer selects its move programmatically.
  7. Turn Management:

    • The human can decide if they play first via input at the beginning (Do you want to go first? y/n), and the game alternates turns between players.
  8. End of Game:

    • The game states "You win!", "Computer wins!", or "It's a tie!" depending on whether the human, computer, or neither achieves a winning condition.

Example Run:

  1. The game starts by asking if the human wants to go first.
  2. Each turn:
    • The board is printed.
    • The human enters a move via terminal input.
    • The computer calculates its move using the AI logic if it's its turn.
  3. The loop continues until a win/draw condition is reached.

Decision-Making by the AI:

  • The computer calculates its best move by considering:
    • The number of 2s and 3s in open lines.
    • Avoiding moves that would create an advantage for the opponent.
    • Depth-limited search stops when the maximum depth or the time limit is reached.

Summary:

This is an interactive two-player Connect Four game where the human and computer take turns placing their moves on an 8x8 grid. The computer employs alpha-beta pruning to determine its moves under a strict time constraint. The game ends when a win condition is achieved by either player or when a tie occurs due to a full board.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node