def __init__(self, dim_x, dim_y, margin, spaces, board=None): self.dim_x = dim_x self.dim_y = dim_y self.margin = margin self.spaces = spaces self.ovals=[] if board==None: self.board = Board(spaces, spaces) else: self.board = board self.spaces = max(board.x, board.y) self.diam = (float(dim_x)-2*float(margin))/float(self.spaces-1) self.master = Tk() self.master.resizable(True, True) self.master.configure(bg='#d8af4f') #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f') #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES) #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f') #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES) self.C = None self.drawGrid() self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) def callback(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'white') def callback2(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'black') #self.goForWhite(i, j) # Left-click for white, right-click for black self.C.bind("<Button-1>", callback2) self.C.bind("<Button-3>", callback)
def extractPatches(self, f): mtp = MoveTreeParser(f) #print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType)) sn = mtp.getSolutionNodes() inc = mtp.getIncorrectNodes() probtyp = mtp.getProblemType() if probtyp == 1 or probtyp == 3: #Black to live probtyp = 1 elif probtyp == 2 or probtyp == 4: #White to kill probtyp = 2 else: #Error should be thrown, but just in case it isn't probtyp = 0 isBTL = (probtyp == 1) if not sn.isdisjoint(inc): print('NOT DISJOINT') paths = mtp.getAllPaths() movesConsidered = set() for path in paths: parent = 0 start = mtp.start #print('START NEW PATH') for mid in path: move_dict = mtp.formatMove(mtp.moveID[mid]) saysblack = move_dict['isBlack'] #move_str[0:1]=='B' #print('{}''s turn'.format('black' if saysblack else 'white')) move_y = move_dict['y'] #ord(move_str[2]) - ord('a') move_x = move_dict['x'] #ord(move_str[3]) - ord('a') move = Board(start.x, start.y) move.white_stones = [x for x in start.white_stones] move.black_stones = [y for y in start.black_stones] try: move.place_stone(move_x, move_y, saysblack) if (parent, mid) not in movesConsidered: outcome = 0 if isBTL == saysblack: #CHECK THIS LOGIC if mid in sn: outcome = 1 elif mid in inc: outcome = 0 else: raise Exception('Unknown outcome!') else: ''' Assume only moves on incorrect path are correct for the "antagonist" ''' if mid in inc: outcome = 1 ''' Assume all moves for the "antagonist" are correct ''' # outcome = 1 self.individualExtraction(start, move, (move_x, move_y), saysblack, outcome) movesConsidered.add((parent, mid)) # Only train on the first wrong move for the protagonist if outcome == 0 and isBTL == saysblack: break except IllegalMove as e: print('{}: ({},{})'.format(e, move_x, move_y)) parent = mid start = move
def __init__(self, dim_x, dim_y, margin, spaces, board=None): self.dim_x = dim_x self.dim_y = dim_y self.margin = margin self.spaces = spaces self.ovals = [] if board == None: self.board = Board(spaces, spaces) else: self.board = board self.spaces = max(board.x, board.y) self.diam = (float(dim_x) - 2 * float(margin)) / float(self.spaces - 1) self.master = Tk() self.master.resizable(True, True) self.master.configure(bg='#d8af4f') #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f') #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES) #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f') #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES) self.C = None self.drawGrid() self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) def callback(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'white') def callback2(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'black') #self.goForWhite(i, j) # Left-click for white, right-click for black self.C.bind("<Button-1>", callback2) self.C.bind("<Button-3>", callback)
def parseStartState(self, gameData): boardSizeLocation = gameData.find("SZ") sizeString = '' counter = 0 currentChar = gameData[boardSizeLocation + counter + 3] ''' while(currentChar != ']'): sizeString += currentChar counter += 1 currentChar = gameData[boardSizeLocation + counter + 3] if(sizeString.isdigit()): size = int(sizeString) else: size = 19 ''' currentBoard = Board(self.boardDimensions['xMax'] - self.boardDimensions['xMin'] + 1,self.boardDimensions['yMax'] - self.boardDimensions['yMin'] + 1) whitePositionLocations = [m.start() for m in re.finditer('AW', gameData)] blackPositionLocations = [m.start() for m in re.finditer('AB', gameData)] stonePositions = whitePositionLocations + blackPositionLocations stonePositions.sort() for i in stonePositions: isBlack = False if i in blackPositionLocations: isBlack = not self.flipColors if i in whitePositionLocations: isBlack = self.flipColors counter = 0 while(True): currentChar = gameData[i + counter + 2] if (currentChar != '['): break currentChar = gameData[i + counter + 3] y = ord(currentChar) - ord('a') - self.boardDimensions['yMin'] currentChar = gameData[i + counter + 4] x = ord(currentChar) - ord('a') - self.boardDimensions['xMin'] if isBlack: currentBoard.black_stones.append((x,y)) else: currentBoard.white_stones.append((x,y)) #currentBoard.place_stone(x,y,isBlack) counter += 4 return currentBoard
def individualExtraction(self, start, move, movePosition, isblack, outcome): if (not isblack): newstart = Board(start.x, start.y) newstart.black_stones = start.white_stones newstart.white_stones = start.black_stones start = newstart newmove = Board(move.x, move.y) newmove.black_stones = move.white_stones newmove.white_stones = move.black_stones move = newmove sparsePatches = SparseDictionaryFeature(start, move, movePosition, isblack).get_transformed_data( 4, 'features/') if isblack: for row in sparsePatches: self.fout1a.write(','.join([str(x) for x in row] + [str(outcome)])) self.fout1a.write('\n') else: for row in sparsePatches: self.fout2a.write(','.join([str(x) for x in row] + [str(outcome)])) self.fout2a.write('\n') sparsePatches = SparseDictionaryFeature(start, move, movePosition, isblack).get_transformed_data( 5, 'features/') if isblack: for row in sparsePatches: self.fout3a.write(','.join([str(x) for x in row] + [str(outcome)])) self.fout3a.write('\n') else: for row in sparsePatches: self.fout4a.write(','.join([str(x) for x in row] + [str(outcome)])) self.fout4a.write('\n')
def actOnSolutionStates(self, f): mtp = MoveTreeParser(f) print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType)) sn = mtp.getSolutionStates() #print sn probtyp = mtp.getProblemType() if probtyp == 1 or probtyp == 3: #Black to live probtyp = 1 elif probtyp == 2 or probtyp == 4: #White to kill probtyp = 2 else: #Error should be thrown, but just in case it isn't probtyp = 0 isBTL = (probtyp==1) paths = mtp.getSolutionPaths() for path in paths: parent = 0 start = mtp.start for mid in path: move_dict = mtp.formatMove(mtp.moveID[mid]) saysblack = move_dict['isBlack'] move_y = move_dict['y'] move_x = move_dict['x'] move = Board(start.x, start.y) move.white_stones = [x for x in start.white_stones] move.black_stones = [y for y in start.black_stones] try: move.place_stone(move_x, move_y, saysblack) if isBTL == saysblack: if mid in sn: #DO WHATEVER YOU WANT WITH BOARD: move moveConverted = self.convert_board(move,0,2) print mid print moveConverted print move print move.black_stones print move.white_stones aliveGroups = gold.models.terminalLife.findAliveGroups(move, saysblack) print aliveGroups except IllegalMove as e: print('{}: ({},{})'.format(e, move_x, move_y,sys.exc_info()[-1].tb_lineno)) parent = mid start = move
class Launcher: def __init__(self, dim_x, dim_y, margin, spaces, board=None): self.dim_x = dim_x self.dim_y = dim_y self.margin = margin self.spaces = spaces self.ovals=[] if board==None: self.board = Board(spaces, spaces) else: self.board = board self.spaces = max(board.x, board.y) self.diam = (float(dim_x)-2*float(margin))/float(self.spaces-1) self.master = Tk() self.master.resizable(True, True) self.master.configure(bg='#d8af4f') #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f') #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES) #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f') #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES) self.C = None self.drawGrid() self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) def callback(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'white') def callback2(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'black') #self.goForWhite(i, j) # Left-click for white, right-click for black self.C.bind("<Button-1>", callback2) self.C.bind("<Button-3>", callback) def resize(self, x, y): if x==self.dim_x and y==self.dim_y: return self.dim_x = x self.dim_y = y self.diam = (float(min(x,y))-2*float(self.margin))/float(self.spaces-1) self.drawGrid() self.drawBoard() def goForWhite(self, pi, pj): #tree = MinMaxTree(self.board, False, True, 0, 0.0, 'b({},{})'.format(pi,pj)) #bestMove = tree.decideNextMove() #self.board.place_stone(bestMove.i, bestMove.j, False) #print(self.board) self.drawBoard() def mainloop(self): mainloop() def computeSpace(self, x_coord, y_coord): i = int(round((y_coord-self.margin)/self.diam)) if( i<0 ): i=0 elif( i>self.spaces-1 ): i = self.spaces - 1 j = int(round((x_coord-self.margin)/self.diam)) if( j<0 ): j=0 elif( j>self.spaces-1 ): j = self.spaces - 1 return [i, j] def computeCoord(self, i, j): y = self.margin+round((i)*self.diam) x = self.margin + round((j)*self.diam) return [x, y] def placeStoneNear(self, x, y, color): [i, j] = self.computeSpace(x, y) #print("test.place_stone({},{}, {})".format(i,j, color=='black')) #if not self.board.board_spaces()[i][j] == '0': if (i,j) in self.board.white_stones+self.board.black_stones: print ("There's already a stone at ({}, {}).".format(i, j)) else: self.board.place_stone(i, j, color=='black') #print(self.board) self.drawBoard() def drawStone(self, i, j, color, alive=False): [x0, y0] = self.computeCoord(i, j) x2 = x0+self.diam/2 #10 y2 = y0+self.diam/2 #10 x1 = x0+1-self.diam/2 #9 y1 = y0+1-self.diam/2 self.ovals.append(self.C.create_oval(x1, y1, x2, y2, fill=color, tags=color)) if( alive ): self.ovals.append(self.C.create_oval(x0-2, y0-2, x0+1, y0+1, fill='green', tags=color)) def setBoardIndex(self, index): self.setBoard(self.boards[int(index)]) self.drawBoard() def showPath(self, boards): self.boards = boards scale = Scale(self.master, orient=HORIZONTAL, from_=0, to=len(boards)-1, command=self.setBoardIndex, bg='#d8af4f',highlightthickness=0) scale.pack(side=BOTTOM, padx=10, pady=10, expand=NO) self.setBoard(boards[0]) self.drawBoard() self.mainloop() def drawPoint(self, i, j): [x0, y0] = self.computeCoord(i, j) x1 = x0+5 y1 = y0+5 x0 = x0-4 y0 = y0-4 self.ovals.append(self.C.create_oval(x0, y0, x1, y1, fill='black')) def setBoard(self, newboard): self.board = newboard def drawGrid(self): if self.C is None: #self.C.destroy() self.C = ResizingCanvas(self.master, self, width=self.dim_x, height=self.dim_y, highlightthickness=0, bg='#d8af4f') #self.C.grid(row=0,column=0, sticky=tkinter.N+tkinter.S+tkinter.W+tkinter.E) self.C.pack(side=TOP, fill=BOTH, expand=YES) self.C.delete(ALL) for i in range(self.spaces): bound = min(self.dim_x, self.dim_y) self.C.create_line(self.margin, self.margin+i*self.diam, bound-self.margin, self.margin+i*self.diam) self.C.create_line(self.margin+i*self.diam, self.margin, self.margin+i*self.diam, bound-self.margin ) self.drawPoint(3, 3) self.drawPoint(3, self.spaces-4) self.drawPoint(self.spaces-4, 3) self.drawPoint(self.spaces-4, self.spaces-4) self.drawPoint(3, (self.spaces-1)/2) self.drawPoint((self.spaces-1)/2, 3) self.drawPoint((self.spaces-1)/2, (self.spaces-1)/2) self.drawPoint(self.spaces-4, (self.spaces-1)/2) self.drawPoint((self.spaces-1)/2, self.spaces-4) ''' Draws board dim_x x dim_y pixels, with margin 'margin' and number of spaces 'spaces'. Only tested with (400, 400, 12, 19). ''' def drawBoard(self): #board, dim_x, dim_y, diam, margin, spaces): #i = 0 for c in self.C.children: c.destroy() for [color,stones] in [['white', self.board.white_stones], ['black', self.board.black_stones]]: living_groups = determineLife(self.board, color) self.C.delete(color) for stone in stones: alive = False for group in living_groups: if not alive and stone in group: alive = True self.drawStone(stone[0],stone[1],color,alive) #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MARGIN, DEFAULT_SPACES) #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, 30,5) #ui.drawBoard() '''
gameData = currentGame.read() boardSizeLocation = gameData.find("SZ") sizeString = '' counter = 0 currentChar = gameData[boardSizeLocation + counter + 3] while (currentChar != ']'): sizeString += currentChar counter += 1 currentChar = gameData[boardSizeLocation + counter + 3] if (sizeString.isdigit()): size = int(sizeString) currentBoard = Board(size, size) whitePositionLocations = [m.start() for m in re.finditer('AW', gameData)] blackPositionLocations = [m.start() for m in re.finditer('AB', gameData)] stonePositions = whitePositionLocations + blackPositionLocations stonePositions.sort() for i in stonePositions: isBlack = False if i in blackPositionLocations: isBlack = True counter = 0 while (True): currentChar = gameData[i + counter + 2] if (currentChar != '['):
gameData = currentGame.read() boardSizeLocation = gameData.find("SZ") sizeString = '' counter = 0 currentChar = gameData[boardSizeLocation + counter + 3] while(currentChar != ']'): sizeString += currentChar counter += 1 currentChar = gameData[boardSizeLocation + counter + 3] if(sizeString.isdigit()): size = int(sizeString) currentBoard = Board(size,size) whitePositionLocations = [m.start() for m in re.finditer('AW', gameData)] blackPositionLocations = [m.start() for m in re.finditer('AB', gameData)] stonePositions = whitePositionLocations + blackPositionLocations stonePositions.sort() for i in stonePositions: isBlack = False if i in blackPositionLocations: isBlack = True counter = 0 while(True): currentChar = gameData[i + counter + 2] if (currentChar != '['):
def get_vectors_from_file(self, f): mtp = MoveTreeParser(f) #print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType)) subpaths = f.split('/') subfnparts = subpaths[-1].split('\\') difficulty = subfnparts[-2] fname = subfnparts[-1] probId = fname.split('.')[0] sn = mtp.getSolutionNodes() inc = mtp.getIncorrectNodes() probtyp = mtp.getProblemType() if probtyp == 1 or probtyp == 3: #Black to live probtyp = 1 elif probtyp == 2 or probtyp == 4: #White to kill probtyp = 2 else: #Error should be thrown, but just in case it isn't probtyp = 0 isBTL = (probtyp == 1) if not sn.isdisjoint(inc): print('NOT DISJOINT') paths = mtp.getAllPaths() movesConsidered = set() fe = FeatureExtractor() vectors = [] for path in paths: parent = 0 start = mtp.start #print('START NEW PATH') for i, mid in enumerate(path): move_dict = mtp.formatMove(mtp.moveID[mid]) saysblack = move_dict['isBlack'] #move_str[0:1]=='B' #print('{}''s turn'.format('black' if saysblack else 'white')) move_y = move_dict['y'] #ord(move_str[2]) - ord('a') move_x = move_dict['x'] #ord(move_str[3]) - ord('a') move = Board(start.x, start.y) move.white_stones = [x for x in start.white_stones] move.black_stones = [y for y in start.black_stones] try: move.place_stone(move_x, move_y, saysblack) if (parent, mid) not in movesConsidered: features = fe.extract_features(start, move, (move_x, move_y), saysblack) inSoln = 1 if mid in sn else 0 inInc = 1 if mid in inc else 0 isTerminal = 1 if i == len(path) - 1 else 0 features['_PT'] = probtyp features['_SOLUTION'] = inSoln features['_INC'] = inInc features['_TERM'] = isTerminal features['_PROBID'] = probId features['_DI'] = difficulty features['_MOVE'] = mid features['_PARENT'] = parent movesConsidered.add((parent, mid)) vectors.append(features) except IllegalMove as e: print('{} ({},{}): {}'.format(fname, move_x, move_y, e)) parent = mid start = move return vectors
class Launcher: def __init__(self, dim_x, dim_y, margin, spaces, board=None): self.dim_x = dim_x self.dim_y = dim_y self.margin = margin self.spaces = spaces self.ovals = [] if board == None: self.board = Board(spaces, spaces) else: self.board = board self.spaces = max(board.x, board.y) self.diam = (float(dim_x) - 2 * float(margin)) / float(self.spaces - 1) self.master = Tk() self.master.resizable(True, True) self.master.configure(bg='#d8af4f') #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f') #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES) #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f') #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES) self.C = None self.drawGrid() self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) def callback(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'white') def callback2(event): #[i, j] = self.computeSpace(event.x, event.y) self.placeStoneNear(event.x, event.y, 'black') #self.goForWhite(i, j) # Left-click for white, right-click for black self.C.bind("<Button-1>", callback2) self.C.bind("<Button-3>", callback) def resize(self, x, y): if x == self.dim_x and y == self.dim_y: return self.dim_x = x self.dim_y = y self.diam = (float(min(x, y)) - 2 * float(self.margin)) / float(self.spaces - 1) self.drawGrid() self.drawBoard() def goForWhite(self, pi, pj): #tree = MinMaxTree(self.board, False, True, 0, 0.0, 'b({},{})'.format(pi,pj)) #bestMove = tree.decideNextMove() #self.board.place_stone(bestMove.i, bestMove.j, False) #print(self.board) self.drawBoard() def mainloop(self): mainloop() def computeSpace(self, x_coord, y_coord): i = int(round((y_coord - self.margin) / self.diam)) if (i < 0): i = 0 elif (i > self.spaces - 1): i = self.spaces - 1 j = int(round((x_coord - self.margin) / self.diam)) if (j < 0): j = 0 elif (j > self.spaces - 1): j = self.spaces - 1 return [i, j] def computeCoord(self, i, j): y = self.margin + round((i) * self.diam) x = self.margin + round((j) * self.diam) return [x, y] def placeStoneNear(self, x, y, color): [i, j] = self.computeSpace(x, y) #print("test.place_stone({},{}, {})".format(i,j, color=='black')) #if not self.board.board_spaces()[i][j] == '0': if (i, j) in self.board.white_stones + self.board.black_stones: print("There's already a stone at ({}, {}).".format(i, j)) else: self.board.place_stone(i, j, color == 'black') #print(self.board) self.drawBoard() def drawStone(self, i, j, color, alive=False): [x0, y0] = self.computeCoord(i, j) x2 = x0 + self.diam / 2 #10 y2 = y0 + self.diam / 2 #10 x1 = x0 + 1 - self.diam / 2 #9 y1 = y0 + 1 - self.diam / 2 self.ovals.append( self.C.create_oval(x1, y1, x2, y2, fill=color, tags=color)) if (alive): self.ovals.append( self.C.create_oval(x0 - 2, y0 - 2, x0 + 1, y0 + 1, fill='green', tags=color)) def setBoardIndex(self, index): self.setBoard(self.boards[int(index)]) self.drawBoard() def showPath(self, boards): self.boards = boards scale = Scale(self.master, orient=HORIZONTAL, from_=0, to=len(boards) - 1, command=self.setBoardIndex, bg='#d8af4f', highlightthickness=0) scale.pack(side=BOTTOM, padx=10, pady=10, expand=NO) self.setBoard(boards[0]) self.drawBoard() self.mainloop() def drawPoint(self, i, j): [x0, y0] = self.computeCoord(i, j) x1 = x0 + 5 y1 = y0 + 5 x0 = x0 - 4 y0 = y0 - 4 self.ovals.append(self.C.create_oval(x0, y0, x1, y1, fill='black')) def setBoard(self, newboard): self.board = newboard def drawGrid(self): if self.C is None: #self.C.destroy() self.C = ResizingCanvas(self.master, self, width=self.dim_x, height=self.dim_y, highlightthickness=0, bg='#d8af4f') #self.C.grid(row=0,column=0, sticky=tkinter.N+tkinter.S+tkinter.W+tkinter.E) self.C.pack(side=TOP, fill=BOTH, expand=YES) self.C.delete(ALL) for i in range(self.spaces): bound = min(self.dim_x, self.dim_y) self.C.create_line(self.margin, self.margin + i * self.diam, bound - self.margin, self.margin + i * self.diam) self.C.create_line(self.margin + i * self.diam, self.margin, self.margin + i * self.diam, bound - self.margin) self.drawPoint(3, 3) self.drawPoint(3, self.spaces - 4) self.drawPoint(self.spaces - 4, 3) self.drawPoint(self.spaces - 4, self.spaces - 4) self.drawPoint(3, (self.spaces - 1) / 2) self.drawPoint((self.spaces - 1) / 2, 3) self.drawPoint((self.spaces - 1) / 2, (self.spaces - 1) / 2) self.drawPoint(self.spaces - 4, (self.spaces - 1) / 2) self.drawPoint((self.spaces - 1) / 2, self.spaces - 4) ''' Draws board dim_x x dim_y pixels, with margin 'margin' and number of spaces 'spaces'. Only tested with (400, 400, 12, 19). ''' def drawBoard(self): #board, dim_x, dim_y, diam, margin, spaces): #i = 0 for c in self.C.children: c.destroy() for [color, stones] in [['white', self.board.white_stones], ['black', self.board.black_stones]]: living_groups = determineLife(self.board, color) self.C.delete(color) for stone in stones: alive = False for group in living_groups: if not alive and stone in group: alive = True self.drawStone(stone[0], stone[1], color, alive) #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MARGIN, DEFAULT_SPACES) #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, 30,5) #ui.drawBoard() '''