def loadToModel(self, gameno, position=-1, model=None, quick_parse=True): if not model: model = GameModel() model.tags['Event'] = self._getTag(gameno, 'Event') model.tags['Site'] = self._getTag(gameno, 'Site') model.tags['Date'] = self._getTag(gameno, 'Date') model.tags['Round'] = self._getTag(gameno, 'Round') model.tags['White'], model.tags['Black'] = self.get_player_names( gameno) model.tags['WhiteElo'] = self._getTag(gameno, 'WhiteElo') model.tags['BlackElo'] = self._getTag(gameno, 'BlackElo') model.tags['Result'] = reprResult[self.get_result(gameno)] model.tags['ECO'] = self._getTag(gameno, "ECO") fenstr = self._getTag(gameno, "FEN") variant = self._getTag(gameno, "Variant") if variant and ("fischer" in variant.lower() or "960" in variant): from pychess.Variants.fischerandom import FRCBoard model.variant = FischerRandomChess model.boards = [FRCBoard(fenstr)] else: if fenstr: model.boards = [Board(fenstr)] else: model.boards = [Board(setup=True)] del model.moves[:] model.status = WAITING_TO_START model.reason = UNKNOWN_REASON error = None if quick_parse: movstrs = self._getMoves(gameno) for i, mstr in enumerate(movstrs): if position != -1 and model.ply >= position: break try: move = parseAny(model.boards[-1], mstr) except ParsingError, e: notation, reason, boardfen = e.args ply = model.boards[-1].ply if ply % 2 == 0: moveno = "%d." % (i / 2 + 1) else: moveno = "%d..." % (i / 2 + 1) errstr1 = _( "The game can't be read to end, because of an error parsing move %(moveno)s '%(notation)s'." ) % { 'moveno': moveno, 'notation': notation } errstr2 = _("The move failed because %s.") % reason error = LoadingError(errstr1, errstr2) break model.moves.append(move) model.boards.append(model.boards[-1].move(move))
def testAll(self): board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["d7"], cordDic["d5"])) for cord0, cord1 in moves: board = board.move(Move(Cord(cord0), Cord(cord1), board)) board.printPieces() # Not protected self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e4", color="R") ]), set(dsa.calculate_coordinate_in_danger(board, WHITE))) # protected by Queen, so no danger self.assertEqual(set([Cord("a8", color="Y"), Cord("h8", color="Y")]), set(dsa.calculate_coordinate_in_danger(board, BLACK))) # pawn go forward, no danger board = board.move(Move(Cord(E4), Cord(E5), board)) self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e5", color="Y") ]), set(dsa.calculate_coordinate_in_danger(board, WHITE))) # Should not recognize king board_king = Board(setup=True) dsa_king = DecisionSupportAlgorithm() dsa_king.set_foe_as_bot() dsa_king.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["f7"], cordDic["f5"]), (cordDic["d1"], cordDic["h5"])) for cord0, cord1 in moves: board_king = board_king.move( Move(Cord(cord0), Cord(cord1), board_king)) # board_king.printPieces() self.assertEqual( set([ Cord("a8", color="Y"), Cord("h8", color="Y"), Cord("f5", color="Y") ]), set(dsa.calculate_coordinate_in_danger(board_king, BLACK)))
def on_selection_changed(self, selection): model, iter = selection.get_selected() if iter is None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redrawCanvas() return path = self.gamelist.get_model().get_path(iter) gameno = self.gamelist.get_gameno(path) self.boardview.animation_lock.acquire() try: try: self.gamelist.chessfile.loadToModel(gameno, -1, self.gamemodel) except LoadingError as err: dialogue = Gtk.MessageDialog(type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, message_format=err.args[0]) if len(err.args) > 1: dialogue.format_secondary_text(err.args[1]) dialogue.connect("response", lambda dialogue, a: dialogue.hide()) dialogue.show() self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply finally: self.boardview.animation_lock.release() self.boardview.redrawCanvas() self.boardview.shown = self.gamelist.ply
def on_selection_changed(self, selection): model, iter = selection.get_selected() if iter is None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redrawCanvas() return path = self.persp.gamelist.get_model().get_path(iter) rec, ply = self.persp.gamelist.get_record(path) if rec is None: return try: self.persp.chessfile.loadToModel(rec, -1, self.gamemodel) except LoadingError as err: dialogue = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, message_format=err.args[0]) if len(err.args) > 1: dialogue.format_secondary_text(err.args[1]) dialogue.connect("response", lambda dialogue, a: dialogue.hide()) dialogue.show() self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply self.boardview.redrawCanvas() self.boardview.shown = ply if ply > 0 else self.persp.gamelist.ply
def testAttackedAndNotProtected(self): """ Testing what recognize the algorithm """ board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["d7"], cordDic["d5"])) for cord0, cord1 in moves: board = board.move(Move(Cord(cord0), Cord(cord1), board)) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) # Not protected self.assertEqual([Cord("e4", color="R")], coordinate_attacked) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, BLACK, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) # protected by Queen self.assertEqual([], coordinate_attacked) board = board.move(Move(Cord(E4), Cord(E5), board)) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) self.assertEqual([], coordinate_attacked)
def on_selection_changed(self, selection): iter = selection.get_selected()[1] if iter == None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redraw_canvas() return sel = self.list.get_model().get_path(iter)[0] if sel == self.lastSel: return self.lastSel = sel self.boardview.animationLock.acquire() try: try: self.chessfile.loadToModel(sel, -1, self.gamemodel) except LoadingError as e: d = Gtk.MessageDialog(type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, message_format=e.args[0]) d.format_secondary_text(e.args[1]) d.connect("response", lambda d, a: d.hide()) d.show() self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply last = self.gamemodel.ply finally: self.boardview.animationLock.release() self.boardview.redraw_canvas() self.boardview.shown = last self.shown_changed(self.boardview, last)
def __init__(self, subprocess, color, protover, md5): ProtocolEngine.__init__(self, subprocess, color, protover, md5) self.ids = {} self.options = {} self.optionsToBeSent = {} self.wtime = 60000 self.btime = 60000 self.incr = 0 self.moves = 0 self.timeHandicap = 1 self.ponderOn = False self.pondermove = None self.ignoreNext = False self.waitingForMove = False self.needBestmove = False self.bestmove_event = asyncio.Event() self.readyForStop = ( False) # keeps track of whether we already sent a 'stop' command self.multipvSetting = 1 # MultiPV option sent to the engine self.multipvExpected = ( 1) # Number of PVs expected (limited by number of legal moves) self.commands = collections.deque() self.gameBoard = Board( setup=True) # board at the end of all moves played self.board = Board(setup=True) # board to send the engine self.uciPosition = "startpos" self.uciPositionListsMoves = False self.analysis = [None] self.analysis_depth = None self.queue = asyncio.Queue() self.parse_line_task = create_task(self.parseLine(self.engine)) self.died_cid = self.engine.connect( "died", lambda e: self.queue.put_nowait("die")) self.invalid_move = None self.cids = [ self.connect_after("readyForOptions", self.__onReadyForOptions), self.connect_after("readyForMoves", self.__onReadyForMoves), ]
def __init__(self, subprocess, color, protover, md5): ProtocolEngine.__init__(self, subprocess, color, protover, md5) self.ids = {} self.options = {} self.optionsToBeSent = {} self.wtime = 60000 self.btime = 60000 self.incr = 0 self.moves = 0 self.timeHandicap = 1 self.moveLock = RLock() # none of the following variables should be changed or used in a # condition statement without holding the above self.moveLock self.ponderOn = False self.pondermove = None self.ignoreNext = False self.waitingForMove = False self.needBestmove = False self.readyForStop = False # keeps track of whether we already sent a 'stop' command self.multipvSetting = conf.get("multipv", 1) # MultiPV option sent to the engine self.multipvExpected = 1 # Number of PVs expected (limited by number of legal moves) self.commands = collections.deque() self.gameBoard = Board( setup=True) # board at the end of all moves played self.board = Board(setup=True) # board to send the engine self.uciPosition = "startpos" self.uciPositionListsMoves = False self.analysis = [None] self.returnQueue = Queue() self.line_cid = self.engine.connect("line", self.parseLine) self.died_cid = self.engine.connect("died", self.__die) self.invalid_move = None self.cids = [ self.connect("readyForOptions", self.__onReadyForOptions_before), self.connect_after("readyForOptions", self.__onReadyForOptions), self.connect_after("readyForMoves", self.__onReadyForMoves), ]
def _get_board(request: WSGIRequest) -> Board: """ This will eventually be fleshed out into accessing the Database """ game_id = request.GET.get("game_id") most_recent_move = _get_most_recent_move(game_id) most_recent_move.refresh_from_db() game_board = Board(setup=most_recent_move.post_move_fen) return game_board
def onSelectionChanged(self, selection): iter = selection.get_selected()[1] if iter == None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redrawCanvas() return path = self.list.get_model().get_path(iter) indices = path.get_indices() sel = indices[0] if sel == self.last_sel: return self.last_sel = sel self.boardview.animation_lock.acquire() try: try: self.chessfile.loadToModel(sel, -1, self.gamemodel) except LoadingError as err: dialogue = Gtk.MessageDialog(type=Gtk.MessageType.WARNING, \ buttons=Gtk.ButtonsType.OK, \ message_format=err.args[0]) dialogue.format_secondary_text(err.args[1]) dialogue.connect("response", lambda dialogue, a: dialogue.hide()) dialogue.show() if self.gamemodel.variant.variant == NORMALCHESS: radiobutton = self.widgets["playNormalRadio"] radiobutton.set_active(True) else: radiobutton = self.widgets["playVariant1Radio"] radiobutton.set_active(True) conf.set("ngvariant1", self.gamemodel.variant.variant) radiobutton.set_label("%s" % self.gamemodel.variant.name) if self.gamemodel.tags.get("TimeControl"): radiobutton = self.widgets["blitzRadio"] radiobutton.set_active(True) conf.set("ngblitz min", self.gamemodel.timemodel.minutes) conf.set("ngblitz gain", self.gamemodel.timemodel.gain) else: radiobutton = self.widgets["notimeRadio"] radiobutton.set_active(True) self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply last = self.gamemodel.ply finally: self.boardview.animation_lock.release() self.boardview.redrawCanvas() self.boardview.shown = last self.shownChanged(self.boardview, last)
def __onReadyForMoves(self, self_): self.returnQueue.put("ready") self.readyMoves = True self._newGame() # If we are an analyzer, this signal was already called in a different # thread, so we can safely block it. if self.mode in (ANALYZING, INVERSE_ANALYZING): if not self.board: self.board = Board(setup=True) self.putMove(self.board, None, None)
def test2(self): """ Test analyzing in promotion situations """ board = Board('5k2/PK6/8/8/8/6P1/6P1/8 w - - 1 48') self.analyzerA.setBoardList([board],[]) self.analyzerI.setBoardList([board],[]) self._testLine(self.engineA, self.analyzerA, board, "9. 1833 23 43872584 a8=Q+ Kf7 Qa2+ Kf6 Qd2 Kf5 g4+", ['a8=Q+','Kf7','Qa2+','Kf6','Qd2','Kf5','g4+'], 1833, "9.") self._testLine(self.engineI, self.analyzerI, board.switchColor(), "10. -1883 59 107386433 Kf7 a8=Q Ke6 Qa6+ Ke5 Qd6+ Kf5", ['Kf7','a8=Q','Ke6','Qa6+','Ke5','Qd6+','Kf5'], -1883, "10.")
def test1(self): """ Testing Board.move() on frc castling in non frc game """ board = Board(setup=True) moves = ((D2, D4), (G8, F6), (C2, C4), (G7, G6), (G2, G3), (F8, G7), (F1, G2), (E8, H8)) for cord0, cord1 in moves: print(cord0, cord1) board = board.move(Move(Cord(cord0), Cord(cord1), board)) board.printPieces() self.assertIsNone(board[Cord(E8)]) self.assertIsNone(board[Cord(H8)]) self.assertEqual(board[Cord(G8)].piece, Piece(BLACK, KING).piece) self.assertEqual(board[Cord(F8)].piece, Piece(BLACK, ROOK).piece)
def test1(self): """ Test analyzing in forced mate situations """ board = Board( 'B1n1n1KR/1r5B/6R1/2b1p1p1/2P1k1P1/1p2P2p/1P2P2P/3N1N2 w - - 0 1') self.analyzerA.setBoardList([board], []) self.analyzerI.setBoardList([board], []) self._testLine(self.engineA, self.analyzerA, board, "1. Mat1 0 1 Bxb7#", ['Bxb7#'], MATE_VALUE, "1.") # Notice, in the opposite situation there is no forced mate. Black can # do Bxe3 or Ne7+, but we just emulate a stupid analyzer not # recognizing this. self._testLine(self.engineI, self.analyzerI, board.switchColor(), "10. -Mat 2 35 64989837 Bd4 Bxb7#", ['Bd4', 'Bxb7#'], -MATE_VALUE, "10.")
def figure_out_previously_moved_pieces(request: WSGIRequest) -> JsonResponse: game_id = request.GET.get("game_id") opponent_color = WHITE if request.GET.get( "player_color") == WHITE_STR else BLACK most_recent_move = _get_most_recent_move(game_id) old_board = Board(setup=most_recent_move.pre_move_fen) old_move = _convert_SAN_str_to_move(most_recent_move.move_algebraic, old_board) current_board = old_board.move(old_move) from_coord, to_coord = _move_to_board_location(old_move) pieces_moved = [{"from_coord": from_coord, "to_coord": to_coord}] pieces_moved += _check_for_castle(old_move, opponent_color) return JsonResponse({ "moves": pieces_moved, "winner": check_if_game_over(board, game_id) })
def walk(node, path): if node.prev is None: # initial game board if variant == "Fischerandom": board = FRCBoard(setup=node.asFen(), lboard=node) elif variant == "Atomic": board = AtomicBoard(setup=node.asFen(), lboard=node) elif variant == "Crazyhouse": board = CrazyhouseBoard(setup=node.asFen(), lboard=node) elif variant == "Wildcastle": board = WildcastleBoard(setup=node.asFen(), lboard=node) elif variant == "Suicide": board = SuicideBoard(setup=node.asFen(), lboard=node) elif variant == "Losers": board = LosersBoard(setup=node.asFen(), lboard=node) elif variant == "Kingofthehill": board = KingOfTheHillBoard(setup=node.asFen(), lboard=node) else: board = Board(setup=node.asFen(), lboard=node) else: move = Move(node.lastMove) try: board = node.prev.pieceBoard.move(move, lboard=node) except: raise LoadingError( _("Invalid move."), "%s%s" % (move_count(node, black_periods=True), move)) if node.next is None: model.variations.append(path + [board]) else: walk(node.next, path + [board]) for child in node.children: if isinstance(child, list): if len(child) > 1: # non empty variation, go walk walk(child[1], list(path)) else: if not self.has_emt: self.has_emt = child.find("%emt") >= 0 if not self.has_eval: self.has_eval = child.find("%eval") >= 0
def test2(self): """ Test analyzing in promotion situations """ board = Board('5k2/PK6/8/8/8/6P1/6P1/8 w - - 1 48') self.analyzerA.setBoardList([board], []) self.analyzerI.setBoardList([board], []) async def coro(): await self._testLine( self.engineA, self.analyzerA, board, "9. 1833 23 43872584 a8=Q+ Kf7 Qa2+ Kf6 Qd2 Kf5 g4+", 94, ['a8=Q+', 'Kf7', 'Qa2+', 'Kf6', 'Qd2', 'Kf5', 'g4+'], 1833, "9.", "190750365") await self._testLine( self.engineI, self.analyzerI, board.switchColor(), "10. -1883 59 107386433 Kf7 a8=Q Ke6 Qa6+ Ke5 Qd6+ Kf5", 94, ['Kf7', 'a8=Q', 'Ke6', 'Qa6+', 'Ke5', 'Qd6+', 'Kf5'], -1883, "10.", "182010903") self.loop.run_until_complete(coro())
def testNotProtected(self): board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) # at the start of the game, only the two towers are not protected by other pieces coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) self.assertEqual(set([Cord("a1", color="Y"), Cord("h1", color="Y")]), set(coordinate_not_protected)) board = board.move( Move(Cord(cordDic["e2"]), Cord(cordDic["e4"]), board)) coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) # the pawn moved to e4 is now not protected self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e4", color="Y") ]), set(coordinate_not_protected)) board = board.move( Move(Cord(cordDic["d7"]), Cord(cordDic["d5"]), board)) # the black pawn attack the white pawn, it is not notProtected that will detect this case, # only the two towers are not protected coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) self.assertEqual(set([Cord("a1", color="Y"), Cord("h1", color="Y")]), set(coordinate_not_protected))
def on_selection_changed(self, selection): iter = selection.get_selected()[1] if iter == None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redraw_canvas() return sel = self.list.get_model().get_path(iter)[0] if sel == self.lastSel: return self.lastSel = sel self.boardview.animationLock.acquire() try: try: self.chessfile.loadToModel(sel, -1, self.gamemodel) except LoadingError, e: #TODO: Pressent this a little nicer print e self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply last = self.gamemodel.ply
def __init__(self, subprocess, color, protover, md5): ProtocolEngine.__init__(self, subprocess, color, protover, md5) self.features = { "ping": 0, "setboard": 0, "playother": 0, "san": 0, "usermove": 0, "time": 1, "draw": 1, "sigint": 0, "sigterm": 0, "reuse": 0, "analyze": 0, "myname": ', '.join(self.defname), "variants": None, "colors": 1, "ics": 0, "name": 0, "pause": 0, "nps": 0, "debug": 0, "memory": 0, "smp": 0, "egt": '', "option": '', "exclude": 0, "done": None, } self.supported_features = [ "ping", "setboard", "san", "usermove", "time", "draw", "sigint", "analyze", "myname", "variants", "colors", "pause", "done", "egt", "debug", "smp", "memory", "option" ] self.options = {} self.options["Ponder"] = { "name": "Ponder", "type": "check", "default": False } self.name = None self.board = Board(setup=True) # if self.engineIsInNotPlaying == True, engine is in "force" mode, # i.e. not thinking or playing, but still verifying move legality self.engineIsInNotPlaying = False self.engineIsAnalyzing = False self.movenext = False self.waitingForMove = False self.readyForMoveNowCommand = False self.timeHandicap = 1 self.lastping = 0 self.lastpong = 0 self.timeout = None self.returnQueue = Queue() self.engine.connect("line", self.parseLine) self.engine.connect("died", lambda e: self.returnQueue.put("del")) self.invalid_move = None self.funcQueue = Queue() self.optionQueue = [] self.boardLock = RLock() self.undoQueue = [] self.analysis_timer = None self.connect("readyForOptions", self.__onReadyForOptions_before) self.connect_after("readyForOptions", self.__onReadyForOptions) self.connect_after("readyForMoves", self.__onReadyForMoves)
from move.models import Moves from move.move import MoveState from user.user import get_user_info FROM_COORD = 0 TO_COORD = 1 BOARD_WIDTH = 8 STOCKFISH_ENGINE_LOC = "../../../mac_stockfish/stockfish-10-mac/Mac/stockfish-10-64" # STOCKFISH_ENGINE_LOC = "./mac_stockfish/stockfish-10-mac/Mac/stockfish-10-64" ONLINE_OPPONENT = "Online Opponent" AI = "Computer" AI_ID = 0 WHITE_STR = "White" BLACK_STR = "Black" global_board = Board(setup=True) @csrf_exempt def create_chess_game(request: WSGIRequest) -> JsonResponse: """ Takes the appropriate information from `request` and creates a new chess game Relevant attributes: user_id_1: str user_id_2: str white_user_id: str black_user_id: str id: int """
def setUp(self): self.board = Board()