コード例 #1
0
ファイル: ai.py プロジェクト: KeivanR/chess
    def move(self, table, last, still, data_hist):
        if self.level == -1:
            allrules = pieces.allrules_ek(table, last, still)
            return allrules[0]
        elif self.level == 0:
            allrules = pieces.allrules_ek(table, last, still)
            return random.choice(allrules)
        else:
            if last is None:
                color = 1
            else:
                color = -table[pieces.xy(last[1])[0]][pieces.xy(
                    last[1])[1]] / np.abs(table[pieces.xy(
                        last[1])[0]][pieces.xy(last[1])[1]])
            if self.tree:
                res = rec_sum_tree(table,
                                   self.node,
                                   last,
                                   still,
                                   color,
                                   self.level - 1,
                                   noha=0,
                                   noha_lim=self.noha_lim)
                self.update_tree(res[0])
            else:
                res = rec_sum(table,
                              last,
                              still,
                              data_hist,
                              color,
                              self.level - 1,
                              noha=0,
                              noha_lim=self.noha_lim,
                              first_layer=True)

            print('AI(', color, ') assessment: ', res[1])
            return res[0]
コード例 #2
0
ファイル: ai.py プロジェクト: KeivanR/chess
def rec_sum(table,
            last,
            still,
            data_hist,
            color,
            k,
            noha,
            noha_lim,
            first_layer=False):
    shine_mode = first_layer
    check_repet = first_layer
    allr = pieces.allrules_ek(table, last, still)
    val = []
    if len(allr) == 0:
        if pieces.exposed_king(table, last, still, no_move=True):
            return [None, -100 * color]
        else:
            return [None, 0]
    if noha == noha_lim:
        return [None, sum_value(table)]
    if k == 0:
        for m in allr:
            still2 = still[:]
            table2 = pieces.move(table,
                                 m.split()[0],
                                 m.split()[1],
                                 still2,
                                 real=False)
            val.append(sum_value(table2))
        val = np.asarray(val)
        if color > 0:
            return [
                allr[np.random.choice(np.flatnonzero(val == max(val)))],
                max(val)
            ]
        else:
            return [
                allr[np.random.choice(np.flatnonzero(val == min(val)))],
                min(val)
            ]
    else:
        for m in allr:
            still2 = still[:]
            table2 = pieces.move(table,
                                 m.split()[0],
                                 m.split()[1],
                                 still2,
                                 real=False)
            if check_repet and repet(table2, data_hist, rep_lim=2):
                val.append(0)
            else:
                if first_layer or sum_value(table2) == sum_value(table):
                    rs = rec_sum(table2,
                                 [m.split()[0], m.split()[1]], still2, None,
                                 -color, k - 1, noha + 1, noha_lim)
                else:
                    rs = rec_sum(table2,
                                 [m.split()[0], m.split()[1]], still2, None,
                                 -color, k - 1, noha, noha_lim)
                val.append(rs[1])

        val = np.asarray(val)
        if not shine_mode:
            if color > 0:
                return [
                    allr[np.random.choice(np.flatnonzero(val == max(val)))],
                    max(val)
                ]
            else:
                return [
                    allr[np.random.choice(np.flatnonzero(val == min(val)))],
                    min(val)
                ]
        shine = []
        allr = np.asarray(allr)
        if color > 0:
            allrmax = allr[np.flatnonzero(val == max(val))]
            for m in allrmax:
                still2 = still[:]
                table2 = pieces.move(table,
                                     m.split()[0],
                                     m.split()[1],
                                     still2,
                                     real=False)
                if pieces.iscastle(m, table):
                    return [m, max(val)]
                shine.append(pieces.allrules_ek_shine(table2, last, still2))
            shine = np.asarray(shine)
            return [
                allrmax[np.random.choice(np.flatnonzero(shine == max(shine)))],
                max(val)
            ]
        else:
            allrmin = allr[np.flatnonzero(val == min(val))]
            for m in allrmin:
                still2 = still[:]
                table2 = pieces.move(table,
                                     m.split()[0],
                                     m.split()[1],
                                     still2,
                                     real=False)
                if pieces.iscastle(m, table):
                    return [m, min(val)]
                shine.append(pieces.allrules_ek_shine(table2, last, still2))
            shine = np.asarray(shine)

            return [
                allrmin[np.random.choice(np.flatnonzero(shine == max(shine)))],
                min(val)
            ]
