Airbnb phone screening
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-07-11Added By Anonymous
Source: Link
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'
1def print_board(self):
2 for row in self.board:
3 print('|'.join(row))
4 print('-' * 13)
5
6def is_valid_move(self, col):
7 return self.board[0][col] == ' '
8
9def make_move(self, col):
10 for row in reversed(self.board):
11 if row[col] == ' ':
12 row[col] = self.current_player
13 return True
14 return False
15
16def switch_player(self):
17 self.current_player = 'O' if self.current_player == 'X' else 'X'
18
19def check_winner(self):
20 # Check horizontal, vertical, and diagonal lines for a winner
21 for row in range(6):
22 for col in range(7):
23 if self.board[row][col] == ' ':
24 continue
25
26 # Check horizontal (left to right)
27 if col + 3 < 7 and all(self.board[row][col + i] == self.board[row][col] for i in range(4)):
28 return self.board[row][col]
29
30 # Check horizontal (right to left)
31 if col - 3 >= 0 and all(self.board[row][col - i] == self.board[row][col] for i in range(4)):
32 return self.board[row][col]
33
34 # Check vertical
35 if row + 3 < 6 and all(self.board[row + i][col] == self.board[row][col] for i in range(4)):
36 return self.board[row][col]
37
38 # Check diagonal (left to right)
39 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)):
40 return self.board[row][col]
41
42 # Check diagonal (right to left)
43 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)):
44 return self.board[row][col]
45 return None
46
47def is_full(self):
48 return all(self.board[0][col] != ' ' for col in range(7))
49
50def play_with_moves(self, moves):
51 print("Welcome to Connect Four!")
52 self.print_board()
53 for col in moves:
54 if col < 0 or col > 6 or not self.is_valid_move(col):
55 print(f"Invalid move: {col}. Try again.")
56 continue
57
58 self.make_move(col)
59 self.print_board()
60
61 winner = self.check_winner()
62 if winner:
63 print(f"Player {winner} wins!")
64 return
65 if self.is_full():
66 print("The game is a draw!")
67 return
68
69 self.switch_player()
70
71 print("No winner or draw. Game ended.")Example usage
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)