예제 #1
0
def check_blund():
    print()

    if game.ply + 1 in values and game.ply in values:
        color = game.ply % 2
        oldmoves, oldscore = values[game.ply]
        moves, score = values[game.ply + 1]
        dif = score - oldscore
        if dif < -100 and color == WHITE:
            print("White blunder", dif)
            print("Should have done:",
                  ", ".join(listToSan(game.getBoardAtPly(game.ply), oldmoves)))
            print()
        elif dif > 100 and color == BLACK:
            print("Black blunder", dif)
            print("Should have done:",
                  ", ".join(listToSan(game.getBoardAtPly(game.ply), oldmoves)))
            print()

    movename = toSAN(game.getBoardAtPly(game.ply - 1),
                     game.getMoveAtPly(game.ply - 1))
    if game.ply % 2 == 1:
        move_suffix = ""
    else:
        move_suffix = "..."
    print("Considering %d%s %s " % (
        (game.ply + 1) // 2,
        move_suffix,
        movename,
    ),
          end=' ')
    game.undoMoves(1)
예제 #2
0
 def shown_changed (self, board, shown):
     self.openings = getOpenings(self.board.model.getBoardAtPly(shown))
     self.openings.sort(lambda a, b: sum(b[1:])-sum(a[1:]))
     
     self.board.bluearrow = None
     self.store.clear()
     
     if not self.openings and self.sw.get_child() == self.tv:
         self.sw.remove(self.tv)
         label = gtk.Label(_("In this position,\nthere is no book move."))
         label.set_property("yalign",0.1)
         self.sw.add_with_viewport(label)
         self.sw.get_child().set_shadow_type(gtk.SHADOW_NONE)
         self.sw.show_all()
         return
     
     if self.openings and self.sw.get_child() != self.tv:
         self.sw.remove(self.sw.get_child())
         self.sw.add(self.tv)
     
     i = 0
     for move, wins, draws, loses in self.openings:
         games = wins+draws+loses
         if not games: continue
         wins, draws, loses = \
                 map(lambda x: x/float(games), (wins, draws, loses))
         b = self.board.model.getBoardAtPly(shown)
         if conf.get("figuresInNotation", False):
             move = toFAN(b, parseSAN(b, move))
         else:
             move = toSAN(b, parseSAN(b, move), True)
         self.store.append ([move, str(games), (wins,draws,loses)])
예제 #3
0
    def on_analyze(self, engine, analysis):
        if self.boardview.animating:
            return

        if self.boardview.model.isPlayingICSGame():
            return

        if not self.active:
            return

        is_FAN = conf.get("figuresInNotation", False)

        for i, line in enumerate(analysis):
            if line is None:
                self.store[self.path + (i, )] = self.textOnlyRow("")
                continue

            board0 = self.engine.board
            board = board0.clone()

            movstrs, score, depth = line
            try:
                pv = listToMoves(board, movstrs, validate=True)
            except ParsingError as e:
                # ParsingErrors may happen when parsing "old" lines from
                # analyzing engines, which haven't yet noticed their new tasks
                log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" %
                          (' '.join(movstrs), e))
                return
            except:
                return

            move = None
            if pv:
                move = pv[0]

            ply0 = board.ply if self.mode == HINT else board.ply + 1
            counted_pv = []
            for j, pvmove in enumerate(pv):
                ply = ply0 + j
                if ply % 2 == 0:
                    mvcount = "%d." % (ply / 2 + 1)
                elif j == 0:
                    mvcount = "%d..." % (ply / 2 + 1)
                else:
                    mvcount = ""
                counted_pv.append("%s%s" %
                                  (mvcount, toFAN(board, pvmove)
                                   if is_FAN else toSAN(board, pvmove, True)))
                board = board.move(pvmove)

            goodness = (min(max(score, -250), 250) + 250) / 500.0
            if self.engine.board.color == BLACK:
                score = -score

            self.store[self.path + (i, )] = [
                (board0, move, pv),
                (prettyPrintScore(score, depth), 1, goodness), 0, False,
                " ".join(counted_pv), False, False
            ]