コード例 #3
0
ファイル: gui.py プロジェクト: KeivanR/chess
    def start_game(self, option):
        self.winfo_toplevel().title("Keivchess")
        self.hist = []
        self.data_hist = []
        self.hist_time = 0
        self.checkmate = 0
        self.option = option
        self.a = None
        self.last = None
        self.still = [1, 1, 1, 1]
        self.taken = []
        talking = 0
        if option != 'Two players':
            self.comp = ai.Keivchess(self.c1[0], self.c1[1])
        if option == 'Two computers':
            self.comp = [
                ai.Keivchess(self.c1[0], self.c1[1]),
                ai.Keivchess(self.c2[0], self.c2[1])
            ]
        if option == 'Play black' or option == 'Blindfold black':
            self.chess_up = -1
        else:
            self.chess_up = 1
        self.cb = pieces.Chessboard()
        self.cb.white_init()
        self.cb.black_init()
        self.bkg = Image.open(constants.chessboard_path[constants.os_name])
        render = ImageTk.PhotoImage(self.bkg)
        img = Label(self, image=render)
        img.image = render
        img.grid(row=0, column=0)
        self.display_pieces(self.cb.table, to=self.chess_up)
        self.update()
        if option == 'Play black' or option == 'Blindfold black':
            cmove = self.comp.move(self.cb.table, self.last, self.still,
                                   self.data_hist).split()
            s = np.sum(self.cb.table)
            self.cb.table = pieces.move(self.cb.table, cmove[0], cmove[1],
                                        self.still)
            if ai.repet(self.cb.table, self.data_hist):
                self.checkmate = 1
            self.add_taken(s - np.sum(self.cb.table))
            self.display_pieces(self.cb.table, to=self.chess_up)
            self.last = cmove
            self.show_last()
            render = ImageTk.PhotoImage(self.bkg)
            img = Label(self, image=render)
            img.image = render
            img.grid(row=0, column=0)
            self.update()
            if option == 'Blindfold black':
                if talking:
                    blind.engine.say(cmove[0] + ' to ' + cmove[1])
                    blind.engine.runAndWait()
                print(cmove[0] + ' ' + cmove[1])
        if 'Blindfold' in self.option:
            turn = 0
            while not self.checkmate:
                bmove = [0]
                allrules = pieces.allrules_ek(self.cb.table, self.last,
                                              self.still)
                attempt = 0
                if talking:
                    while attempt < 4 and (len(bmove) != 2 or bmove[0] + ' ' +
                                           bmove[1] not in allrules):
                        blind.engine.say("Say a valid move")
                        blind.engine.runAndWait()
                        with blind.mic as source:
                            audio = blind.r.listen(source)
                        try:
                            bmove = blind.r.recognize_google(
                                audio).lower().split(' to ')
                            if len(bmove) == 1:
                                bmove = bmove.split()
                        except:
                            bmove = [0]
                            attempt -= 1
                        print(bmove)
                        attempt += 1
                    if attempt == 4:
                        blind.engine.say(
                            "I can't understand your accent, write down your move, you prick!"
                        )
                        blind.engine.runAndWait()
                if not talking or attempt == 4:
                    while (len(bmove) != 2
                           or bmove[0] + ' ' + bmove[1] not in allrules):
                        bmove = input("Move: ").split()
                if talking:
                    blind.engine.say("You chose " + bmove[0] + ' to ' +
                                     bmove[1])
                    blind.engine.runAndWait()
                s = np.sum(self.cb.table)
                self.cb.table = pieces.move(self.cb.table, bmove[0], bmove[1],
                                            self.still)
                if ai.repet(self.cb.table, self.data_hist):
                    self.checkmate = 1
                self.add_taken(s - np.sum(self.cb.table))
                self.last = bmove
                self.display_pieces(self.cb.table, to=self.chess_up)
                self.update()
                start = time.time()
                cmove = self.comp.move(self.cb.table, self.last, self.still,
                                       self.data_hist).split()
                print(int(1000 * float(time.time() - start)) / 1000, 's')
                s = np.sum(self.cb.table)
                self.cb.table = pieces.move(self.cb.table, cmove[0], cmove[1],
                                            self.still)
                if ai.repet(self.cb.table, self.data_hist):
                    self.checkmate = 1
                self.add_taken(s - np.sum(self.cb.table))
                self.last = cmove
                self.display_pieces(self.cb.table, to=self.chess_up)

                allrules = pieces.allrules_ek(self.cb.table, self.last,
                                              self.still)
                if len(allrules) == 0:
                    if pieces.exposed_king(self.cb.table,
                                           self.last,
                                           self.still,
                                           no_move=True):
                        self.winfo_toplevel().title("Checkmate!")
                        if talking:
                            blind.engine.say('Checkmate')
                            blind.engine.runAndWait()
                    else:
                        self.winfo_toplevel().title("Stalemate!")
                        if talking:
                            blind.engine.say('Stalemate')
                            blind.engine.runAndWait()
                    self.checkmate = 1
                if pieces.draw(self.cb.table):
                    print("DRAW")
                    break
                if self.last is not None:
                    self.show_last()
                render = ImageTk.PhotoImage(self.bkg)
                img = Label(self, image=render)
                img.image = render
                img.grid(row=0, column=0)
                self.update()
                #time.sleep(0.25)
                turn = 1 - turn
                if talking:
                    blind.engine.say(cmove[0] + ' to ' + cmove[1])
                    blind.engine.runAndWait()
                print(cmove[0] + ' ' + cmove[1])

        if self.option == 'Two computers':
            turn = 0
            while not self.checkmate:
                try:
                    start = time.time()
                    cmove = self.comp[turn].move(self.cb.table, self.last,
                                                 self.still,
                                                 self.data_hist).split()
                    print(int(1000 * float(time.time() - start)) / 1000, 's')
                    s = np.sum(self.cb.table)
                    self.cb.table = pieces.move(self.cb.table, cmove[0],
                                                cmove[1], self.still)
                    if ai.repet(self.cb.table, self.data_hist):
                        self.checkmate = 1
                    self.add_taken(s - np.sum(self.cb.table))
                    self.last = cmove
                    self.display_pieces(self.cb.table, to=self.chess_up)

                    allrules = pieces.allrules_ek(self.cb.table, self.last,
                                                  self.still)
                    if len(allrules) == 0:
                        if pieces.exposed_king(self.cb.table,
                                               self.last,
                                               self.still,
                                               no_move=True):
                            self.winfo_toplevel().title("Checkmate!")
                        else:
                            self.winfo_toplevel().title("Stalemate!")
                        self.checkmate = 1
                    if pieces.draw(self.cb.table):
                        print("DRAW")
                        break
                    if self.last is not None:
                        self.show_last()
                    render = ImageTk.PhotoImage(self.bkg)
                    img = Label(self, image=render)
                    img.image = render
                    img.grid(row=0, column=0)
                    self.update()
                    #time.sleep(0.25)
                    turn = 1 - turn
                except KeyboardInterrupt:
                    break

        self.startGame = True
