-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsample_players.py
171 lines (133 loc) · 5.99 KB
/
sample_players.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
"""This file contains a collection of player classes for comparison with your
own agent and example heuristic functions.
"""
from random import randint
from scorefunctions import open_move_score
class RandomPlayer():
"""Player that chooses a move randomly."""
def get_move(self, game, legal_moves, time_left):
"""Randomly select a move from the available legal moves.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
legal_moves : list<(int, int)>
A list containing legal moves. Moves are encoded as tuples of pairs
of ints defining the next (row, col) for the agent to occupy.
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
----------
(int, int)
A randomly selected legal move; may return (-1, -1) if there are
no available legal moves.
"""
if not legal_moves:
return (-1, -1)
return legal_moves[randint(0, len(legal_moves) - 1)]
class GreedyPlayer():
"""Player that chooses next move to maximize heuristic score. This is
equivalent to a minimax search agent with a search depth of one.
"""
def __init__(self, score_fn=open_move_score):
self.score = score_fn
def get_move(self, game, legal_moves, time_left):
"""Select the move from the available legal moves with the highest
heuristic score.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
legal_moves : list<(int, int)>
A list containing legal moves. Moves are encoded as tuples of pairs
of ints defining the next (row, col) for the agent to occupy.
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
----------
(int, int)
The move in the legal moves list with the highest heuristic score
for the current game state; may return (-1, -1) if there are no
legal moves.
"""
if not legal_moves:
return (-1, -1)
_, move = max([(self.score(game.forecast_move(m), self), m) for m in legal_moves])
return move
class HumanPlayer():
"""Player that chooses a move according to user's input."""
def get_move(self, game, legal_moves, time_left):
"""
Select a move from the available legal moves based on user input at the
terminal.
**********************************************************************
NOTE: If testing with this player, remember to disable move timeout in
the call to `Board.play()`.
**********************************************************************
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
legal_moves : list<(int, int)>
A list containing legal moves. Moves are encoded as tuples of pairs
of ints defining the next (row, col) for the agent to occupy.
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
----------
(int, int)
The move in the legal moves list selected by the user through the
terminal prompt; automatically return (-1, -1) if there are no
legal moves
"""
if not legal_moves:
return (-1, -1)
print(('\t'.join(['[%d] %s' % (i, str(move)) for i, move in enumerate(legal_moves)])))
valid_choice = False
while not valid_choice:
try:
index = int(input('Select move index:'))
valid_choice = 0 <= index < len(legal_moves)
if not valid_choice:
print('Illegal move! Try again.')
except ValueError:
print('Invalid index! Try again.')
return legal_moves[index]
if __name__ == "__main__":
from isolation import Board
# create an isolation board (by default 7x7)
player1 = RandomPlayer()
player2 = GreedyPlayer()
game = Board(player1, player2)
# place player 1 on the board at row 2, column 3, then place player 2 on
# the board at row 0, column 5; display the resulting board state. Note
# that .apply_move() changes the calling object
game.apply_move((2, 3))
game.apply_move((0, 5))
print(game.to_string())
# players take turns moving on the board, so player1 should be next to move
assert(player1 == game.active_player)
# get a list of the legal moves available to the active player
print(game.get_legal_moves())
# get a successor of the current state by making a copy of the board and
# applying a move. Notice that this does NOT change the calling object
# (unlike .apply_move()).
new_game = game.forecast_move((1, 1))
assert(new_game.to_string() != game.to_string())
print("\nOld state:\n{}".format(game.to_string()))
print("\nNew state:\n{}".format(new_game.to_string()))
# play the remainder of the game automatically -- outcome can be "illegal
# move" or "timeout"; it should _always_ be "illegal move" in this example
winner, history, outcome = game.play()
print("\nWinner: {}\nOutcome: {}".format(winner, outcome))
print(game.to_string())
print("Move history:\n{!s}".format(history))