-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoe.py
199 lines (149 loc) · 4.92 KB
/
tictactoe.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import random
from collections import ChainMap
from itertools import cycle
class GameOver(Exception):
winner = None
class Victory(GameOver):
def __init__(self, winner):
self.winner = winner
super().__init__('Winner: {}'.format(winner))
class TicTacToeBoard:
def __init__(self, board):
self.board = board
@classmethod
def new(cls, size):
locs = {(row, col) for row in range(size) for col in range(size)}
board = ChainMap({loc: None for loc in locs})
return cls(board)
@classmethod
def from_str(cls, board_str):
board = {}
for row, line in enumerate(board_str.split()):
for col, player in enumerate(line):
board[(row, col)] = player if player != '.' else None
return cls(ChainMap(board))
def size(self):
return int(len(self.board) ** 0.5)
def __str__(self):
size = self.size()
stuff = []
for row in range(size):
for col in range(size):
stuff.append(self.board[(row, col)] or '.')
stuff.append('\n')
return ''.join(stuff)
def move(self, loc, label):
try:
data = self.board[loc]
except KeyError:
raise ValueError('invalid location: {}'.format(loc))
if data is not None:
raise ValueError('{} already contains {}'.format(loc, data))
return self.__class__(self.board.new_child({loc: label}))
def game_over(self):
return self.full() or self.victory()
def full(self):
return all(data is not None for data in self.board.values())
def victory(self):
size = self.size()
checks = [
{(r, c) for (r, c) in self.board.keys() if r == c},
{(r, c) for (r, c) in self.board.keys() if r == size - 1 - c},
]
for i in range(size):
checks.append({(r, c) for (r, c) in self.board.keys() if r == i})
checks.append({(r, c) for (r, c) in self.board.keys() if c == i})
for locs in checks:
values = {self.board[loc] for loc in locs}
if len(values) == 1 and values != {None}:
return True
return False
class TicTacToe:
def __init__(self, board, players):
self.board = board
self.players = players
self.turns = cycle(players)
self.active_player = next(self.turns)
@classmethod
def new(cls, size, players):
return cls(TicTacToeBoard.new(size), players)
def move(self):
loc = self.active_player.get_move(self.board)
label = self.active_player.label
self.board = self.board.move(loc, label)
if self.board.game_over():
if self.board.victory():
raise Victory(self.active_player)
else:
raise GameOver
self.active_player = next(self.turns)
def play(self):
print(self.board)
while True:
try:
self.move()
except Victory as victory:
return victory.winner
except GameOver:
return None
finally:
print(self.board)
class Player:
def __init__(self, label):
self.label = label
def __str__(self):
return self.label
def get_move(self, board):
raise NotImplementedError
class RandomPlayer(Player):
def get_move(self, board):
locs = list(board.board.keys())
random.shuffle(locs)
for loc in locs:
try:
board.move(loc, self.label)
except ValueError:
pass
else:
return loc
raise ValueError('No valid move found')
def play():
x = RandomPlayer('x')
o = RandomPlayer('o')
game = TicTacToe.new(3, [x, o])
winner = game.play()
print('Winner:', winner)
# Tests: run with py.test or nosetests
def assert_equal(a, b):
assert a == b
def test_tictactoeboard():
board_str = """\
xox
oxo
ox.
"""
board = TicTacToeBoard.from_str(board_str)
yield assert_equal, str(board).split(), board_str.split()
full_str = """\
xox
oxo
oxx
"""
full_board = TicTacToeBoard.from_str(full_str)
moved_board = board.move((2, 2), 'x')
yield assert_equal, str(moved_board), str(full_board)
problem = """\
o..
xox
.x.
"""
problem_board = TicTacToeBoard.from_str(problem)
yield assert_equal, problem_board.full(), False
yield assert_equal, problem_board.victory(), False
yield assert_equal, problem_board.game_over(), False
yield assert_equal, full_board.full(), True
yield assert_equal, board.full(), False
yield assert_equal, full_board.victory(), True
yield assert_equal, board.victory(), False
yield assert_equal, full_board.game_over(), True
yield assert_equal, board.game_over(), False