-
Notifications
You must be signed in to change notification settings - Fork 0
/
reversi.py
executable file
·302 lines (273 loc) · 11.6 KB
/
reversi.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python
import copy
from itertools import cycle
import os
from random import shuffle
import sys
import time
BLACK=" ⚫️ "
WHITE=" ⚪️ "
EMPTY=" "
BACK_GREEN = "\x1b[0;30;42m" # style=0=normal, front=30=black, back=42=green
RESET_COLOR = "\x1b[0m"
DANGEROUS_POSITIONS = [
(0, 1), (0, 6),
(1, 0), (1, 1), (1, 6), (1, 7),
(6, 0), (6, 1), (6, 6), (6, 7),
(7, 1), (7, 6)
]
CORNER_POSITIONS = [(0, 0), (7, 0), (7, 7), (0, 7)]
class Board():
def __init__(self):
self.board = [[EMPTY for i in range(8)] for i in range(8)]
self.board[3][4] = WHITE
self.board[3][3] = BLACK
self.board[4][3] = WHITE
self.board[4][4] = BLACK
def __str__(self):
b = self.board
return f""" 1 2 3 4 5 6 7 8
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
A {BACK_GREEN}│{b[0][0]}│{b[0][1]}│{b[0][2]}│{b[0][3]}│{b[0][4]}│{b[0][5]}│{b[0][6]}│{b[0][7]}│{RESET_COLOR} A
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
B {BACK_GREEN}│{b[1][0]}│{b[1][1]}│{b[1][2]}│{b[1][3]}│{b[1][4]}│{b[1][5]}│{b[1][6]}│{b[1][7]}│{RESET_COLOR} B
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
C {BACK_GREEN}│{b[2][0]}│{b[2][1]}│{b[2][2]}│{b[2][3]}│{b[2][4]}│{b[2][5]}│{b[2][6]}│{b[2][7]}│{RESET_COLOR} C
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
D {BACK_GREEN}│{b[3][0]}│{b[3][1]}│{b[3][2]}│{b[3][3]}│{b[3][4]}│{b[3][5]}│{b[3][6]}│{b[3][7]}│{RESET_COLOR} D
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
E {BACK_GREEN}│{b[4][0]}│{b[4][1]}│{b[4][2]}│{b[4][3]}│{b[4][4]}│{b[4][5]}│{b[4][6]}│{b[4][7]}│{RESET_COLOR} E
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
F {BACK_GREEN}│{b[5][0]}│{b[5][1]}│{b[5][2]}│{b[5][3]}│{b[5][4]}│{b[5][5]}│{b[5][6]}│{b[5][7]}│{RESET_COLOR} F
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
G {BACK_GREEN}│{b[6][0]}│{b[6][1]}│{b[6][2]}│{b[6][3]}│{b[6][4]}│{b[6][5]}│{b[6][6]}│{b[6][7]}│{RESET_COLOR} G
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
H {BACK_GREEN}│{b[7][0]}│{b[7][1]}│{b[7][2]}│{b[7][3]}│{b[7][4]}│{b[7][5]}│{b[7][6]}│{b[7][7]}│{RESET_COLOR} H
{BACK_GREEN}┼────┼────┼────┼────┼────┼────┼────┼────┼{RESET_COLOR}
1 2 3 4 5 6 7 8"""
def has_dominated(self, player):
"""
Returns False if the other player is still on the board
"""
for y in range(8):
for x in range(8):
if self.board[x][y] != EMPTY and self.board[x][y] != player.color:
return False
return True
def is_full(self):
"""
Returns True/False if the board is/isn't full.
"""
for y in range(8):
for x in range(8):
if self.board[x][y] == EMPTY:
return False
return True
def has_valid_moves(self, player):
try:
return True if self._get_valid_moves(player) else False
except Exception as e:
return False
def _get_valid_moves(self, player):
valid_moves = []
for y in range(8):
for x in range(8):
move = x, y
if self.is_valid_move(player, move):
valid_moves.append(move)
return valid_moves
def is_valid_move(self, player, move):
"""
Returns True/False if the player can/cannot play the move.
"""
x, y = move
if x not in range(8) or y not in range(8):
return False # Off the board
elif self.board[x][y] != EMPTY:
return False # Position to move is not empty
else:
return True if self._get_flips(player, move) else False
def _get_flips(self, player, move):
"""
Return a list of tuples that represents stones (x,y positions) to flip.
"""
flips = []
flips += self._get_flips_in_direction(player, move, direction=( 0, 1)) # up
flips += self._get_flips_in_direction(player, move, direction=( 0, -1)) # down
flips += self._get_flips_in_direction(player, move, direction=( 1, 0)) # right
flips += self._get_flips_in_direction(player, move, direction=(-1, 0)) # left
flips += self._get_flips_in_direction(player, move, direction=( 1, 1)) # up-right
flips += self._get_flips_in_direction(player, move, direction=(-1, 1)) # up-left
flips += self._get_flips_in_direction(player, move, direction=( 1, -1)) # down-right
flips += self._get_flips_in_direction(player, move, direction=(-1, -1)) # down-left
return flips
def _get_flips_in_direction(self, player, move, direction):
flips = []
x, y = move
xd, yd = direction
line = self._get_line_in_direction(move, direction)
rest_of_line = line[1:] # line[0] would be where the player just put their stone
try:
flips_count = self._get_flip_count(player, rest_of_line)
except RuntimeError:
flips_count = 0
for i in range(flips_count):
next_position = x + xd*(i+1), y + yd*(i+1)
flips.append(next_position)
return flips
def _get_line_in_direction(self, position, direction):
"""
Returns a list (line) of stones in a direction.
"""
xp, yp = position
if xp not in range(8) or yp not in range(8):
return []
else:
xd, yd = direction
next_position = xp + xd, yp + yd
return [self.board[xp][yp]] + self._get_line_in_direction(next_position, direction)
def _get_flip_count(self, player, rest_of_line):
if player.color not in rest_of_line:
# X, [O, O, O]
# X, []
return 0
if not rest_of_line:
# X, []
return 0
if player.color == rest_of_line[0]:
# X, [X, ...]
return 0
if rest_of_line[0] == EMPTY:
raise RuntimeError
# X, [O, ..., X]
return 1 + self._get_flip_count(player, rest_of_line[1:])
def put_stone(self, player, move):
"""
Checks if the move is valid, and if so, puts the stone and flip others.
"""
if not self.is_valid_move(player, move):
raise RuntimeError("Invalid move")
x, y = move
self.board[x][y] = player.color
for xi, yi in self._get_flips(player, move):
self.board[xi][yi] = player.color
def get_player_score(self, player):
score = 0
for y in range(8):
for x in range(8):
if self.board[x][y] == player.color:
score += 1
return score
def get_best_next_move(self, player):
"""
Returns best next move for the `player` based on max score.
TODO: Predicts moves up to `look_head` times.
TODO: Should care more for strategic positions than just score.
"""
valid_moves = self._get_valid_moves(player)
time.sleep(0.25 * (len(valid_moves)+1))
shuffle(valid_moves)
best_next_move = None
max_score = 0
# Avoid dangerous positions
safe_moves = list(filter(lambda move: move not in DANGEROUS_POSITIONS, valid_moves))
if safe_moves:
valid_moves = safe_moves
for move in valid_moves:
# Get the corners
if move in CORNER_POSITIONS:
return move
# Get to the walls
elif 0 in move:
return move
# Get max flip
else:
tmp_board = Board()
tmp_board.board = copy.deepcopy(self.board) # copy this board
tmp_board.put_stone(player, move)
score = tmp_board.get_player_score(player)
if score > max_score:
max_score = score
best_next_move = move
return best_next_move
class Player():
def __init__(self, color, is_bot=False):
self.color = color
self.is_bot = is_bot
def get_move(self):
# Input move
move = input( \
f"Where will you play next, {self.color}? "
).strip().replace(" ", "").replace(",", "").replace("|", "")
if len(move) != 2:
raise RuntimeError # Invalid move
# Parse move
x, y = move[0].upper(), move[1].upper()
# fix move
if x in "12345678" and y.upper() in "ABCDEFGH":
x, y = y, x
x, y = ord(x.upper())-65, int(y)-1
elif x in "ABCDEFGH" and y in "12345678":
x, y = ord(x.upper())-65, int(y)-1
else:
raise RuntimeError # Invalid move - can't parse
return x, y
class Game:
def __init__(self):
self.board = Board()
self.players = [Player(BLACK), Player(WHITE)]
def _print(self):
"""
Prints the game: the header, notification(s) (if any) and the board
"""
os.system("clear")
header = "Reversi • By @josegalarza (2020)"
p0 = self.players[0]
p1 = self.players[1]
p0_score = f"{p0.color}{'%2d' % self.board.get_player_score(p0)}"
p1_score = f"{p1.color}{'%2d' % self.board.get_player_score(p1)}"
render = f"""{header}
Score: {p0_score} vs. {p1_score}
{self.board}
"""
print(render)
def play(self):
for player in cycle(self.players):
self._print()
if self.board.is_full() \
or self.board.has_dominated(player):
break
if self.board.has_valid_moves(player):
while True:
try:
if not player.is_bot:
move = player.get_move()
else:
print(f"Player {player.color} is thinking...")
move = self.board.get_best_next_move(player)
self.board.put_stone(player, move)
break
except KeyboardInterrupt:
sys.exit(1)
except RuntimeError as e:
pass
except Exception as e:
pass
self._print()
def start(self):
while True:
try:
self._print()
players = input("Number of players (1-2)? ").strip().replace(' ', '').replace(' ', '')
if players in ["1", "2"]:
break
except KeyboardInterrupt:
sys.exit(1)
except Exception:
pass
if players == "1":
self.players[1].is_bot = True
self.play()
if __name__ == '__main__':
game = Game()
game.start()