コード例 #4
0
ファイル: ai.py プロジェクト: KeivanR/chess
def rec_sum_tree(table,
                 node,
                 last,
                 still,
                 color,
                 k,
                 noha,
                 noha_lim,
                 create=False):
    if len(node.children) == 0:
        allr = pieces.allrules_ek(table, last, still)
        node.children = [Node(allr[i]) for i in range(len(allr))]
    allr = node.children
    #print(node)
    #print(node.children)
    val = []
    if len(allr) == 0:
        if pieces.exposed_king(table, last, still, no_move=True):
            #print('future checkmate possible')
            return [None, 100 * (2 * color - 1)]
        else:
            #print('future stalemate possible')
            return [None, sum_value(table)]
    if noha == noha_lim:
        #print('noha_lim reached')
        if create:
            return node
        else:
            return [None, sum_value(table)]
    if k == 0:
        for m in allr:
            still2 = still[:]
            move = m.name
            table2 = pieces.move(table,
                                 move.split()[0],
                                 move.split()[1],
                                 still2,
                                 real=False)
            node2 = Node(move, parent=node)
            val.append(sum_value(table2))
    else:
        for m in allr:
            still2 = still[:]
            move = m.name
            table2 = pieces.move(table,
                                 move.split()[0],
                                 move.split()[1],
                                 still2,
                                 real=False)
            if sum_value(table2) == sum_value(table):
                rs = rec_sum_tree(
                    table2, m,
                    [move.split()[0], move.split()[1]], still2, -color, k - 1,
                    noha + 1, noha_lim, create)
            else:
                rs = rec_sum_tree(
                    table2, m,
                    [move.split()[0], move.split()[1]], still2, -color, k - 1,
                    noha, noha_lim, create)
            if not create:
                val.append(rs[1])
    if create:
        return node
    else:
        val = np.asarray(val)
        if color > 0:
            return [
                allr[np.random.choice(np.flatnonzero(val == max(val)))].name,
                max(val)
            ]
        else:
            return [
                allr[np.random.choice(np.flatnonzero(val == min(val)))].name,
                min(val)
            ]