예제 #4
0
def record_move(board: Board, move: Move, game_id: int):
    most_recent_move = _get_most_recent_move(game_id)
    move_state = MoveState()
    move_state.set_state_from_prev_move(most_recent_move)
    move_state.post_move_fen = board.asFen()
    move_state.set_move(toSAN(board, move))
    add_move_state_to_database(move_state)
예제 #5
0
파일: bookPanel.py 프로젝트: JKrame/pychess
    def on_analyze(self, engine, analysis):
        if self.boardview.animating:
            return

        if self.boardview.model.isPlayingICSGame():
            return

        if not self.active:
            return

        is_FAN = conf.get("figuresInNotation", False)

        for i, line in enumerate(analysis):
            if line is None:
                self.store[self.path + (i, )] = self.textOnlyRow("")
                continue

            board0 = self.engine.board
            board = board0.clone()

            movstrs, score, depth = line
            try:
                pv = listToMoves(board, movstrs, validate=True)
            except ParsingError as e:
                # ParsingErrors may happen when parsing "old" lines from
                # analyzing engines, which haven't yet noticed their new tasks
                log.debug(
                    "__parseLine: Ignored (%s) from analyzer: ParsingError%s" %
                    (' '.join(movstrs), e))
                return
            except:
                return

            move = None
            if pv:
                move = pv[0]

            ply0 = board.ply if self.mode == HINT else board.ply + 1
            counted_pv = []
            for j, pvmove in enumerate(pv):
                ply = ply0 + j
                if ply % 2 == 0:
                    mvcount = "%d." % (ply / 2 + 1)
                elif j == 0:
                    mvcount = "%d..." % (ply / 2 + 1)
                else:
                    mvcount = ""
                counted_pv.append("%s%s" % (mvcount, toFAN(
                    board, pvmove) if is_FAN else toSAN(board, pvmove, True)))
                board = board.move(pvmove)

            goodness = (min(max(score, -250), 250) + 250) / 500.0
            if self.engine.board.color == BLACK:
                score = -score

            self.store[self.path + (i, )] = [
                (board0, move, pv),
                (prettyPrintScore(score, depth), 1, goodness), 0, False,
                " ".join(counted_pv), False, False
            ]
