Skip to content

Commit

Permalink
add expectimax agent
Browse files Browse the repository at this point in the history
  • Loading branch information
duducheng committed Sep 27, 2018
1 parent a7ae066 commit b68dfbd
Show file tree
Hide file tree
Showing 16 changed files with 8,040 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
.idea/
tmp*

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
Empty file added game2048/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions game2048/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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._decide()
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 _decide(self):
direction = int(input("0: left, 1: down, 2: right, 3: up = ")) % 4
return direction


class RandomAgent(Agent):

def _decide(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 _decide(self):
direction = self.search_func(self.game.board)
return direction
60 changes: 60 additions & 0 deletions game2048/displays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import sys
from IPython.display import HTML, display as ipy_display


class Display:
'''A basic display.'''

def display(self, game):
if game.end == 2:
self.win(game)
elif game.end == 1:
self.lose(game)
else:
self.show(game)

def _display(self, game):
print(game)

def show(self, game):
self._display(game)

def win(self, game):
self._display(game)
print("You win! Score: %s" % game.score)

def lose(self, game):
self._display(game)
print("You lose! Score: %s" % game.score)


class IPythonDisplay(Display):
'''A better display for IPython (Jupyter) notebook environments.'''

def __init__(self, display_size=40):
self.display_size = display_size

def _render(self, game):
board = game.board
html = '''<h1>Score: {}</h1>'''.format(game.score)
table = '''<table style="border: 5px solid black;">{}</table>'''
td = '''<td style="border:3px solid black; text-align:center;"
width="%s" height="%s">{}</td>''' % (self.display_size, self.display_size)
content = ''
for row in range(game.size):
content += '''<tr>'''
for col in range(game.size):
elem = int(board[row, col])
content += td.format(elem if elem else "")
content += '''</tr>'''
html += table.format(content)
return html

def _display(self, game):
if 'ipykernel' in sys.modules:
source = self._render(game)
ipy_display(HTML(source))
else:
print("Warning: since it's not in ipykernel, "
"it will show the command line version.")
super()._display(game)
54 changes: 54 additions & 0 deletions game2048/expectimax/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
build.zip
config.h
config.log
config.status
Makefile
bin/

# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# =========================
# Operating System Files
# =========================

# OSX
# =========================

.DS_Store
.AppleDouble
.LSOverride

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
Loading

0 comments on commit b68dfbd

Please sign in to comment.