A Connect Four game. Play moves with :meth:`play`. Get past moves with :attr:`moves`. Check for a victory with :attr:`winner`.
| 4 | |
| 5 | |
| 6 | class Connect4: |
| 7 | """ |
| 8 | A Connect Four game. |
| 9 | |
| 10 | Play moves with :meth:`play`. |
| 11 | |
| 12 | Get past moves with :attr:`moves`. |
| 13 | |
| 14 | Check for a victory with :attr:`winner`. |
| 15 | |
| 16 | """ |
| 17 | |
| 18 | def __init__(self): |
| 19 | self.moves = [] |
| 20 | self.top = [0 for _ in range(7)] |
| 21 | self.winner = None |
| 22 | |
| 23 | @property |
| 24 | def last_player(self): |
| 25 | """ |
| 26 | Player who played the last move. |
| 27 | |
| 28 | """ |
| 29 | return PLAYER1 if len(self.moves) % 2 else PLAYER2 |
| 30 | |
| 31 | @property |
| 32 | def last_player_won(self): |
| 33 | """ |
| 34 | Whether the last move is winning. |
| 35 | |
| 36 | """ |
| 37 | b = sum(1 << (8 * column + row) for _, column, row in self.moves[::-2]) |
| 38 | return any(b & b >> v & b >> 2 * v & b >> 3 * v for v in [1, 7, 8, 9]) |
| 39 | |
| 40 | def play(self, player, column): |
| 41 | """ |
| 42 | Play a move in a column. |
| 43 | |
| 44 | Returns the row where the checker lands. |
| 45 | |
| 46 | Raises :exc:`ValueError` if the move is illegal. |
| 47 | |
| 48 | """ |
| 49 | if player == self.last_player: |
| 50 | raise ValueError("It isn't your turn.") |
| 51 | |
| 52 | row = self.top[column] |
| 53 | if row == 6: |
| 54 | raise ValueError("This slot is full.") |
| 55 | |
| 56 | self.moves.append((player, column, row)) |
| 57 | self.top[column] += 1 |
| 58 | |
| 59 | if self.winner is None and self.last_player_won: |
| 60 | self.winner = self.last_player |
| 61 | |
| 62 | return row |
no outgoing calls
no test coverage detected
searching dependent graphs…