Skip to content

Commit 8a2198b

Browse files
Add solution for connect4
1 parent 4a1b1cf commit 8a2198b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/python/katas/py5kyu/connect4.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""Kata url: https://www.codewars.com/kata/586c0909c1923fdb89002031."""
2+
3+
4+
class Connect4:
5+
6+
def __init__(self):
7+
self.width = 6
8+
self.height = 7
9+
10+
self.board = [list("-")*self.width for _ in range(self.height)]
11+
self.placed = [0]*self.height
12+
self.turn = 1
13+
14+
self.visited = [[False]*self.width for _ in range(self.height)]
15+
self.won = False
16+
17+
@property
18+
def player(self):
19+
return "YR"[self.turn & 1]
20+
21+
def count_connected(self, x, y, dirs) -> int:
22+
if x < 0 or x >= self.width or y < 0 or y >= self.height:
23+
return 0
24+
25+
if self.visited[y][x] or self.board[y][x] != self.player:
26+
return 0
27+
28+
self.visited[y][x] = True
29+
count = 1 # this one!
30+
31+
for (dx, dy) in dirs:
32+
count += self.count_connected(x + dx, y + dy, dirs)
33+
34+
self.visited[y][x] = False
35+
return count
36+
37+
def play(self, col):
38+
if self.won:
39+
return "Game has finished!"
40+
x = self.placed[col]
41+
if x == self.width:
42+
return "Column full!"
43+
44+
self.turn ^= 1
45+
self.board[col][x] = self.player
46+
self.placed[col] += 1
47+
48+
for dirs in (
49+
((-1, 0), (1, 0)),
50+
((0, -1), (0, 1)),
51+
((-1, -1), (1, 1)),
52+
((1, -1), (-1, 1))
53+
):
54+
if self.count_connected(x, col, dirs) >= 4:
55+
self.won = True
56+
return f"Player {self.turn + 1} wins!"
57+
58+
return f"Player {self.turn + 1} has a turn"

0 commit comments

Comments
 (0)