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
| import random import sys
def create_dominoes_game(rows, cols): Total = [[False for i in range(cols)] for i in range(rows)] return DominoesGame(Total)
class DominoesGame(object):
def __init__(self, board): self.board = board self.rows = len(board) self.cols = len(board[0])
def get_board(self): return self.board
def reset(self): self.board = [[False for i in range(self.cols)] for i in range(self.rows)]
def is_legal_move(self, row, col, vertical): if vertical: if row >= 0 and row < self.rows and col >= 0 and col < self.cols \ and row+1 < self.rows and not self.board[row][col] and not self.board[row+1][col]: return True else: if row >= 0 and row < self.rows and col >= 0 and col < self.cols \ and col+1 < self.cols and not self.board[row][col] and not self.board[row][col+1]: return True return False
def legal_moves(self, vertical): for i in range(self.rows): for j in range(self.cols): if self.is_legal_move(i, j, vertical): yield (i, j)
def perform_move(self, row, col, vertical): if vertical: self.board[row][col] = self.board[row+1][col] = True else: self.board[row][col] = self.board[row][col+1] = True
def game_over(self, vertical): if list(self.legal_moves(vertical)): return False return True
def copy(self): return DominoesGame([row[:] for row in self.board])
def successors(self, vertical): '''当前棋盘可能的所有存放情况,生成器函数''' for move in self.legal_moves(vertical): g = self.copy() g.perform_move(move[0], move[1], vertical) yield move, g
def get_random_move(self, vertical): return random.choice(list(self.legal_moves(vertical)))
def get_best_move(self, vertical, limit): best_move = () total_num = 0 is_max = True alpha = -sys.maxint beta = sys.maxint best_move, value, total_num = self.alpha_beta_search(is_max, alpha, beta, vertical, limit) return (best_move, value, total_num) def alpha_beta_search(self, is_max, alpha, beta, vertical, limit): total_num = 0 best_move = () if limit == 0: value = len(list(self.legal_moves(vertical))) - len(list(self.legal_moves(not vertical))) return (), value, 1 else: for move, g in self.successors(not is_max ^ vertical): if alpha < beta: _, value, num = g.alpha_beta_search(not is_max, alpha, beta, vertical, limit-1) total_num += num if is_max and value > alpha: alpha = value best_move = move elif not is_max and value < beta: beta = value return best_move, alpha if is_max else beta, total_num
|