-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplay_with_human.py
82 lines (62 loc) · 2.74 KB
/
play_with_human.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
# Run this if you(human) wants to play against the agent.
from random import randint
class HumanPlayer():
"""Player that chooses a move according to user's input."""
def get_move(self, game, 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).
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
"""
legal_moves = game.get_legal_moves()
if not legal_moves:
return (-1, -1)
print(game.to_string()) #display the board for the human player
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
from game_agent import AlphaBetaPlayer
# create an isolation board (by default 7x7)
player1 = HumanPlayer()
player2 = AlphaBetaPlayer()
game = Board(player1, player2)
initial_pos1 = (randint(0, 6), randint(0, 6))
initial_pos2 = (randint(0, 6), randint(0, 6))
while (initial_pos2 == initial_pos1):
initial_pos2 = (randint(0, 6), randint(0, 6))
game.apply_move(initial_pos1)
game.apply_move(initial_pos2)
# players take turns moving on the board, so player1 should be next to move
assert(player1 == game.active_player)
winner, history, outcome = game.play(ENABLE_TIMEOUT = False)
print("\nWinner: {}\nOutcome: {}".format(winner, outcome))
print(game.to_string())
print("Move history:\n{!s}".format(history))