strategy.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import time
  2. from collections import deque
  3. from itertools import islice
  4. from parser import COLUMNS, NOBLOCK, detect_blocks, detect_exa, \
  5. detect_held, print_board, is_basic, is_bomb, bomb_to_basic
  6. GRAB, DROP, SWAP, LEFT, RIGHT = range(5)
  7. GET = ((GRAB,), (SWAP, GRAB), (GRAB, SWAP, DROP, SWAP, GRAB))
  8. PUT = ((DROP,), (DROP, SWAP), (DROP, SWAP, GRAB, SWAP, DROP))
  9. #REVERSE = [DROP, GRAB, SWAP, RIGHT, LEFT]
  10. MIN_BASIC_GROUP_SIZE = 4
  11. MIN_BOMB_GROUP_SIZE = 2
  12. FIND_GROUPS_DEPTH = 20
  13. FRAG_DEPTH = 20
  14. COLSIZE_PRIO = 5
  15. class State:
  16. def __init__(self, blocks, exa, held):
  17. assert exa is not None
  18. self.blocks = blocks
  19. self.exa = exa
  20. self.held = held
  21. def has_holes(self):
  22. return any(self.blocks[i] == NOBLOCK
  23. for col in self.iter_columns()
  24. for i in col)
  25. def iter_columns(self):
  26. nrows = self.nrows()
  27. def gen_col(col):
  28. for row in range(nrows):
  29. i = row * COLUMNS + col
  30. if self.blocks[i] != NOBLOCK:
  31. yield i
  32. for col in range(COLUMNS):
  33. yield gen_col(col)
  34. @classmethod
  35. def detect(cls, board):
  36. blocks = [NOBLOCK] * (COLUMNS * 2) + list(detect_blocks(board))
  37. exa = detect_exa(board)
  38. held = detect_held(board, exa)
  39. return cls(blocks, exa, held)
  40. def copy(self):
  41. return State(list(self.blocks), self.exa, self.held)
  42. def colsizes(self):
  43. for col in range(COLUMNS):
  44. yield self.nrows() - self.colskip(col)
  45. def score(self, points, moves, prev):
  46. frag = self.fragmentation()
  47. colsizes = list(self.colsizes())
  48. mincol = min(colsizes)
  49. maxcol = max(colsizes)
  50. colsize_score = maxcol, colsizes.count(maxcol), -mincol
  51. #colsize_score = tuple(sorted(colsizes, reverse=True))
  52. #if prev.nrows() >= 6:
  53. # return colsize_score, -points, frag, len(moves)
  54. prev_colsize = max(prev.colsizes())
  55. if prev_colsize >= COLSIZE_PRIO:
  56. return colsize_score, frag, -points, len(moves)
  57. else:
  58. return -points, frag, colsize_score, len(moves)
  59. def score_moves(self):
  60. # clear exploding blocks before computing colsize
  61. prev = self.copy()
  62. prev.score_points()
  63. for moves in self.gen_moves():
  64. try:
  65. points, newstate = self.simulate(moves)
  66. yield newstate.score(points, moves, prev), moves
  67. except AssertionError:
  68. pass
  69. def colskip(self, col):
  70. nrows = self.nrows()
  71. for row in range(nrows):
  72. if self.blocks[row * COLUMNS + col] != NOBLOCK:
  73. return row
  74. return nrows
  75. def find_unmovable_blocks(self):
  76. unmoveable = set()
  77. bombed = set()
  78. for block, group in self.find_groups():
  79. if is_basic(block) and len(group) >= MIN_BASIC_GROUP_SIZE:
  80. for i in group:
  81. unmoveable.add(i)
  82. elif is_bomb(block) and len(group) >= MIN_BOMB_GROUP_SIZE:
  83. bombed.add(bomb_to_basic(block))
  84. for i in group:
  85. unmoveable.add(i)
  86. for i, block in enumerate(self.blocks):
  87. if block in bombed:
  88. unmoveable.add(i)
  89. return unmoveable
  90. def simulate(self, moves):
  91. s = self.copy()
  92. points = 0
  93. # clear the current board before planning the next move
  94. #s.score_points()
  95. if not moves:
  96. return s.score_points(), s
  97. # avoid swapping/grabbing currently exploding items
  98. unmoveable = s.find_unmovable_blocks()
  99. for move in moves:
  100. if move == LEFT:
  101. assert s.exa > 0
  102. s.exa -= 1
  103. elif move == RIGHT:
  104. assert s.exa < COLUMNS - 1
  105. s.exa += 1
  106. elif move == GRAB:
  107. assert s.held == NOBLOCK
  108. row = s.colskip(s.exa)
  109. assert row < s.nrows()
  110. i = row * COLUMNS + s.exa
  111. assert i not in unmoveable
  112. s.held = s.blocks[i]
  113. s.blocks[i] = NOBLOCK
  114. elif move == DROP:
  115. assert s.held != NOBLOCK
  116. row = s.colskip(s.exa)
  117. assert row > 0
  118. i = row * COLUMNS + s.exa
  119. s.blocks[i - COLUMNS] = s.held
  120. s.held = NOBLOCK
  121. points += s.score_points()
  122. elif move == SWAP:
  123. row = s.colskip(s.exa)
  124. assert row < s.nrows() - 2
  125. i = row * COLUMNS + s.exa
  126. j = i + COLUMNS
  127. assert i not in unmoveable
  128. assert j not in unmoveable
  129. s.blocks[i], s.blocks[j] = s.blocks[j], s.blocks[i]
  130. points += s.score_points()
  131. return points, s
  132. def find_groups(self, depth=FIND_GROUPS_DEPTH):
  133. def follow_group(i, block, group):
  134. if self.blocks[i] == block and i not in visited:
  135. group.append(i)
  136. visited.add(i)
  137. for nb in self.neighbors(i):
  138. follow_group(nb, block, group)
  139. visited = set()
  140. for col in self.iter_columns():
  141. for i in islice(col, depth):
  142. block = self.blocks[i]
  143. group = []
  144. follow_group(i, block, group)
  145. if len(group) > 1:
  146. #for j in group:
  147. # visited.add(j)
  148. yield block, group
  149. def neighbors(self, i):
  150. def gen_indices():
  151. row, col = divmod(i, COLUMNS)
  152. if col > 0:
  153. yield i - 1
  154. if col < COLUMNS - 1:
  155. yield i + 1
  156. if row > 0:
  157. yield i - COLUMNS
  158. if row < self.nrows() - 1:
  159. yield i + COLUMNS
  160. for j in gen_indices():
  161. if self.blocks[j] != NOBLOCK:
  162. yield j
  163. def fragmentation(self, depth=FRAG_DEPTH):
  164. """
  165. Sum the minimum distance from every block in the first 3 layers to the
  166. closest block of the same color.
  167. """
  168. def find_closest(i):
  169. block = self.blocks[i]
  170. work = deque([(i, -1)])
  171. visited = {i}
  172. while work:
  173. i, dist = work.popleft()
  174. if dist >= 0 and self.blocks[i] == block:
  175. return dist
  176. for j in self.neighbors(i):
  177. if j not in visited:
  178. visited.add(j)
  179. work.append((j, dist + 1))
  180. # only one of this type -> don't count as fragmented
  181. return 0
  182. return sum(find_closest(i)
  183. for col in self.iter_columns()
  184. for i in islice(col, depth))
  185. def score_points(self, multiplier=1):
  186. remove = []
  187. points = 0
  188. for block, group in self.find_groups():
  189. if is_basic(block) and len(group) >= MIN_BASIC_GROUP_SIZE:
  190. remove.extend(group)
  191. points += len(group) * multiplier
  192. elif is_bomb(block) and len(group) >= MIN_BOMB_GROUP_SIZE:
  193. #points += 10
  194. remove.extend(group)
  195. for i, other in enumerate(self.blocks):
  196. if other == bomb_to_basic(block):
  197. remove.append(i)
  198. remove.sort()
  199. prev = None
  200. for i in remove:
  201. if i != prev:
  202. while self.blocks[i] != NOBLOCK:
  203. self.blocks[i] = self.blocks[i - COLUMNS]
  204. i -= COLUMNS
  205. prev = i
  206. if points:
  207. points += self.score_points(min(2, multiplier * 2))
  208. return points
  209. def gen_moves(self):
  210. yield ()
  211. for src in range(COLUMNS):
  212. diff = src - self.exa
  213. direction = RIGHT if diff > 0 else LEFT
  214. mov1 = abs(diff) * (direction,)
  215. yield mov1 + (SWAP,)
  216. yield mov1 + (GRAB, SWAP, DROP)
  217. for dst in range(COLUMNS):
  218. diff = dst - src
  219. direction = RIGHT if diff > 0 else LEFT
  220. mov2 = abs(diff) * (direction,)
  221. for i, get in enumerate(GET):
  222. if i > 1 or diff != 0:
  223. for put in PUT:
  224. yield mov1 + get + mov2 + put
  225. def solve(self):
  226. if self.held != NOBLOCK:
  227. return (DROP,)
  228. score, moves = min(self.score_moves())
  229. return moves
  230. def print(self):
  231. print_board(self.blocks, self.exa, self.held)
  232. def nrows(self):
  233. return len(self.blocks) // COLUMNS
  234. def moves_to_keys(moves):
  235. return ''.join('jjkad'[move] for move in moves)
  236. if __name__ == '__main__':
  237. import sys
  238. from PIL import Image
  239. #from pprint import pprint
  240. board = Image.open('screens/board%d.png' % int(sys.argv[1])).convert('HSV')
  241. state = State.detect(board)
  242. print('parsed:')
  243. state.print()
  244. print()
  245. start = time.time()
  246. moves = state.solve()
  247. print('moves:', moves_to_keys(moves))
  248. end = time.time()
  249. print('elapsed:', end - start)
  250. print()
  251. print('target after moves:')
  252. points, newstate = state.simulate(moves)
  253. newstate.print()
  254. print()
  255. #for score, moves in sorted(state.score_moves()):
  256. # print('move %18s:' % moves_to_keys(moves), score)
  257. # #print('moves:', moves_to_keys(moves), moves)
  258. # #print('score:', score)
  259. #print('\nmoves:', moves_to_keys(state.solve()))