예제 #6
0
    def __addMove(self, game, ply):
        # print "Am I doing anything?"
        row, view, other = self._ply_to_row_col_other(ply)

        if conf.get("figuresInNotation", False):
            notat = toFAN(
                game.getBoardAtPly(ply - 1), game.getMoveAtPly(ply - 1))
        else:
            notat = toSAN(
                game.getBoardAtPly(ply - 1),
                game.getMoveAtPly(ply - 1),
                localRepr=True)

        # Test if the row is 'filled'
        if len(view.get_model()) == len(self.numbers.get_model()):
            num = str((ply + 1) // 2) + "."
            self.numbers.get_model().append([num])

        # Test if the move is black first move. This will be the case if the
        # game was loaded from a fen/epd starting at black
        if view == self.right and len(view.get_model()) == len(other.get_model(
        )):
            self.left.get_model().append([""])

        view.get_model().append([notat])
예제 #7
0
    def shown_changed(self, board, shown):
        self.openings = getOpenings(self.board.model.getBoardAtPly(shown))
        self.openings.sort(lambda a, b: sum(b[1:]) - sum(a[1:]))

        self.board.bluearrow = None
        self.store.clear()

        if not self.openings and self.sw.get_child() == self.tv:
            self.sw.remove(self.tv)
            label = gtk.Label(_("In this position,\nthere is no book move."))
            label.set_property("yalign", 0.1)
            self.sw.add_with_viewport(label)
            self.sw.get_child().set_shadow_type(gtk.SHADOW_NONE)
            self.sw.show_all()
            return

        if self.openings and self.sw.get_child() != self.tv:
            self.sw.remove(self.sw.get_child())
            self.sw.add(self.tv)

        i = 0
        for move, wins, draws, loses in self.openings:
            games = wins + draws + loses
            if not games: continue
            wins, draws, loses = \
                    map(lambda x: x/float(games), (wins, draws, loses))
            b = self.board.model.getBoardAtPly(shown)
            if conf.get("figuresInNotation", False):
                move = toFAN(b, parseSAN(b, move))
            else:
                move = toSAN(b, parseSAN(b, move), True)
            self.store.append([move, str(games), (wins, draws, loses)])
예제 #8
0
 def figuresInNotationCallback (none):
     game = self.boardview.model
     for board, move in zip(game.variations[0], game.moves):
         if conf.get("figuresInNotation", False):
             notat = toFAN(board, move)
         else: notat = toSAN(board, move, True)
         row, col, other = self._ply_to_row_col_other(board.ply+1)
         iter = col.get_model().get_iter((row,))
         col.get_model().set(iter, 0, notat)
예제 #9
0
 def getMoveText(column, cell, store, iter, data):
     board, move, pv = store[iter][0]
     if not move:
         cell.set_property("text", "")
     else:
         if conf.get("figuresInNotation", False):
             cell.set_property("text", toFAN(board, move))
         else:
             cell.set_property("text", toSAN(board, move, True))
예제 #10
0
파일: bookPanel.py 프로젝트: JKrame/pychess
 def getMoveText(column, cell, store, iter, data):
     board, move, pv = store[iter][0]
     if not move:
         cell.set_property("text", "")
     else:
         if conf.get("figuresInNotation", False):
             cell.set_property("text", toFAN(board, move))
         else:
             cell.set_property("text", toSAN(board, move, True))
예제 #11
0
 def figuresInNotationCallback(none):
     game = self.boardview.model
     for board, move in zip(game.variations[0], game.moves):
         if conf.get("figuresInNotation", False):
             notat = toFAN(board, move)
         else:
             notat = toSAN(board, move, True)
         row, col, other = self._ply_to_row_col_other(board.ply + 1)
         iter = col.get_model().get_iter((row, ))
         col.get_model().set(iter, 0, notat)
예제 #12
0
 def __usermove (self, board, move):
     if self.features["usermove"]:
         self.engine.write("usermove ")
     
     if self.features["san"]:
         print(toSAN(board, move), file=self.engine)
     else:
         cn = CASTLE_KK
         if board.variant == FISCHERRANDOMCHESS:
             cn = CASTLE_SAN
         print(toAN(board, move, short=True, castleNotation=cn), file=self.engine)
예제 #13
0
 def __usermove (self, board, move):
     if self.features["usermove"]:
         self.engine.write("usermove ")
     
     if self.features["san"]:
         print(toSAN(board, move), file=self.engine)
     else:
         cn = CASTLE_KK
         if board.variant == FISCHERRANDOMCHESS:
             cn = CASTLE_SAN
         print(toAN(board, move, short=True, castleNotation=cn), file=self.engine)
    def add_move(self, gamemodel, ply):
        if ply == gamemodel.lowply:
            self.store.append([
                "%4s." % gamemodel.lowply,
                "1234567",
                "1234567",
                0,
                self.get_background_rgba(),
                self.get_background_rgba(),
            ])
            return

        if self.figuresInNotation:
            notat = toFAN(gamemodel.getBoardAtPly(ply - 1),
                          gamemodel.getMoveAtPly(ply - 1))
        else:
            notat = toSAN(
                gamemodel.getBoardAtPly(ply - 1),
                gamemodel.getMoveAtPly(ply - 1),
                localRepr=True,
            )

        row, column = self.ply_to_row_col(ply)

        if len(self.store) - 1 < row:
            mvcount = "%s." % ((ply + 1) // 2)
            if column == self.white_column:
                self.store.append([
                    mvcount,
                    notat,
                    "",
                    row,
                    self.get_background_rgba(),
                    self.get_background_rgba(),
                ])
            else:
                self.store.append([
                    mvcount,
                    "",
                    notat,
                    row,
                    self.get_background_rgba(),
                    self.get_background_rgba(),
                ])
        else:
            treeiter = self.store.get_iter(Gtk.TreePath(row))
            col = 1 if column == self.white_column else 2
            self.store.set_value(treeiter, col, notat)
예제 #15
0
    def on_analyze(self, engine, analysis):
        m = self.boardview.model
        if m.isPlayingICSGame():
            return

        if not self.active:
            return

        is_FAN = conf.get("figuresInNotation", False)

        for i, line in enumerate(analysis):
            if line is None:
                self.store[self.path + (i, )] = self.textOnlyRow("")
                continue

            pv, score, depth = line
            move = None
            if pv:
                move = pv[0]

            board0 = self.engine.board
            board = board0.clone()
            ply0 = board.ply if self.mode == HINT else board.ply + 1
            counted_pv = []
            for j, pvmove in enumerate(pv):
                ply = ply0 + j
                if ply % 2 == 0:
                    mvcount = "%d." % (ply / 2 + 1)
                elif j == 0:
                    mvcount = "%d..." % (ply / 2 + 1)
                else:
                    mvcount = ""
                counted_pv.append("%s%s" % (mvcount, toFAN(
                    board, pvmove) if is_FAN else toSAN(board, pvmove, True)))
                board = board.move(pvmove)

            # TODO make a move's "goodness" relative to other moves or past scores
            goodness = (min(max(score, -250), 250) + 250) / 500.0
            if self.engine.board.color == BLACK:
                score = -score

            self.store[self.path + (i, )] = [
                (board0, move, pv),
                (prettyPrintScore(score, depth), 1, goodness), 0, False,
                " ".join(counted_pv), False, False
            ]
    def on_scored(self, board, endings):
        m = self.boardview.model

        if board != self.board.board:
            return

        for move, result, depth in endings:
            if result == DRAW:
                result = (_("Draw"), 1, 0.5)
                details = ""
            elif (result == WHITEWON) ^ (self.board.color == WHITE):
                result = (_("Loss"), 1, 0.0)
                details = _("Mate in %d") % depth
            else:
                result = (_("Win"), 1, 1.0)
                details = _("Mate in %d") % depth

            if m.practice_game or m.lesson_game:
                m.hint = "%s %s %s" % (
                    toSAN(self.board, move, True),
                    result[0],
                    details,
                )
                return

            if m.isPlayingICSGame():
                return

            self.store.append(
                self.parent,
                [(self.board, move, None), result, 0, False, details, False, False],
            )

        self.tv.expand_row(Gtk.TreePath(self.path), False)

        if self.auto_activate:
            path = None
            for i, row in enumerate(self.store):
                if row[4] == self.name:
                    path = Gtk.TreePath.new_from_indices((i, 0))
                    break
            if path is not None:
                self.row_activated(
                    self.tv.get_model().get_iter(path), m, from_gui=False
                )
예제 #17
0
        def figuresInNotationCallback(none):
            game = self.boardview.model
            if game.lesson_game:
                return

            for i, move in enumerate(game.moves):
                board = game.variations[0][i]
                ply = game.lowply + i + 1
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)

                row, column = self.ply_to_row_col(ply)

                col = 2 if column == self.black_column else 1
                treeiter = self.store.get_iter(Gtk.TreePath(row))
                self.store.set_value(treeiter, col, notat)
예제 #18
0
        def figuresInNotationCallback(none):
            game = self.boardview.model
            if game.lesson_game:
                return

            for i, move in enumerate(game.moves):
                board = game.variations[0][i]
                ply = game.lowply + i + 1
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)

                row, column = self.ply_to_row_col(ply)

                col = 2 if column == self.black_column else 1
                treeiter = self.store.get_iter(Gtk.TreePath(row))
                self.store.set_value(treeiter, col, notat)
