1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
class Connect4:
def __init__(self):
self.rows = 6
self.cols = 7
self.grid = [['-' for _ in range(self.cols)] for _ in range(self.rows)]
self.current_player = "R" # Red starts the game
def drop_disc(self, col):
# Check if the column is valid
if col < 0 or col >= self.cols or self.grid[0][col] != '-':
return False # Invalid move
# Drop disc to the lowest empty position in the column
for row in range(self.rows - 1, -1, -1):
if self.grid[row][col] == '-':
self.grid[row][col] = self.current_player
return (row, col) # Return the position of the disc
def check_win(self, row, col):
# Check horizontal, vertical, and diagonal lines
def count_consecutive(x, y, dx, dy):
count = 0
piece = self.grid[x][y]
while 0 <= x < self.rows and 0 <= y < self.cols and self.grid[x][y] == piece:
count += 1
x += dx
y += dy
return count
for dx, dy in [(0, 1), (1, 0), (1, 1), (1, -1)]:
# Check both directions
total = count_consecutive(row, col, dx, dy) + count_consecutive(row, col, -dx, -dy) - 1
if total >= 4:
return True
return False
def play(self, col):
position = self.drop_disc(col)
if not position:
return "Invalid move. Try again."
row, col = position
if self.check_win(row, col):
return f"Player {self.current_player} wins!"
# Switch player
self.current_player = "B" if self.current_player == "R" else "R"
return "Continue"
# Simulation
game = Connect4()
print(game.play(3)) # Drop disc in column 3
print(game.play(3)) # Drop disc in column 3
|