forked from tscizzle/connect-four
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
68 lines (54 loc) · 1.97 KB
/
game.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import time
from boardHelpers import applyMoveToNewBoard, getWinner, isFull, boardStr
class Game(object):
def __init__(self, players, numCols=7, numRows=6):
self.numCols = numCols
self.numRows = numRows
self.board = [[None for _ in range(numRows)] for _ in range(numCols)]
self.numMovesSoFar = 0
self.players = players
self.players[0].symbol = 'X'
self.players[0].vsSymbol = 'O'
self.players[1].symbol = 'O'
self.players[1].vsSymbol = 'X'
def __str__(self):
return boardStr(self.board)
def isEnded(self):
return getWinner(self.board) or isFull(self.board)
def showWhoWon(self):
winningSymbol = getWinner(self.board)
print('%s wins!' % winningSymbol if winningSymbol else 'It was a tie.')
def nextPlayer(self):
return self.players[self.numMovesSoFar % len(self.players)]
def takeTurn(self, verbose=False, pause=False):
currentPlayer = self.nextPlayer()
maxCol = len(self.board) - 1
moveMade = False
while not moveMade:
try:
colIdx = currentPlayer.nextMove(self.board)
if not 0 <= colIdx <= maxCol:
raise MoveOutOfRange
column = self.board[colIdx]
if all(column):
raise ColumnIsFull
except MoveOutOfRange:
print('%s is not from 0 through %s.' % (colIdx, maxCol))
except ColumnIsFull:
print('Column %s is full.' % colIdx)
else:
moveMade = True
if not moveMade:
time.sleep(1)
symbol = currentPlayer.symbol
newBoard = applyMoveToNewBoard(self.board, colIdx, symbol)
self.board = newBoard
self.numMovesSoFar += 1
if verbose:
print(self)
if pause:
input()
class MoveOutOfRange(Exception):
pass
class ColumnIsFull(Exception):
pass