Key OOP Concepts
1. Classes and Objects
• A class is a blueprint (like a plan for a game piece).
• An object is an instance of that class (like one red coin or one yellow coin).
2. Encapsulation
• Bundling data and methods inside objects so they manage themselves.
3. Inheritance
• One class can “inherit” from another, reusing behavior and extending it.
4. Polymorphism
• Different objects can respond to the same method in different ways.
Applying OOP to Connect 4
// Class for each player class Player { constructor(name, color, coins = 21, time = 300) { this.name = name; this.color = color; this.coins = coins; this.time = time; }
useCoin() { if (this.coins > 0) { this.coins–; return true; } return false; } }
// Class for the board class Board { constructor(rows = 6, cols = 7) { this.rows = rows; this.cols = cols; this.grid = Array.from({ length: rows }, () => Array(cols).fill(null)); }
dropCoin(col, player) { for (let r = this.rows - 1; r >= 0; r–) { if (!this.grid[r][col]) { this.grid[r][col] = player.color; return { row: r, col }; } } return null; // column full } }
// Class for the game controller class Game { constructor(player1, player2, board) { this.players = [player1, player2]; this.board = board; this.current = 0; // index of active player }
get activePlayer() { return this.players[this.current]; }
switchTurn() { this.current = 1 - this.current; }
playMove(col) { const player = this.activePlayer; if (!player.useCoin()) return “No coins left!”; const move = this.board.dropCoin(col, player); if (!move) return “Column full!”; // Check win conditions here… this.switchTurn(); } }
Why OOP Helps
• Organization → Instead of one huge script, responsibilities are split:
• Player manages coins and time.
• Board manages slots and win-checking.
• Game manages turns and rules.
• Reusability → Want a different board size (e.g., 8x8)? Just change the Board constructor.