Implement the logic for a Connect Four game. You are given a list of moves where each element is a column index (0-indexed) indicating where a player drops their disc. Player 1 and Player 2 alternate turns, with Player 1 going first.
Discs fall to the lowest available row in the chosen column. The board has 6 rows and 7 columns.
After processing the moves, determine the result: return 1 if Player 1 wins, 2 if Player 2 wins, or 0 if no player has won (draw or game still in progress). A player wins by connecting four of their discs consecutively in a horizontal, vertical, or diagonal direction. Once a player wins, all subsequent moves are ignored.
Function Signature
def connect_four_winner(moves: list[int]) -> int:
Rules
-
The entry at index
i
of
moves
(counting from 0) belongs to Player 1 when
i
is even and to Player 2 when
i
is odd. In other words, the first, third, fifth and later odd-numbered moves are Player 1's.
-
Cells are written as
(row, column)
, with row 0 at the top and row 5 at the bottom, so the first disc in a column lands in row 5.
-
Four or more consecutive discs of one player in a row, a column, or either diagonal is a win.
-
The game ends at the first winning move. Return that player even if later moves in the list would give the other player a line.
-
Return
0
when the moves run out with no line of four, whether or not the board is full.
Constraints
-
1 <= len(moves) <= 42
-
0 <= moves[i] <= 6
-
All moves are valid (the chosen column is not full at the time of the move).
-
The board is 6 rows by 7 columns.
Examples
Input: moves = [0,1,0,1,0,1,0]
Output: 1
Player 1 drops four discs into column 0, at rows 5, 4, 3 and 2, and connects four vertically on the seventh move. Player 2 has only three discs in column 1.
Input: moves = [0,1,1,2,2,3,2,3,3,5,3]
Output: 1
Player 1's discs at (5,0), (4,1), (3,2) and (2,3) form a diagonal, completed by the eleventh and last move, into column 3. Player 2 holds (5,1), (5,2) and (5,3) on the bottom row, but (5,4) stays empty, so that line never reaches four.
Input: moves = [6,0,6,1,5,2,6,3,6]
Output: 2
Player 2 fills (5,0) through (5,3) on the eighth move and wins. The ninth move would give Player 1 four in a row in column 6, but it comes after the win and is ignored.