Create a simple implementation of the "4-in-a-row" game, also known as Connect Four. This game involves two players who take turns dropping their colored discs from the top into a seven-column, six-row grid. The objective is to be the first to form a horizontal, vertical, or diagonal line of four of one's own discs.
from collections import deque
class ConnectFour:
def init(self):
self.board = [[' ' for _ in range(7)] for _ in range(6)]
self.current_player = 'X'
def print_board(self):
for row in self.board:
print('|'.join(row))
print('-' * 13)
def is_valid_move(self, col):
return self.board[0][col] == ' '
def make_move(self, col):
for row in reversed(self.board):
if row[col] == ' ':
row[col] = self.current_player
return True
return False
def switch_player(self):
self.current_player = 'O' if self.current_player == 'X' else 'X'
def check_winner(self):
# Check horizontal, vertical, and diagonal lines for a winner
for row in range(6):
for col in range(7):
if self.board[row][col] == ' ':
continue
# Check horizontal (left to right)
if col + 3 < 7 and all(self.board[row][col + i] == self.board[row][col] for i in range(4)):
return self.board[row][col]
# Check horizontal (right to left)
if col - 3 >= 0 and all(self.board[row][col - i] == self.board[row][col] for i in range(4)):
return self.board[row][col]
# Check vertical
if row + 3 < 6 and all(self.board[row + i][col] == self.board[row][col] for i in range(4)):
return self.board[row][col]
# Check diagonal (left to right)
if row + 3 < 6 and col + 3 < 7 and all(self.board[row + i][col + i] == self.board[row][col] for i in range(4)):
return self.board[row][col]
# Check diagonal (right to left)
if row + 3 < 6 and col - 3 >= 0 and all(self.board[row + i][col - i] == self.board[row][col] for i in range(4)):
return self.board[row][col]
return None
def is_full(self):
return all(self.board[0][col] != ' ' for col in range(7))
def play_with_moves(self, moves):
print("Welcome to Connect Four!")
self.print_board()
for col in moves:
if col < 0 or col > 6 or not self.is_valid_move(col):
print(f"Invalid move: {col}. Try again.")
continue
self.make_move(col)
self.print_board()
winner = self.check_winner()
if winner:
print(f"Player {winner} wins!")
return
if self.is_full():
print("The game is a draw!")
return
self.switch_player()
print("No winner or draw. Game ended.")moves = [0, 0, 1, 1, 2, 2, 3] # A sequence of moves leading to a win for player 'X'
game = ConnectFour()
game.play_with_moves(moves)