-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameBoard.py
536 lines (459 loc) · 14.8 KB
/
GameBoard.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
from time import time
from random import randrange
import unittest
from Position import Pos
class IllegalMoveError(Exception):
pass
class NotDoneError(Exception):
pass
# The true king of the water
KING_SQUIRTLE_SQUAD = True
# The false king and traitor
PUFFS_MAGICAL_DRAGON_SQUAD = False
WIDTH = 7
HEIGHT = 7
WIN_VALUE = 1000
WIN_FOR = KING_SQUIRTLE_SQUAD
class MyTestObject:
def __init__(self):
self.p1 = True
self.isKing = False
assert self.p1 or not self.isKing
class dictBoard:
def __init__(self, state, player=True):
"""
Board dictionary with minimax functions
:param state:
:type state: dict{}
:param player:
:type player: bool
:rtype: None
"""
self.board = {}
self.whoseTurn = player
self.cachedWin = False
self.cachedWinner = None
if state is None:
# This code runs only once, more efficient way to write it but shouldn't matter
self.board[Pos(6,6)] = 'D'
self.board[Pos(6,0)] = 'D'
self.board[Pos(6,3)] = 'K'
for i in range(2,5):
self.board[Pos(5,i)] = 'G'
#self.board[Pos(5, 3)] = 'G'
#self.board[Pos(5, 4)] = 'G'
self.board[Pos(1,5)] = 'D'
self.board[Pos(1,1)] = 'D'
self.board[Pos(0,3)] = 'D'
else:
self.board = state
del_list = []
for p in self.board.items():
if self.is_squirtle_surround(p[0]) & (p[1] is 'G'):
del_list.append(p[0])
for p in del_list:
self.board.pop(p)
if self.whoseTurn is KING_SQUIRTLE_SQUAD:
for p in self.teamPieces(PUFFS_MAGICAL_DRAGON_SQUAD):
if self.is_dragon_surrounded(p):
self.board[p] = 'd'
else:
# part of PUFFS_MAGICAL_DRAGON_SQUAD
for p in self.teamPieces(PUFFS_MAGICAL_DRAGON_SQUAD):
self.board[p]='D'
def __copy__(self):
rv = dictBoard({})
rv.board = self.board.copy()
return rv
def copy(self):
return self.__copy__()
def __repr__(self):
r_str = ""
for x in range(0, HEIGHT):
for y in range(0, WIDTH):
temp = self.board.get(Pos(HEIGHT-1-x, y))
if temp is None:
temp = '-'
r_str += temp + " "
r_str += "\n"
r_str += "\n"
return r_str
def __move(self, piecePos, newPos):
"""
Dumb __move function. Moves any contents of piecePos to any newPos. Doesn't follow rules
:param piecePos: Position of piece
:type piecePos: Pos
:param newPos: Position to __move to
:type newPos: Pos
:rtype: None
"""
temp = self.board.pop(piecePos)
self.board[newPos] = temp
def get(self, key):
return self.board.get(key)
def set(self, key, value):
"""
Sets value in board dictionary
:param key: Board position
:type key: Position.Pos
:param value: 'K' or 'D' or 'G' or None
:type value: char
"""
self.board[key] = value
@property
def king_pos(self):
"""
:return: Position of king
:rtype: Pos
"""
pieces = self.board.items()
for key, value in pieces:
if value == 'K':
return key
@property
def king_clear(self):
# TODO check if guards shorten path
for d in self.board.items():
if (d[1] == 'D') \
& (d[0].distance_to(Pos(0, self.king_pos.y)) < self.king_pos.x):
return False
return True
@property
def num_dragons(self):
count = 0
for i in self.board.values():
if i in ('D','d'):
count += 1
return count
@property
def num_guards(self):
count = 0
for i in self.board.values():
if i in ('G',"G"):
count += 1
return count
def num_little_ds(self):
count = 0
for i in self.board.values():
if i == 'd':
count+=1
return count
def winFor(self, player):
"""
Returns end value of board,
:param player:
:type player: bool
:return: Win value, +1000 if player, -1000 if not player, 0 if tie
:rtype: int
"""
if self.cachedWin is False:
won = False
king_pos = self.king_pos
assert king_pos is not None
# guards die off
"""
if (self.num_dragons >= 3) & (self.num_guards == 0) & (not self.king_clear):
won = True
self.cachedWinner = PUFFS_MAGICAL_DRAGON_SQUAD
self.cachedWin = True
"""
if player is KING_SQUIRTLE_SQUAD:
if king_pos.x == 0:
won = True
elif self.num_dragons < 3 and self.num_guards > 0:
won = True
elif player is PUFFS_MAGICAL_DRAGON_SQUAD:
if (len(self.get_legal_moves(king_pos)) is 0) \
& (self.is_squirtle_surround(king_pos)):
won = True
# TODO check if tie
# case 2: three or more drangons and no gaurds, dragons win
if won:
self.cachedWin = True
self.cachedWinner = player
return True
else:
return False
else:
return player is self.cachedWinner
def isTerminal(self):
return self.winFor(KING_SQUIRTLE_SQUAD) \
or self.winFor(PUFFS_MAGICAL_DRAGON_SQUAD) \
or (len(self.successors()) == 0)
def is_squirtle_surround(self, piecePos):
"""
:param self:
:type self:
:param piecePos:
:type piecePos:
:return:
:rtype:
"""
gk_count = 0
for i in (-1, 1):
if self.get(piecePos + Pos(i, 0)) in ('d', 'D'):
gk_count += 1
if self.get(piecePos + Pos(0, i)) in ('d', 'D'):
gk_count += 1
if gk_count > 2:
return True
return False
def is_dragon_surrounded(self, piecePos):
gk_count = 0
for i in (-1, 1):
if self.get(piecePos + Pos(i, 0)) in ('K', 'G'):
gk_count += 1
if self.get(piecePos + Pos(0, i)) in ('K', 'G'):
gk_count += 1
if gk_count > 1:
return True
return False
def legal_moves(self, piecePos):
"""
Takes a piece position on the board, returns all legal moves
:param board:
:type board: {"Pos":Char}
:param piecePos:
:type piecePos: Pos
:return: List of legal moves for a piece
:rtype: list[Pos]
"""
rList = []
# legal __move for all pieces
rList.append((piecePos + Pos(1, 0)))
rList.append((piecePos + Pos(-1, 0)))
rList.append((piecePos + Pos(0, 1)))
rList.append((piecePos + Pos(0, -1)))
# if King
# TODO better way to do this
if self.board.get(piecePos) == 'K':
kList = []
temp = 0
for x in rList:
if self.board.get(x) == 'G':
if temp == 0:
kList.append((x + Pos(1, 0)))
elif temp == 1:
kList.append(x + Pos(-1, 0))
elif temp == 2:
kList.append(x + Pos(0, 1))
else:
kList.append(x + Pos(0, -1))
temp += 1
rList.extend(kList)
elif self.board.get(piecePos) == 'D':
rList.append((piecePos + Pos(1, 1)))
rList.append((piecePos + Pos(1, -1)))
rList.append((piecePos + Pos(-1, 1)))
rList.append((piecePos + Pos(-1, -1)))
return rList
def get_neighbours_guards(self, piecePos):
count = 0
if self.board.get(piecePos + Pos(1, 0)) == 'G':
count += 1
if self.board.get(piecePos + Pos(0, 1)) == 'G':
count += 1
if self.board.get(piecePos + Pos(-1, 0)) == 'G':
count += 1
if self.board.get(piecePos + Pos(0, -1)) == 'G':
count += 1
return count
def get_legal_moves(self, piecePos):
"""
Creates list of legal moves from a piece
:param piecePos: position of a piece
:type piecePos: Position.Pos
:return: List of legal moves for this piece
:rtype: list[Pos]
"""
move_list = self.legal_moves(piecePos)
rList = list()
while len(move_list) > 0:
x = move_list.pop()
if (x.x >= 0) & (x.y >= 0) & (x.x < HEIGHT) & (x.y < WIDTH) & (self.board.get(x) in (None, 'd')):
rList.append(x)
return rList
# Modify this for use with the get_legal_moves function
def this_one(self, piecePos, newPos):
"""
:param piecePos: Piece to be moved
:type piecePos: Pos
:param newPos: Position to __move to
:type newPos: Pos
:return:
:rtype: (dictBoard, (Pos, Pos))
"""
if newPos is None:
print("Victory")
return self,(piecePos, newPos)
if self.board.get(piecePos) is None:
raise IllegalMoveError("Invalid Piece")
l = self.get_legal_moves(piecePos)
# **********************************************Use index
r_board = dictBoard(self.board.copy())
if l.count(newPos) <= 0:
raise IllegalMoveError("NOOOOOOO! An illegal __move!")
# fixme count is terrible use index
r_board.__move(piecePos, newPos)
r_board.whoseTurn = not self.whoseTurn
return r_board, (piecePos, newPos)
def teamPieces(self, team=None):
"""
Gives list of all pieces of current player
:type team: bool
:return: list of all pieces of current player
:rtype: list[Pos]
"""
if team is None:
team = self.whoseTurn
potential_moves = []
temp = self.board.items()
if team == KING_SQUIRTLE_SQUAD:
for i in temp:
if i[1] == 'G' or i[1] == 'K':
potential_moves.append(i[0])
else:
for i in temp:
if i[1] == 'D':
potential_moves.append(i[0])
return potential_moves
def successors(self):
"""
Returns list of all moves for all pieces of the current player
:return: new board state, original position, move position
:rtype: list[(dictBoard, (Pos, Pos))]
"""
rList = []
for p in self.teamPieces():
for m in self.get_legal_moves(p):
rList.append(self.this_one(p, m))
return rList
def utility(self):
"""
Returns the winner value
:return:
:rtype:
"""
if self.winFor(WIN_FOR):
return WIN_VALUE
else:
return -WIN_VALUE
class BoardTests(unittest.TestCase):
def test_board_init(self):
tbAlpha = dictBoard({}).board
self.assertEqual(tbAlpha, {}, "Board is not a dictionary.")
self.assertEqual(len(tbAlpha), 0, "Board is not empty on init.")
self.assertIsNone(tbAlpha.get(Pos(6,0)))
def test_start_board(self):
foo = dictBoard(None)
board = foo.board
self.assertEqual(board.get(Pos(6,0)), 'D')
self.assertIsNone(board.get(Pos(5,0)))
self.assertEqual(board.get(Pos(6,3)),'K')
def test_move_board(self):
foo = dictBoard(None)
board = foo.board
with self.assertRaises(IllegalMoveError):
foo.this_one(Pos(6,3),Pos(6,6)) # legal piece, illegal __move
with self.assertRaises(IllegalMoveError):
foo.this_one(Pos(6,5),Pos(5,5)) # illegal piece, legal __move
self.assertNotEqual(foo.get(Pos(6,4)),'K')
foo2 = foo.this_one(Pos(6,3),Pos(6,4))[0]
self.assertEqual(foo2.get(Pos(6,4)),'K')
self.assertNotEqual(foo2.get(Pos(6,3)),'K')
if __name__ == '__main__':
unittest.main
"""
b = dictBoard(None)
print(b)
print(b.get_legal_moves(Pos(6,3)))
print(b.this_one(Pos(6,3),Pos(6,4))[0])
b.teamPieces()
b.utility()
"""
#Tests
"""
class arrayBoard:
def __init__(self):
self.board = [[None for x in range(5)] for y in range(5)]
class testClass:
def __init__(self):
self.x = 0
self.y = 0
def __str__(self):
return self.x+","+self.y
limit = 1000000
testvar = testClass()
def testDictBoard(b):
print("Set:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
b[testvar] = MyTestObject()
print(time()-t_start)
print("Get:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
temp = b[testvar]
print(time()-t_start)
def testDictBoardClass(b):
print("Set:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
b.board[testvar] = MyTestObject()
print(time()-t_start)
print("Get:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
temp = b.board[testvar]
print(time()-t_start)
def testArrayBoard(b):
print("Set:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
b[y][z] = MyTestObject()
print(time()-t_start)
print("Get:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
temp = b[y][z]
print(time()-t_start)
def testArrayBoardClass(b):
print("Set:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
b.board[y][z] = MyTestObject()
print(time()-t_start)
print("Get:", end=' ')
t_start = time()
for x in range(limit):
for y in range(5):
for z in range(5):
temp = b.board[y][z]
print(time()-t_start)
varDict = {}
varArray = [[None for x in range(5)] for y in range(5)]
classBoard = dictBoard()
classArray = arrayBoard()
print("Variable defined dictionary:")
testDictBoard(varDict)
print("\nClass defined dictionary:")
testDictBoardClass(classBoard)
print("\nVariable defined array:")
testArrayBoard(varArray)
print("\nClass defined array:")
testArrayBoardClass(classArray)
"""