-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.py
More file actions
221 lines (192 loc) · 7.13 KB
/
Board.py
File metadata and controls
221 lines (192 loc) · 7.13 KB
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
import random
from File import File
class Board:
def __init__(self, player_one, player_two):
self.state = [['', ' ', 'Turn: ', ''],
['1', '*', '*', '*', '*', '*', '*', '*', '*'],
['2', '*', '*', '*', '*', '*', '*', '*', '*'],
['3', '*', '*', '*', '*', '*', '*', '*', '*'],
['4', '*', '*', '*', '*', '*', '*', '*', '*'],
['5', '*', '*', '*', '*', '*', '*', '*', '*'],
['6', '*', '*', '*', '*', '*', '*', '*', '*'],
['7', '*', '*', '*', '*', '*', '*', '*', '*'],
['8', '*', '*', '*', '*', '*', '*', '*', '*'],
[' ', '1', '2', '3', '4', '5', '6', '7', '8']]
self.player_x = player_one
self.player_y = player_two
self.move_log = ''
# piece_positions acts as a key to this current state:
self.piece_positions = self.new_positions()
def display(self):
for p in self.player_x.pieces.values():
self.state[p.row][p.col] = p.player + p.type
for p in self.player_y.pieces.values():
self.state[p.row][p.col] = p.player + p.type
if self.move_log == '':
self.state[0][3] = str(0)
else:
self.state[0][3] = str(self.player_x.turn)
File.print('')
File.print('\n'.join(''.join(['{:3}'.format(item) for item in row]) for row in self.state))
def player_move(self, player, piece_id, new_row, new_col):
hero, opponent = self.identify_players(player)
piece = hero.pieces[piece_id]
self.state[piece.row][piece.col] = '*'
if piece_id == 'K' and not self.tile_is_safe(opponent, new_row, new_col):
print('\n')
File.error("Illegal move.")
self.state[piece.row][piece.col] = piece.player + piece.type
elif not self.legal_move(piece, new_row, new_col):
print('\n')
File.error("Illegal move.")
self.state[piece.row][piece.col] = piece.player + piece.type
else:
self.make_move(player, piece, (new_row, new_col))
self.move_log = piece.player + piece.type + ' to ' + str(new_row) + ',' + str(new_col)
def make_move(self, player, piece, new_coords, testing=False):
new_row = new_coords[0]
new_col = new_coords[1]
# If playerY eats playerX's rook:
if ('R' in self.player_x.pieces and
new_row == self.player_x.pieces['R'].row and \
new_col == self.player_x.pieces['R'].col):
del self.player_x.pieces['R']
if not testing:
File.prompt("PlayerX rook captured")
File.prompt("Stalemate")
exit(0)
self.state[piece.row][piece.col] = '*'
piece.prev_coords = (piece.row, piece.col)
piece.row = new_coords[0]
piece.col = new_coords[1]
self.state[0][0] = "player" + piece.player.upper()
self.state[piece.row][piece.col] = piece.player + piece.type
self.piece_positions = self.new_positions()
player.turn += 1
self.move_log = piece.player + piece.type + ' to ' + str(new_row) + ',' + str(new_col)
def tile_is_safe(self, enemy, tile_row, tile_col):
# Make new tile temporarily empty:
owner = self.state[tile_row][tile_col]
self.state[tile_row][tile_col] = '*'
# Make sure it's safe:
for p in enemy.pieces.values():
if self.legal_move(p, tile_row, tile_col):
return False
self.state[tile_row][tile_col] = owner
return True
def legal_move(self, piece, new_row, new_col):
if new_row == piece.row and new_col == piece.col: # piece unmoved, illegal move
return False
if not (1 <= new_row <= 8): # input out of bounds
return False
if not (1 <= new_col <= 8):
return False
if piece.type == 'R':
if ((new_row == piece.row or new_col == piece.col) and # horizontal/vertical move
self.state[new_row][new_col][0] != piece.player and # space unoccupied by ally
self.is_clear_path(piece.row, piece.col, new_row, new_col)):
return True
elif piece.type == 'K':
if (self.is_adjacent_spot(piece.row, piece.col, new_row, new_col) and
self.state[new_row][new_col][0] != piece.player): # unoccupied by ally
return True
else:
return False
def is_adjacent_spot(self, row, col, new_row, new_col):
# Return True if new coordinates are adjacent (horizontally,
# vertically, or diagonally) to the old coordinates.
for r in range(row - 1, row + 2):
for c in range(col - 1, col + 2):
if (new_row, new_col) == (r, c):
return True
return False
def is_clear_path(self, from_row, from_col, to_row, to_col):
# Check rook's path to make sure there are no obstacles in its way
if to_row > from_row: # moving horizontally to the right
i = from_row + 1
while i < to_row:
if self.state[i][from_col] != '*':
return False
i += 1
elif to_row < from_row: # moving horizontally to the left
i = from_row - 1
while i > to_row:
if self.state[i][from_col] != '*':
return False
i -= 1
elif to_col > from_col: # moving vertically up
i = from_col + 1
while i < to_col:
if self.state[from_row][i] != '*':
return False
i += 1
else: # to_col < from_col; moving down
i = from_col - 1
while i > to_col:
if self.state[from_row][i] != '*':
return False
i -= 1
return True
def ai_move(self, player):
if player.id == 'x':
key = random.randint(0, 1)
if key == 0 or 'R' not in player.pieces:
piece = player.pieces['K']
else:
piece = player.pieces['R']
else:
piece = player.pieces['K']
legal_moves = self.find_legal_moves(piece)
### if len(legal_moves) == 0: *CHECKMATE OR TIE* ###
if len(legal_moves) == 0:
File.prompt("game over")
exit(0)
if len(legal_moves) == 1:
new_destination = legal_moves[0]
else:
new_destination = legal_moves[random.randint(0, len(legal_moves) - 1)]
# move:
self.make_move(player, piece, (new_destination[0], new_destination[1]))
self.move_log = piece.player + piece.type + ' to ' + \
str(new_destination[0]) + ',' + str(new_destination[1])
def find_legal_moves(self, piece):
opponent = self.player_y if piece.player == 'x' else self.player_x
self.state[piece.row][piece.col] = '*'
legal_tiles = []
if piece.type == 'R':
for r in range(1, 9):
if (self.legal_move(piece, r, piece.col) and
self.tile_is_safe(opponent, r, piece.col)):
legal_tiles.append((r, piece.col))
for c in range(1, 9):
if (self.legal_move(piece, piece.row, c) and
self.tile_is_safe(opponent, piece.row, c)):
legal_tiles.append((piece.row, c))
else: # piece = king
for r in range(piece.row - 1, piece.row + 2):
for c in range(piece.col - 1, piece.col + 2):
if (self.legal_move(piece, r, c) and
self.tile_is_safe(opponent, r, c)):
legal_tiles.append((r, c))
self.state[piece.row][piece.col] = piece.player + piece.type
return legal_tiles
def identify_players(self, current_player):
if current_player.id == 'x':
hero = self.player_x
villain = self.player_y
else: # Can safely assume player_id == 'y'
hero = self.player_y
villain = self.player_x
return hero, villain
# Function to just serve as a key to this current state
def new_positions(self):
key = ''
for p in self.player_x.pieces.values():
key += p.player + p.type + str(p.row) + str(p.col)
for p in self.player_y.pieces.values():
key += p.player + p.type + str(p.row) + str(p.col)
return key
def undo_move(self, piece):
self.state[piece.row][piece.col] = '*'
piece.undo_move()
self.state[piece.row][piece.col] = piece.player + piece.type