예제 #19
0
def check_blund():
    print
    
    if game.ply+1 in values and game.ply in values:
        color = game.ply % 2
        oldmoves, oldscore = values[game.ply]
        moves, score = values[game.ply+1]
        dif = score-oldscore
        if dif < -100 and color == WHITE:
            print "White blunder", dif
            print "Should have done:", ", ".join(listToSan(game.getBoardAtPly(game.ply),oldmoves))
            print
        elif dif > 100 and color == BLACK:
            print "Black blunder", dif
            print "Should have done:", ", ".join(listToSan(game.getBoardAtPly(game.ply),oldmoves))
            print
    
    movename = toSAN(game.getBoardAtPly(game.ply-1),game.getMoveAtPly(game.ply-1))
    print "Considering", game.ply//2+1, movename, " ",
    game.undoMoves(1)
예제 #20
0
    def add_move(self, gamemodel, ply):
        if ply == gamemodel.lowply:
            self.store.append(["%4s." % gamemodel.lowply, "1234567", "1234567", 0, self.get_background_rgba(), self.get_background_rgba()])
            return

        if conf.get("figuresInNotation", False):
            notat = toFAN(gamemodel.getBoardAtPly(ply - 1), gamemodel.getMoveAtPly(ply - 1))
        else:
            notat = toSAN(gamemodel.getBoardAtPly(ply - 1), gamemodel.getMoveAtPly(ply - 1), localRepr=True)

        row, column = self.ply_to_row_col(ply)

        if len(self.store) - 1 < row:
            mvcount = "%s." % ((ply + 1) // 2)
            if column == self.white_column:
                self.store.append([mvcount, notat, "", row, self.get_background_rgba(), self.get_background_rgba()])
            else:
                self.store.append([mvcount, "", notat, row, self.get_background_rgba(), self.get_background_rgba()])
        else:
            treeiter = self.store.get_iter(Gtk.TreePath(row))
            col = 1 if column == self.white_column else 2
            self.store.set_value(treeiter, col, notat)
예제 #21
0
def check_blund():
    print

    if game.ply + 1 in values and game.ply in values:
        color = game.ply % 2
        oldmoves, oldscore = values[game.ply]
        moves, score = values[game.ply + 1]
        dif = score - oldscore
        if dif < -100 and color == WHITE:
            print "White blunder", dif
            print "Should have done:", ", ".join(
                listToSan(game.getBoardAtPly(game.ply), oldmoves))
            print
        elif dif > 100 and color == BLACK:
            print "Black blunder", dif
            print "Should have done:", ", ".join(
                listToSan(game.getBoardAtPly(game.ply), oldmoves))
            print

    movename = toSAN(game.getBoardAtPly(game.ply - 1),
                     game.getMoveAtPly(game.ply - 1))
    print "Considering", game.ply // 2 + 1, movename, " ",
    game.undoMoves(1)
예제 #22
0
    def on_scored(self, board, endings):
        m = self.boardview.model

        if board != self.board.board:
            return

        for move, result, depth in endings:
            if result == DRAW:
                result = (_("Draw"), 1, 0.5)
                details = ""
            elif (result == WHITEWON) ^ (self.board.color == WHITE):
                result = (_("Loss"), 1, 0.0)
                details = _("Mate in %d") % depth
            else:
                result = (_("Win"), 1, 1.0)
                details = _("Mate in %d") % depth

            if m.practice_game or m.lesson_game:
                m.hint = "%s %s %s" % (toSAN(self.board, move, True), result[0], details)
                return

            if m.isPlayingICSGame():
                return

            self.store.append(self.parent, [(self.board, move, None), result,
                                            0, False, details, False, False])

        self.tv.expand_row(Gtk.TreePath(self.path), False)

        if self.auto_activate:
            path = None
            for i, row in enumerate(self.store):
                if row[4] == self.name:
                    path = Gtk.TreePath.new_from_indices((i, 0))
                    break
            if path is not None:
                self.row_activated(self.tv.get_model().get_iter(path), m, from_gui=False)
예제 #23
0
파일: blunders.py 프로젝트: fowode/pychess
def check_blund():
    print()
    
    if game.ply+1 in values and game.ply in values:
        color = game.ply % 2
        oldmoves, oldscore = values[game.ply]
        moves, score = values[game.ply+1]
        dif = score-oldscore
        if dif < -100 and color == WHITE:
            print("White blunder", dif)
            print("Should have done:", ", ".join(listToSan(game.getBoardAtPly(game.ply),oldmoves)))
            print()
        elif dif > 100 and color == BLACK:
            print("Black blunder", dif)
            print("Should have done:", ", ".join(listToSan(game.getBoardAtPly(game.ply),oldmoves)))
            print()
    
    movename = toSAN(game.getBoardAtPly(game.ply-1),game.getMoveAtPly(game.ply-1))
    if game.ply % 2 == 1:
        move_suffix = ""
    else:
        move_suffix = "..."
    print("Considering %d%s %s " % ((game.ply+1)//2, move_suffix, movename,), end=' ')
    game.undoMoves(1)
예제 #24
0
    def __addMove(self, game, ply):
        # print "Am I doing anything?"
        row, view, other = self._ply_to_row_col_other(ply)

        if conf.get("figuresInNotation", False):
            notat = toFAN(game.getBoardAtPly(ply - 1),
                          game.getMoveAtPly(ply - 1))
        else:
            notat = toSAN(game.getBoardAtPly(ply - 1),
                          game.getMoveAtPly(ply - 1),
                          localRepr=True)

        # Test if the row is 'filled'
        if len(view.get_model()) == len(self.numbers.get_model()):
            num = str((ply + 1) // 2) + "."
            self.numbers.get_model().append([num])

        # Test if the move is black first move. This will be the case if the
        # game was loaded from a fen/epd starting at black
        if view == self.right and len(view.get_model()) == len(
                other.get_model()):
            self.left.get_model().append([""])

        view.get_model().append([notat])
예제 #25
0
def load (file):
    files = []
    inTags = False
    for line in file:
        if FILESMAX and len(files) > FILESMAX: break
    
        line = line.lstrip()
        if not line: continue
        elif line.startswith("%"): continue
        
        if line.startswith("["):
            if not inTags:
                files.append(["",""])
                inTags = True
            files[-1][0] += line
        
        else:
            inTags = False
            files[-1][1] += line
    
    history = History(False)
    max = str(len(files))
    start = time()
    for i, myFile in enumerate(files):
        number = str(i).rjust(len(max))
        procent = ("%.1f%%" % (i/float(len(files))*100)).rjust(4)
        if i == 0:
            estimation = "N/A etr"
            speed = "N/A g/s"
        else:
            s = round((time()-start)/i*(len(files)-i))
            estimation = ("%d:%02d etr" % (s / 60, s % 60)).rjust(5)
            speed = "%.2f g/s" % (i/(time()-start))
        print "%s/%s: %s - %s (%s)" % (number, max, procent, estimation, speed)
        try:
            tags = dict(tagre.findall(myFile[0]))
            if not tags["Result"] in ("1/2-1/2", "1-0", "0-1"):
                continue
            moves = comre.sub("", myFile[1])
            moves = stripBrackets(moves)
            moves = movre.findall(moves+" ")
            if moves[-1] in ("*", "1/2-1/2", "1-0", "0-1"):
                del moves[-1]
        except:
            # Could not parse game
            continue
        
        mcatch = []
        if MAXMOVES: moves = moves[:MAXMOVES]
        for move in moves:
            try:
                m = parseSAN(history,move)
            except:
                continue
            epd = fen(history[-1])
            res = resultDic[tags["Result"]]
            if epd.endswith("b"): res = 2-res
            history.add(m, False)
            yield epd, toSAN(history[-2], history[-1], history.moves[-1]), res
            mcatch.append(m)
        history.reset(False)
        for move in mcatch:
            movePool.add(move)
        del mcatch[:]
예제 #26
0
파일: bookPanel.py 프로젝트: fowode/pychess
    def on_analyze (self, engine, analysis):
        m = self.boardview.model
        if m.isPlayingICSGame():
            return

        if not self.active:
            return

        is_FAN = conf.get("figuresInNotation", False)
        
        for i, line in enumerate(analysis):
            if line is None:
                self.store[self.path + (i,)] = self.textOnlyRow("")
                continue
                
            pv, score, depth = line
            move = None
            if pv:
                move = pv[0]

            board0 = self.engine.board
            board = board0.clone()
            ply0 = board.ply if self.mode == HINT else board.ply+1
            counted_pv = []
            for j, pvmove in enumerate(pv):
                ply = ply0 + j
                if ply % 2 == 0:
                    mvcount = "%d." % (ply/2+1)
                elif j==0:
                    mvcount = "%d..." % (ply/2+1)
                else:
                    mvcount = ""
                counted_pv.append("%s%s" % (mvcount, toFAN(board, pvmove) if is_FAN else toSAN(board, pvmove, True)))
                board = board.move(pvmove)

            # TODO make a move's "goodness" relative to other moves or past scores
            goodness = (min(max(score, -250), 250) + 250) / 500.0
            if self.engine.board.color == BLACK:
                score = -score
            
            self.store[self.path + (i,)] = [(board0, move, pv), (prettyPrintScore(score, depth), 1, goodness), 0, False, " ".join(counted_pv), False, False]