File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
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"
You can’t perform that action at this time.
0 commit comments