コード例 #5
0
ファイル: gui.py プロジェクト: KeivanR/chess
    def callback(self, event):
        if self.startGame and self.option != 'Two computers' and not self.checkmate:
            [x, y] = (mousetotable(event.x, event.y, self.chess_up))
            if not pieces.oncb(x, y):
                self.a = self.b = None
                return 0
            movexy = pieces.mv(x, y)
            allrules = pieces.allrules_ek(self.cb.table, self.last, self.still)
            if self.a is None:
                self.a = movexy
                self.allowed_moves(allrules, movexy)
            else:
                if np.abs(self.cb.table[pieces.xy(self.a)[0]][pieces.xy(
                        self.a)[1]]) == 1 and y == 3.5 + 3.5 * self.chess_up:
                    prom = input('Promotion:N,B,R,Q?')
                    self.b = movexy + prom
                else:
                    self.b = movexy
                if self.a + ' ' + self.b not in allrules:
                    self.a = movexy
                    self.b = None
                    self.display_pieces(self.cb.table,
                                        to=self.chess_up,
                                        save=False)
                    self.allowed_moves(allrules, movexy)
                else:
                    s = np.sum(self.cb.table)
                    self.cb.table = pieces.move(self.cb.table, self.a, self.b,
                                                self.still)
                    if ai.repet(self.cb.table, self.data_hist):
                        self.checkmate = 1
                    self.add_taken(s - np.sum(self.cb.table))
                    self.last = [self.a, self.b]
                    self.display_pieces(self.cb.table, to=self.chess_up)
                    self.update()
                    allrules = pieces.allrules_ek(self.cb.table, self.last,
                                                  self.still)
                    if len(allrules) == 0 or self.checkmate:
                        if pieces.exposed_king(self.cb.table,
                                               self.last,
                                               self.still,
                                               no_move=True):
                            self.winfo_toplevel().title("Checkmate!")
                        else:
                            self.winfo_toplevel().title("Stalemate!")
                        self.checkmate = 1

                    if self.option == 'Two players':
                        time.sleep(1)
                        self.chess_up = -self.chess_up
                        self.display_pieces(self.cb.table, to=self.chess_up)
                    elif not self.checkmate:
                        self.comp.update_tree(self.last[0] + ' ' +
                                              self.last[1])
                        start = time.time()
                        cmove = self.comp.move(self.cb.table, self.last,
                                               self.still,
                                               self.data_hist).split()
                        print(
                            int(1000 * float(time.time() - start)) / 1000, 's')
                        s = np.sum(self.cb.table)
                        self.cb.table = pieces.move(self.cb.table, cmove[0],
                                                    cmove[1], self.still)
                        if ai.repet(self.cb.table, self.data_hist):
                            self.checkmate = 1
                        self.add_taken(s - np.sum(self.cb.table))
                        self.last = cmove
                        self.display_pieces(self.cb.table, to=self.chess_up)
                        allrules = pieces.allrules_ek(self.cb.table, self.last,
                                                      self.still)
                        if len(allrules) == 0:
                            if pieces.exposed_king(self.cb.table,
                                                   self.last,
                                                   self.still,
                                                   no_move=True):
                                self.winfo_toplevel().title("Checkmate!")
                            else:
                                self.winfo_toplevel().title("Stalemate!")
                            self.checkmate = 1
            if self.last is not None:
                self.show_last()
            render = ImageTk.PhotoImage(self.bkg)
            img = Label(self, image=render)
            img.image = render
            img.grid(row=0, column=0)
            self.update()