forked from duducheng/2048-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agents.py
48 lines (36 loc) · 1.33 KB
/
agents.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
import numpy as np
class Agent:
'''Agent Base.'''
def __init__(self, game, display=None):
self.game = game
self.display = display
def play(self, max_iter=np.inf, verbose=False):
n_iter = 0
while (n_iter < max_iter) and (not self.game.end):
direction = self.step()
self.game.move(direction)
n_iter += 1
if verbose:
print("Iter: {}".format(n_iter))
print("======Direction: {}======".format(
["left", "down", "right", "up"][direction]))
if self.display is not None:
self.display.display(self.game)
def step(self):
direction = int(input("0: left, 1: down, 2: right, 3: up = ")) % 4
return direction
class RandomAgent(Agent):
def step(self):
direction = np.random.randint(0, 4)
return direction
class ExpectiMaxAgent(Agent):
def __init__(self, game, display=None):
if game.size != 4:
raise ValueError(
"`%s` can only work with game of `size` 4." % self.__class__.__name__)
super().__init__(game, display)
from .expectimax import board_to_move
self.search_func = board_to_move
def step(self):
direction = self.search_func(self.game.board)
return direction