-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTeekoGameAI.py
More file actions
267 lines (232 loc) · 10.5 KB
/
TeekoGameAI.py
File metadata and controls
267 lines (232 loc) · 10.5 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
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
import random
class TeekoPlayer:
""" An object representation for an AI game player for the game Teeko.
"""
board = [[' ' for j in range(5)] for i in range(5)]
pieces = ['b', 'r']
def __init__(self):
""" Initializes a TeekoPlayer object by randomly selecting red or black as its
piece color.
"""
self.my_piece = random.choice(self.pieces)
self.opp = self.pieces[0] if self.my_piece == self.pieces[1] else self.pieces[1]
def heuristic_game_value(self, state):
return
def succ(self, state, currPieces):
currSucc = []
return currSucc
def make_move(self, state):
""" Selects a (row, col) space for the next move. You may assume that whenever
this function is called, it is this player's turn to move.
Args:
state (list of lists): should be the current state of the game as saved in
this TeekoPlayer object. Note that this is NOT assumed to be a copy of
the game state and should NOT be modified within this method (use
place_piece() instead). Any modifications (e.g. to generate successors)
should be done on a deep copy of the state.
In the "drop phase", the state will contain less than 8 elements which
are not ' ' (a single space character).
Return:
move (list): a list of move tuples such that its format is
[(row, col), (source_row, source_col)]
where the (row, col) tuple is the location to place a piece and the
optional (source_row, source_col) tuple contains the location of the
piece the AI plans to relocate (for moves after the drop phase). In
the drop phase, this list should contain ONLY THE FIRST tuple.
Note that without drop phase behavior, the AI will just keep placing new markers
and will eventually take over the board. This is not a valid strategy and
will earn you no points.
"""
currPieces = 0
for currRow in state:
for currSpace in range(len(currRow)):
if currRow[currSpace] == ' ':
continue
else:
currPieces += 1
if currPieces < 8:
drop_phase = True
else:
drop_phase = False
if drop_phase:
# TODO: choose a piece to move and remove it from the board
# (You may move this condition anywhere, just be sure to handle it)
#
# Until this part is implemented and the move list is updated
# accordingly, the AI will not follow the rules after the drop phase!
pass
# select an unoccupied space randomly
# TODO: implement a minimax algorithm to play better
move = []
(row, col) = (random.randint(0,4), random.randint(0,4))
while not state[row][col] == ' ':
(row, col) = (random.randint(0,4), random.randint(0,4))
# ensure the destination (row,col) tuple is at the beginning of the move list
move.insert(0, (row, col))
return move
def opponent_move(self, move):
""" Validates the opponent's next move against the internal board representation.
You don't need to touch this code.
Args:
move (list): a list of move tuples such that its format is
[(row, col), (source_row, source_col)]
where the (row, col) tuple is the location to place a piece and the
optional (source_row, source_col) tuple contains the location of the
piece the AI plans to relocate (for moves after the drop phase). In
the drop phase, this list should contain ONLY THE FIRST tuple.
"""
# validate input
if len(move) > 1:
source_row = move[1][0]
source_col = move[1][1]
if source_row != None and self.board[source_row][source_col] != self.opp:
self.print_board()
print(move)
raise Exception("You don't have a piece there!")
if abs(source_row - move[0][0]) > 1 or abs(source_col - move[0][1]) > 1:
self.print_board()
print(move)
raise Exception('Illegal move: Can only move to an adjacent space')
if self.board[move[0][0]][move[0][1]] != ' ':
raise Exception("Illegal move detected")
# make move
self.place_piece(move, self.opp)
def place_piece(self, move, piece):
""" Modifies the board representation using the specified move and piece
Args:
move (list): a list of move tuples such that its format is
[(row, col), (source_row, source_col)]
where the (row, col) tuple is the location to place a piece and the
optional (source_row, source_col) tuple contains the location of the
piece the AI plans to relocate (for moves after the drop phase). In
the drop phase, this list should contain ONLY THE FIRST tuple.
This argument is assumed to have been validated before this method
is called.
piece (str): the piece ('b' or 'r') to place on the board
"""
if len(move) > 1:
self.board[move[1][0]][move[1][1]] = ' '
self.board[move[0][0]][move[0][1]] = piece
def print_board(self):
""" Formatted printing for the board """
for row in range(len(self.board)):
line = str(row)+": "
for cell in self.board[row]:
line += cell + " "
print(line)
print(" A B C D E")
def game_value(self, state):
""" Checks the current board status for a win condition
Args:
state (list of lists): either the current state of the game as saved in
this TeekoPlayer object, or a generated successor state.
Returns:
int: 1 if this TeekoPlayer wins, -1 if the opponent wins, 0 if no winner
TODO: complete checks for diagonal and box wins
"""
# check horizontal wins
for row in state:
for i in range(2):
if row[i] != ' ' and row[i] == row[i+1] == row[i+2] == row[i+3]:
return 1 if row[i]==self.my_piece else -1
# check vertical wins
for col in range(5):
for i in range(2):
if state[i][col] != ' ' and state[i][col] == state[i+1][col] == state[i+2][col] == state[i+3][col]:
return 1 if state[i][col]==self.my_piece else -1
# TODO: check \ diagonal wins
for i in range(0, 2):
for k in range(0, 2):
if(state[i][k] != ' ' and state [i][k] == state[i+1][k+1] == state[i+2][k+2] == state[i+3][k+3]):
if(state[i][k] == self.my_piece):
return 1
else:
return -1
# TODO: check / diagonal wins
for i in range(0, 2):
for k in range(3, 5):
if(state[i][k] != ' ' and state[i][k] == state[i+1][k-1] == state[i+2][k-2] == state[i+3][k-3]):
if(state[i][k] == self.my_piece):
return 1
else:
return -1
# TODO: check box wins
for i in range(4):
for k in range(4):
if(state[i][k] != ' ' and state[i][k] == state[i+1][k] == state[i][k+1] == state[i+1][k+1]):
if(state[i][k] == self.my_piece):
return 1
else:
return -1
return 0 # no winner yet
############################################################################
#
# THE FOLLOWING CODE IS FOR SAMPLE GAMEPLAY ONLY
#
############################################################################
def main():
print('Hello, this is Samaritan')
ai = TeekoPlayer()
piece_count = 0
turn = 0
# drop phase
while piece_count < 8 and ai.game_value(ai.board) == 0:
# get the player or AI's move
if ai.my_piece == ai.pieces[turn]:
ai.print_board()
move = ai.make_move(ai.board)
ai.place_piece(move, ai.my_piece)
print(ai.my_piece+" moved at "+chr(move[0][1]+ord("A"))+str(move[0][0]))
else:
move_made = False
ai.print_board()
print(ai.opp+"'s turn")
while not move_made:
player_move = input("Move (e.g. B3): ")
while player_move[0] not in "ABCDE" or player_move[1] not in "01234":
player_move = input("Move (e.g. B3): ")
try:
ai.opponent_move([(int(player_move[1]), ord(player_move[0])-ord("A"))])
move_made = True
except Exception as e:
print(e)
# update the game variables
piece_count += 1
turn += 1
turn %= 2
# move phase - can't have a winner until all 8 pieces are on the board
while ai.game_value(ai.board) == 0:
# get the player or AI's move
if ai.my_piece == ai.pieces[turn]:
ai.print_board()
move = ai.make_move(ai.board)
ai.place_piece(move, ai.my_piece)
print(ai.my_piece+" moved from "+chr(move[1][1]+ord("A"))+str(move[1][0]))
print(" to "+chr(move[0][1]+ord("A"))+str(move[0][0]))
else:
move_made = False
ai.print_board()
print(ai.opp+"'s turn")
while not move_made:
move_from = input("Move from (e.g. B3): ")
while move_from[0] not in "ABCDE" or move_from[1] not in "01234":
move_from = input("Move from (e.g. B3): ")
move_to = input("Move to (e.g. B3): ")
while move_to[0] not in "ABCDE" or move_to[1] not in "01234":
move_to = input("Move to (e.g. B3): ")
try:
ai.opponent_move([(int(move_to[1]), ord(move_to[0])-ord("A")),
(int(move_from[1]), ord(move_from[0])-ord("A"))])
move_made = True
except Exception as e:
print(e)
# update the game variables
turn += 1
turn %= 2
ai.print_board()
if ai.game_value(ai.board) == 1:
print("AI wins! Game over.")
else:
print("You win! Game over.")
if __name__ == "__main__":
main()