-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaghchal.py
432 lines (321 loc) · 14.9 KB
/
Baghchal.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
from mcts import *
class Board():
def __init__(self, board=None):
self.player_1 = "G"
self.player_2 = "T"
self.empty_point = "."
self.size = 5
self.tiger_positions = []
self.tiger_captured = 0
self.goat_counts = 20
self.goat_placed = 0
self.goat_eaten = 0
self.position = {}
self.invalid_moves = {frozenset(move) for move in [
((0, 1), (1, 0)), ((0, 1), (1, 2)), ((0, 3), (1, 2)), ((0, 3), (1, 4)),
((2, 1), (1, 0)), ((2, 1), (1, 2)), ((2, 3), (1, 2)), ((2, 3), (1, 4)),
((2, 1), (3, 0)), ((2, 1), (3, 2)), ((2, 3), (3, 2)), ((2, 3), (3, 4)),
((4, 1), (3, 0)), ((4, 1), (3, 2)), ((4, 3), (3, 2)), ((4, 3), (3, 4)),
((0, 1), (2, 3)), ((1, 2), (3, 4)), ((1, 0), (3, 2)), ((2, 1), (4, 3)),
((0, 3), (2, 1)), ((1, 2), (3, 0)), ((1, 4), (3, 2)), ((2, 3), (4, 1)),
]}
self.position_history = {}
self.moves_without_progress = 0
if board is not None:
self.position = dict(board.position)
self.tiger_positions = list(board.tiger_positions)
self.goat_placed = board.goat_placed
self.goat_eaten = board.goat_eaten
self.player_1 = board.player_1
self.player_2 = board.player_2
self.tiger_captured = board.tiger_captured
self.position_history = board.position_history
self.moves_without_progress = board.moves_without_progress
else:
self.init_board()
def init_board(self):
for row in range(self.size):
for col in range(self.size):
self.position[row, col] = self.empty_point
# set tiger in four corners
tiger_positions = [(0, 0), (0, self.size - 1), (self.size - 1, 0), (self.size - 1, self.size - 1)]
for position in tiger_positions:
self.position[position] = self.player_2
self.tiger_positions.append(position)
def best_tiger_positions_score(self):
best_positions = [(1, 1), (3, 1), (1, 3), (3, 3), (2, 2)]
score = 0
for tiger_position in self.tiger_positions:
if tiger_position in best_positions:
score += 1
return score
def goat_tiger_distance(self):
score = 0
goat_positions = self.get_goat_positions()
if len(goat_positions) == 0:
return score
directions = [
(-1, 0), (1, 0), (0, -1), (0, 1), # horizontal and vertical moves
(-1, -1), (1, 1), (-1, 1), (1, -1), # Diagonals
]
for goat_position in goat_positions:
row, col = goat_position
for dr, dc in directions:
row_end = row + dr
col_end = col + dc
if self.is_valid_move(goat_position, (row_end, col_end)) and self.position[row_end, col_end] == "T":
score += 0.5
return score
def get_goat_cluster_score(self):
goat_positions = self.get_goat_positions()
return sum(self.calculate_distance(goat1, goat2) for goat1 in goat_positions for goat2 in goat_positions)
def get_goat_positions(self):
return [(row, col) for row in range(self.size) for col in range(self.size) if self.position[row, col] == "G"]
def calculate_distance(self, pos1, pos2):
return math.sqrt(abs(pos1[0] - pos2[0])**2 + abs(pos1[1] - pos2[1])**2)
def is_draw(self):
if self.moves_without_progress >= 50:
return True
repeat_states = 0
for value in self.position_history.values():
if value >= 3:
repeat_states += 1
if repeat_states >= 2:
return True
return False
def is_valid_move(self, start, end):
if not (0 <= end[0] < self.size and 0 <= end[1] < self.size):
return False
if self.position[end] != self.empty_point:
return False
if frozenset((start, end)) in self.invalid_moves:
return False
row_diff = abs(start[0] - end[0])
col_diff = abs(start[1] - end[1])
if (row_diff, col_diff) in [(1, 0), (0, 1), (1, 1)]:
return True
elif self.player_1 == "T" and (row_diff, col_diff) in [(2, 0), (0, 2), (2,2)]:
mid_row = (start[0] + end[0]) // 2
mid_col = (start[1] + end[1]) // 2
if self.position[mid_row, mid_col] == self.player_2:
return True
return False
def is_goat_win(self):
directions = [
(-1, 0), (1, 0), (0, -1), (0, 1), # horizontal and vertical moves
(-1, -1), (1, 1), (-1, 1), (1, -1), # Diagonals
(-2, 0), (2, 0), (0, -2), (0, 2), # horizontal and vertical jumps
(-2, -2), (2, 2), (-2, 2), (2, -2), # Diagonal jumps
]
# if any one tiger can move then goat hasn't won
for tiger_position in self.tiger_positions:
row, col = tiger_position
for dr, dc in directions:
row_end = row + dr
col_end = col + dc
if self.is_valid_move(tiger_position, (row_end, col_end)):
return False
self.tiger_captured += 1
return True
def is_tiger_win(self):
return self.goat_eaten >= 5
def move_tiger(self, start, end):
board = Board(self)
board.position[start] = board.empty_point
board.position[end] = board.player_1
board.tiger_positions.remove(start)
board.tiger_positions.append(end)
# check if goat captured during tiger movement
row_dff = abs(start[0] - end[0])
col_diff = abs(start[1] - end[1])
if (row_dff, col_diff) in [(2, 0), (0, 2), (2, 2)]:
mid_row = (start[0] + end[0]) // 2
mid_col = (start[1] + end[1]) // 2
if board.position[mid_row, mid_col] == board.player_2:
board.position[mid_row, mid_col] = board.empty_point
board.goat_eaten += 1
board.player_1, board.player_2 = board.player_2, board.player_1
return board
def move_goat(self, start, end):
board = Board(self)
board.position[start] = board.empty_point
board.position[end] = board.player_1
board.player_1, board.player_2 = board.player_2, board.player_1
return board
def place_goat(self, row, col):
board = Board(self)
board.position[row, col] = board.player_1
board.goat_placed += 1
board.player_1, board.player_2 = board.player_2, board.player_1
return board
def generate_states(self):
actions = []
directions = [
(-1, 0), (1, 0), (0, -1), (0, 1), # horizontal and vertical moves
(-1, -1), (1, 1), (-1, 1), (1, -1), # Diagonals
(-2, 0), (2, 0), (0, -2), (0, 2), # horizontal and vertical jumps
(-2, -2), (2, 2), (-2, 2), (2, -2), # Diagonal jumps
]
# either place goat
if self.player_1 == "G" and self.goat_placed < 20:
for row in range(self.size):
for col in range(self.size):
if self.position[row, col] == self.empty_point:
actions.append(self.place_goat(row, col))
# or move goat
elif self.player_1 == "G" and self.goat_placed >= 20:
for row in range(self.size):
for col in range(self.size):
if self.position[row, col] == "G":
for dr, dc in directions:
row_end = row + dr
col_end = col + dc
if self.is_valid_move((row, col), (row_end, col_end)):
actions.append(self.move_goat((row, col), (row_end, col_end)))
# or move tiger
elif self.player_1 == "T":
for tiger_position in self.tiger_positions:
row, col = tiger_position
for dr, dc in directions:
row_end = row + dr
col_end = col + dc
if self.is_valid_move((row ,col), (row_end, col_end)):
actions.append(self.move_tiger((row ,col), (row_end, col_end)))
return actions
def game_loop(self):
print("Welcome to Baghchal!\n")
print(self)
mcts = MCTS()
while True:
if self.is_tiger_win():
print("------ Tigers win! ------")
break
if self.is_goat_win():
print("------ Goats win! ------")
break
if self.is_draw():
print("------ Game draw! ------")
break
print("Player: {} turn to play\n".format(self.player_1))
try:
if self.player_1 == "G" and self.goat_placed < 20:
# place goat
print("Place a goat:")
user_input = input("> ")
if user_input == "exit": break
if user_input == "": continue
row = int(user_input.split(",")[0]) - 1
col = int(user_input.split(",")[1]) - 1
if self.position[row, col] != self.empty_point:
print("This position is already occupied!")
print(self)
continue
last_goat_eaten = self.goat_eaten
has_tiger_moves = not self.is_goat_win()
self = self.place_goat(row, col)
if len(self.position_history) >= 2:
first_key = next(iter(self.position_history))
self.position_history.pop(first_key)
hashed_state = hash(self)
if hashed_state in self.position_history:
self.position_history[hashed_state] += 1
else:
self.position_history[hashed_state] = 1
#
if (self.player_1 == "T" and has_tiger_moves) or (self.player_1 == "G" and last_goat_eaten == self.goat_eaten):
self.moves_without_progress += 1
else:
self.moves_without_progress = 0
#
elif self.player_1 == "G" and self.goat_placed >= 20:
# move goat
print("Select a goat to move:")
start = input("> ")
start = (int(start.split(",")[0]) - 1, int(start.split(",")[1]) - 1)
if self.position[start] != self.player_1:
print("This position doesn't have a goat to move!")
print(self)
continue
print("Place that goat:")
end = input("> ")
end = (int(end.split(",")[0]) - 1, int(end.split(",")[1]) - 1)
if not self.is_valid_move(start, end):
print("Invalid goat move!")
print(self)
continue
last_goat_eaten = self.goat_eaten
has_tiger_moves = not self.is_goat_win()
self = self.move_goat(start, end)
if len(self.position_history) >= 2:
first_key = next(iter(self.position_history))
self.position_history.pop(first_key)
hashed_state = hash(self)
if hashed_state in self.position_history:
self.position_history[hashed_state] += 1
else:
self.position_history[hashed_state] = 1
#
if (self.player_1 == "T" and has_tiger_moves) or (self.player_1 == "G" and last_goat_eaten == self.goat_eaten):
self.moves_without_progress += 1
else:
self.moves_without_progress = 0
#
elif self.player_1 == "T":
# move tiger
print("Tiger's turn(AI): ")
# AI move
last_goat_eaten = self.goat_eaten
has_tiger_moves = not self.is_goat_win()
best_move = mcts.search(self)
try:
self = best_move.board
if len(self.position_history) >= 2:
first_key = next(iter(self.position_history))
self.position_history.pop(first_key)
hashed_state = hash(self)
if hashed_state in self.position_history:
self.position_history[hashed_state] += 1
else:
self.position_history[hashed_state] = 1
#
if (self.player_1 == "T" and has_tiger_moves) or (self.player_1 == "G" and last_goat_eaten == self.goat_eaten):
self.moves_without_progress += 1
else:
self.moves_without_progress = 0
#
except:
pass
# start = input("> ")
# start = (int(start.split(",")[0]) - 1, int(start.split(",")[1]) - 1)
# if start not in self.tiger_positions:
# print("This position doesn't have a tiger")
# print(self)
# continue
# print("Place that tiger:")
# end = input("> ")
# end = (int(end.split(",")[0]) - 1, int(end.split(",")[1]) - 1)
# if not self.is_valid_move(start, end):
# print("Invalid tiger move!")
# print(self)
# continue
# self = self.move_tiger(start, end)
except Exception as e:
print("Error: {}".format(e))
print(self)
def __str__(self):
board_string = ""
for row in range(self.size):
for col in range(self.size):
board_string += " {}".format(self.position[row, col])
board_string += "\n\n"
return board_string
if __name__ == "__main__":
board = Board()
board.game_loop()
# # # # ai vs ai
# mcts = MCTS()
# while True:
# best_move = mcts.search(board)
# board = best_move.board
# print(board)
# input()