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