def move(self, gn_current): assert(gn_current.board().turn == 0) if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = self._maxd t0 = time.time() best_value, best_move = negamax(self._pos, depth, alpha, beta, 1, self._func) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) print depth, best_value, crdn, time.time() - t0 self._pos = self._pos.move(best_move) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): if gn_current.board().turn == 1 : # Apply last_move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) #self.first_move = False #t0 = time.time() move, score = sunfish_mod3.search(self._pos, maxn=self._maxn) #print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119-move[0]) + sunfish.render(119 - move[1]) else: if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) #t0 = time.time() move, score = sunfish_mod3.search(self._pos, maxn=self._maxn) #print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(move[0]) + sunfish.render(move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move_player(self, move): uci_move = move if not self.isPlayerTurn: return (False, None) if self.game_end(): return (False, None) match = re.match('([a-h][1-8])' * 2, move) if match: if self.isPlayerwhite: move = sunfish.parse(match.group(1)), sunfish.parse( match.group(2)) else: move = 119 - sunfish.parse( match.group(1)), 119 - sunfish.parse(match.group(2)) else: return (False, None) if move not in self.pos.gen_moves(): return (False, None) self.pos = self.pos.move(move) annotation = self.get_kor_sentence(uci_move, True) self.isPlayerTurn = False return (True, annotation)
def move(self, gn_current): sys.path.append("/Users/Brennen/sunfish") import sunfish searcher = sunfish.Searcher() assert (gn_current.board().turn == False) # Apply last_move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) t0 = time.time() #print self._maxn move, score = searcher.search(self._pos, secs=5) print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119 - move[0]) + sunfish.render(119 - move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): if gn_current.board().turn == 1: # Apply last_move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) #self.first_move = False #t0 = time.time() move, score = sunfish_mod3.search(self._pos, maxn=self._maxn) #print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119 - move[0]) + sunfish.render(119 - move[1]) else: if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) #t0 = time.time() move, score = sunfish_mod3.search(self._pos, maxn=self._maxn) #print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(move[0]) + sunfish.render(move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): assert (gn_current.board().turn != True) if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = self._maxd t0 = time.time() best_value, best_move = negamax(self._pos, depth, alpha, beta, 1, self._func) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) print(depth, best_value, crdn, time.time() - t0) self._pos = self._pos.move(best_move) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): searcher = sunfish.Searcher() # assert(gn_current.board().turn == False) # parse UCI move into Sunfish format move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) t0 = time.time() # calls Sunfish's search function to find a move move, score = searcher.search(self._pos, self._maxn) print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119 - move[0]) + sunfish.render(119 - move[1]) move = create_move(gn_current.board(), crdn) # updates game moves and returns board gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def prepare(self): try: move_str = self.move_str.lower() self.move = parse(move_str[0:2]), parse(move_str[2:4]) self.prepared = True except ValueError: # Inform the user when invalid input (e.g. "help") is entered pass
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ armies, stones, board, color, castling, enpas, hclock, fclock = fen.split() wa, ba = int(army_abr_dict[armies[0]]), int(army_abr_dict[armies[1].upper()]) ws, bs = int(stones[0]), int(stones[1]) board = re.sub('\d', (lambda m: '.'*int(m.group(0))), board) board = list(' '*9+'\n'+' '*9+'\n ' + '\n '.join(board.split('/')) + '\n'+' '*9+'\n'+' '*10) change = lambda p, a: classic_piece_to_army_piece_dict[p][a - 1] for num, char in enumerate(board): if char == '.': continue if char.isspace(): continue if char.isupper(): board[num] = change(char, wa) else: board[num] = change(char.upper(), ba).lower() board = "".join(board) color = 0 if color == 'w' else 1 if color == 1: board = board[::-1].swapcase() wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = sunfish.parse(enpas) if enpas != '-' else 0 score = sum(sunfish.pst[p][i] for i,p in enumerate(board) if p.isupper() and p != 'U') score -= sum(sunfish.pst[p.upper()][i] for i,p in enumerate(board) if p.islower() and p != 'u') pos = sunfish.Position(board, color, False, score, wa, ba, ws, bs, wc, bc, ep, 0) return pos
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ armies, stones, board, color, castling, enpas, hclock, fclock = fen.split() wa, ba = int(army_abr_dict[armies[0]]), int( army_abr_dict[armies[1].upper()]) ws, bs = int(stones[0]), int(stones[1]) board = re.sub('\d', (lambda m: '.' * int(m.group(0))), board) board = list(' ' * 9 + '\n' + ' ' * 9 + '\n ' + '\n '.join(board.split('/')) + '\n' + ' ' * 9 + '\n' + ' ' * 10) change = lambda p, a: classic_piece_to_army_piece_dict[p][a - 1] for num, char in enumerate(board): if char == '.': continue if char.isspace(): continue if char.isupper(): board[num] = change(char, wa) else: board[num] = change(char.upper(), ba).lower() board = "".join(board) color = 0 if color == 'w' else 1 if color == 1: board = board[::-1].swapcase() wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = sunfish.parse(enpas) if enpas != '-' else 0 score = sum(sunfish.pst[p][i] for i, p in enumerate(board) if p.isupper() and p != 'U') score -= sum(sunfish.pst[p.upper()][i] for i, p in enumerate(board) if p.islower() and p != 'u') pos = sunfish.Position(board, color, False, score, wa, ba, ws, bs, wc, bc, ep, 0) return pos
def mover_ficha(self, columna, fila): ficha = self.celda_seleccionada.ficha celda = self.partida.tablero.obtener_celda(columna, fila) # verificamos si la celda tiene ficha: if celda.tiene_ficha(): # si tiene ficha verificamos que no sea del mismo color: celdaVerificada = ficha.color != celda.ficha.color else: celdaVerificada = True if ficha.puede_mover(celda) and celdaVerificada: # puede realizar el movimiento: self.partida.registrar_movimiento( ficha=self.celda_seleccionada.ficha, fichaEliminada=celda.ficha, celdaOrigen=self.celda_seleccionada, celdaDestino=celda) # ajustamos el movimiento: desde = chr(97 + self.celda_seleccionada.columna) + str( self.celda_seleccionada.fila + 1) hasta = chr(97 + columna) + str(fila + 1) if self.secs == 1: mover = sunfish.parse(desde, 'b'), sunfish.parse(hasta, 'b') else: mover = sunfish.parse(desde), sunfish.parse(hasta) self.posicion = self.posicion.move(mover) # valida si se comio el rey para finalizar la partida: if celda.ficha is not None and celda.ficha.nombre == "rey": self.partida.finalizar(motivo="jacke mate", color=self.colorOpuesto( celda.ficha.color)) self.partida.tablero.posicionar(ficha, columna=columna, fila=fila) self.celda_seleccionada.liberar() self._deseleccionarCelda() self.partida.finalizaMovimiento(celda) self.pasar_turno() self.partida.pilas.tareas.agregar(0.1, self.jugarPc) else: # no puede realizar el movimiento: self._deseleccionarCelda() self.movimiento_imposible()
def move(self, gn_current): #assert(gn_current.board().turn == True) if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) print 'setting position', move # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = self._maxd t0 = time.time() #print 'pos: ', self._pos #what is self._pos #depth is computation depth in tree #alpha is -inf #beta is positive inf #1 is 1 #func is the pickle model best_value, best_move = negamax(self._pos, depth, alpha, beta, 1, self._func) #print 'bestMove: ', best_move crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) #print 'crdn', crdn #print depth, best_value, crdn, time.time() - t0 self._pos = self._pos.move(best_move) print 'setting position', best_move #print 'crdn[0:2]', crdn[0:2] #print 'crdn[2:4]', crdn[2:4] #print 'bestMove', best_move crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): assert (gn_current.board().turn == 0) if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = self._maxd t0 = time.time() bb = pos_board_to_bitboard(self._pos.board) if args.multilayer: im = convert_bitboard_to_image_2(bb) else: im = convert_bitboard_to_image(bb) im = np.rollaxis(im, 2, 0) if args.elo_layer: im = np.append(im, elo_layer, axis=0) #print im.shape best_value, best_move = negamax(im, depth, alpha, beta, 1, maxm=self._maxm) best_move = (sunfish.parse(best_move[0:2]), sunfish.parse(best_move[2:4])) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) print depth, best_value, crdn, time.time() - t0 self._pos = self._pos.move(best_move) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, move: str): # We query the user until she enters a (pseudo) legal move. match = re.match('([a-h][1-8])' * 2, move) if match: move = sf.parse(match.group(1)), sf.parse(match.group(2)) else: return False if move in self.hist[-1].gen_moves(): self.hist.append(self.hist[-1].move(move)) # After our move we rotate the board and print it again. # This allows us to see the effect of our move. self.togglePlayer() self.lastmove = match.group(1) + match.group(2) return self.lastmove return False
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ board, color, castling, enpas, hclock, fclock = fen.split() board = re.sub("\d", (lambda m: "." * int(m.group(0))), board) board = " " * 21 + " ".join(board.split("/")[::-1]) + " " * 21 wc = ("Q" in castling, "K" in castling) bc = ("k" in castling, "q" in castling) ep = parse(enpas) if enpas != "-" else 0 pos = Position(board, 0, wc, bc, ep, 0) return pos if color == "w" else pos.rotate()
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ board, color, castling, enpas, hclock, fclock = fen.split() board = re.sub('\d', (lambda m: '.'*int(m.group(0))), board) board = ' '*21 + ' '.join(board.split('/')[::-1]) + ' '*21 wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = parse(enpas) if enpas != '-' else 0 pos = Position(board, 0, wc, bc, ep, 0) return pos if color == 'w' else pos.rotate()
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ board, color, castling, enpas, _hclock, _fclock = fen.split() board = re.sub(r"\d", (lambda m: "." * int(m.group(0))), board) board = " " * 19 + "\n " + "\n ".join(board.split("/")) + " \n" + " " * 19 wc = ("Q" in castling, "K" in castling) bc = ("k" in castling, "q" in castling) ep = sunfish.parse(enpas) if enpas != "-" else 0 score = sum(sunfish.pst[p][i] for i, p in enumerate(board) if p.isupper()) score -= sum(sunfish.pst[p.upper()][119 - i] for i, p in enumerate(board) if p.islower()) pos = sunfish.Position(board, score, wc, bc, ep, 0) return pos if color == "w" else pos.rotate()
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ board, color, castling, enpas, hclock, fclock = fen.split() board = re.sub('\d', (lambda m: '.'*int(m.group(0))), board) board = ' '*19+'\n ' + '\n '.join(board.split('/')) + ' \n'+' '*19 wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = sunfish.parse(enpas) if enpas != '-' else 0 score = sum(sunfish.pst[p][i] for i,p in enumerate(board) if p.isupper()) score -= sum(sunfish.pst[p.upper()][i] for i,p in enumerate(board) if p.islower()) pos = sunfish.Position(board, score, wc, bc, ep, 0) return pos if color == 'w' else pos.rotate()
def xboard(): """ Play as a black engine in the CECP/XBoard protocol """ pos = parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') while True: smove = input() if smove == 'quit': break elif smove == 'protover 2': print('feature myname="Sunfish" usermove=1 done=1') continue elif smove.startswith('usermove'): smove = smove[9:] m = parse(smove[0:2]), parse(smove[2:4]) pos = pos.move(m) # Respond m, _ = search(pos) print("move %s%s" % (render(119-m[0]), render(119-m[1]))) pos = pos.move(m) else: print("Didn't understand command '%s'" % smove) continue
def move(self, gn_current): assert(gn_current.board().turn == 0) if gn_current.move is not None: # Apply last_move crdn = str(gn_current.move) move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = self._maxd t0 = time.time() bb = pos_board_to_bitboard(self._pos.board) if args.multilayer: im = convert_bitboard_to_image_2(bb) else: im = convert_bitboard_to_image(bb) im = np.rollaxis(im,2,0) if args.elo_layer: im = np.append(im,elo_layer,axis=0) #print im.shape best_value, best_move = negamax(im, depth, alpha, beta, 1, maxm=self._maxm) best_move = (sunfish.parse(best_move[0:2]), sunfish.parse(best_move[2:4])) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) print depth, best_value, crdn, time.time() - t0 self._pos = self._pos.move(best_move) crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def move(self, gn_current): import sunfish assert(gn_current.board().turn == False) # Apply last_move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) t0 = time.time() move, score = sunfish.search(self._pos, maxn=self._maxn) print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119-move[0]) + sunfish.render(119 - move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def getMove(moveList): learnedModel = model currentBoardPosition = sunfish.Position(sunfish.initial, 0, (True,True), (True,True), 0, 0) #apply all moves in movelist to the currentBoardPosition player1 = True for move in moveList: if player1: formatedMove = (sunfish.parse(move[0:2]), sunfish.parse(move[2:4])) else: formatedMove = (119 - sunfish.parse(move[0:2]), 119 - sunfish.parse(move[2:4])) print 'formatedMove', formatedMove player1 = not(player1) currentBoardPosition = currentBoardPosition.move(formatedMove) # for depth in xrange(1, self._maxd+1): alpha = float('-inf') beta = float('inf') depth = 2 t0 = time.time() best_value, best_move = negamax(currentBoardPosition, depth, alpha, beta, 1, learnedModel) moveStandardFormat = sunfish.render(best_move[0]) + sunfish.render(best_move[1]) return moveStandardFormat
def parseFEN(self, fen, pst): board, color, castling, enpas, _hclock, _fclock = fen.split() board = re.sub(r'\d', (lambda m: '.' * int(m.group(0))), board) board = list(21 * ' ' + ' '.join(board.split('/')) + 21 * ' ') board[9::10] = ['\n'] * 12 #if color == 'w': board[::10] = ['\n']*12 #if color == 'b': board[9::10] = ['\n']*12 board = ''.join(board) wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = sunfish.parse(enpas) if enpas != '-' else 0 score = sum(pst[p][i] for i, p in enumerate(board) if p.isupper()) score -= sum(pst[p.upper()][119 - i] for i, p in enumerate(board) if p.islower()) pos = sunfish.Position(board, score, wc, bc, ep, 0) return pos if color == 'w' else pos.rotate()
def parseFEN(fen): """ Parses a string in Forsyth-Edwards Notation into a Position """ board, color, castling, enpas, _hclock, _fclock = fen.split() board = re.sub(r'\d', (lambda m: '.'*int(m.group(0))), board) board = list(21*' ' + ' '.join(board.split('/')) + 21*' ') board[9::10] = ['\n']*12 # if color == 'w': board[::10] = ['\n']*12 # if color == 'b': board[9::10] = ['\n']*12 board = ''.join(board) wc = ('Q' in castling, 'K' in castling) bc = ('k' in castling, 'q' in castling) ep = sunfish.parse(enpas) if enpas != '-' else 0 score = sum(sunfish.pst[p][i] for i, p in enumerate(board) if p.isupper()) def func(i, p): return sunfish.pst[p.upper()][119 - i] score -= sum(func(i, p) for i, p in enumerate(board) if p.islower()) pos = sunfish.Position(board, score, wc, bc, ep, 0) return pos if color == 'w' else pos.rotate()
def main(): md = MoveDetector('http://192.168.178.39/webcam/?action=stream') o = Octoprint(api_key=secrets.api_key) print('Welcome to 3d printer chess.') s = None while s != 'n' and s != 'y': s = input('Should we home the 3d printer? (y/n)\n') if s == 'y': o.home() print('Homing finished. Parking.') o.park() hist = [Position(initial, 0, (True,True), (True,True), 0, 0)] searcher = Searcher() print('Game started') while True: print_pos(hist[-1]) if hist[-1].score <= -MATE_LOWER: print('You lost') break print('Your move:\a') move = None while move not in hist[-1].gen_moves(): match = re.match('([a-h][1-8])'*2, md.getMove()) if match: move = parse(match.group(1)), parse(match.group(2)) else: print('Please enter a move like g8f6') hist.append(hist[-1].move(move)) print_pos(hist[-1].rotate()) if hist[-1].score <= -MATE_LOWER: print('You won') break start = time.time() for _depth, move, score in searcher.search(hist[-1], hist): if time.time() - start > 1: break if score == MATE_UPPER: print('Checkmate!') smove = render(119-move[0]) + render(119-move[1]) print('My move:', smove) hist.append(hist[-1].move(move)) #print(hist[-1][0]) xf,yf,xt,yt = parse_move(smove) capturing = not new_field_is_empty(xt, yt, hist) if capturing: pawn = is_pawn(xt,yt, hist, last_move=True) #print('Capturing pawn:', pawn) o.remove(xt,yt,pawn) pawn = is_pawn(xt,yt, hist) o.from_to(xf,yf,xt,yt, pawn=pawn)
def mparse(color, move): m = (sunfish.parse(move[0:2]), sunfish.parse(move[2:4])) return m if color == WHITE else (119 - m[0], 119 - m[1])
def mparse(color, move): m = (sunfish.parse(move[0:2]), sunfish.parse(move[2:4])) return m if color == WHITE else (119-m[0], 119-m[1])