Connect Four game engine with win detection
Implement a two-player game of Connect Four.
The board has rows rows and cols columns (default 6 x 7). Players "A" and "B" alternate turns, and "A" moves first. On a turn, a player picks a column and drops a disc into it. The disc falls to the lowest empty cell in that column. A player wins by getting k (default 4) of their discs in an unbroken line: horizontal, vertical, or along either diagonal. If every cell is filled and nobody has won, the game is a draw.
Implement the class:
-
ConnectFour(rows: int = 6, cols: int = 7, k: int = 4)creates an empty board. -
move(player: str, column: int) -> strdropsplayer's disc intocolumn(0-indexed, left to right) and returns the game state after the move:-
"A"or"B"if that move wins the game, -
"draw"if the board is now full with no winner, -
"in_progress"otherwise.
-
move must raise ValueError, and leave the game unchanged, when:
- the game has already ended,
- it is not
player's turn, -
columnis outside0 .. cols - 1, or - the column is already full.
Aim for each move to take time proportional to k, not to the board size.
Example 1
g = ConnectFour()
g.move("A", 2) # "in_progress"
g.move("B", 2) # "in_progress" (B's disc lands on top of A's)
g.move("A", 3) # "in_progress"
g.move("B", 3) # "in_progress"
g.move("A", 5) # "in_progress"
g.move("B", 5) # "in_progress"
g.move("A", 4) # "A" -> bottom row now holds A in columns 2, 3, 4, 5
g.move("B", 0) # raises ValueError (game is over)
Example 2
g = ConnectFour(rows=2, cols=2, k=3)
g.move("A", 0) # "in_progress"
g.move("B", 1) # "in_progress"
g.move("A", 1) # "in_progress"
g.move("B", 0) # "draw" (no line of 3 fits on a 2 x 2 board)
Constraints
-
1 <= rows, cols <= 100,1 <= k <= max(rows, cols) - At most
rows * colssuccessful calls tomove.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
