Exemplo n.º 1
0
 def testBoardSize(self):
     board = ChessBoard.ChessBoard()
     self.assertEqual(board.BOARD_WIDTH, 8)
     self.assertEqual(board.BOARD_HEIGHT, 8)
     for i in range(board.BOARD_WIDTH):
         for j in range (board.BOARD_HEIGHT):
             self.assertEqual(board.board[i][j], None)
Exemplo n.º 2
0
    def __init__(self, in_ai_count, in_ai_function, in_play_playout, in_delay, in_end_delay, batch_size, search_threads,
                 processor, num_gpus, res_block_nums, human_color = "b"):
        self.human_color = human_color
        self.current_player = "w"
        self.players = {}
        self.players[self.human_color] = "human"
        ai_color = "w" if self.human_color == "b" else "b"
        self.players[ai_color] = "AI"

        ChessGame.board = ChessBoard(self.human_color == 'b')
        self.view = ChessView(self, board=ChessGame.board)
        self.view.showMsg("Loading Models...")    #"Red"    player_color
        self.view.draw_board(self.board)
        ChessGame.game_mode = in_ai_count
        self.ai_function = in_ai_function
        self.play_playout = in_play_playout
        self.delay = in_delay
        self.end_delay = in_end_delay

        self.win_rate = {}
        self.win_rate['w'] = 0.0
        self.win_rate['b'] = 0.0

        self.view.root.update()
        self.cchess_engine = cchess_main(playout=self.play_playout, in_batch_size=batch_size, exploration=False, in_search_threads=search_threads,
                                         processor=processor, num_gpus=num_gpus, res_block_nums=res_block_nums, human_color=human_color)
Exemplo n.º 3
0
 def __init__(self):
     self.board = ChessBoard()
     self.view = ChessView(self)
     self.view.showMsg("Red")
     self.view.draw_board(self.board)
     self.player_is_red = True
     self.ai = AI()
Exemplo n.º 4
0
    def __init__(self, parent, pieceWidth=48, pieceHeight=48):
        Tkinter.Frame.__init__(self, parent)

        self.parent = parent

        # left side
        self.chessBoard = ChessBoard.ChessBoard(self, pieceWidth, pieceHeight)
        self.chessBoard.draw()
        # right side
        self.reserveBoard = ReserveBoard.ReserveBoard(self, pieceWidth,
                                                      pieceHeight)
        self.reserveBoard.draw()

        self.margin = 4
        self.width = self.margin + self.chessBoard.width + self.reserveBoard.width + self.margin
        self.height = self.margin + self.chessBoard.height + self.margin

        #self.chessBoard.pack(side=Tkinter.LEFT)
        #self.reserveBoard.pack(side=Tkinter.LEFT)

        self.chessBoard.grid(row=0, column=0)
        self.reserveBoard.grid(row=0, column=1)

        #print self.chessBoard.grid_info()
        #print self.reserveBoard.grid_info()
        w = Tkinter.Label(self, text="row0_column2", bg="red", fg="white")
        w.grid(row=0, column=2)
        w = Tkinter.Label(self, text="row1_column2", bg="red", fg="white")
        w.grid(row=1, column=2)
        w = Tkinter.Label(self, text="row2_column2", bg="red", fg="white")
        w.grid(row=2, column=2)
Exemplo n.º 5
0
    def testAddPiece(self):
        board = ChessBoard.ChessBoard()
        pawn1 = pieces.Pawn(PieceColor.WHITE)
        pawn2 = pieces.Pawn(PieceColor.BLACK)
        rook1 = pieces.Rook(PieceColor.WHITE)
        rook2 = pieces.Rook(PieceColor.BLACK)
        bishop1 = pieces.Bishop(PieceColor.BLACK)
        bishop2 = pieces.Bishop(PieceColor.WHITE)
        knight1 = pieces.Knight(PieceColor.BLACK)
        knight2 = pieces.Knight(PieceColor.WHITE)
        queen1 = pieces.Queen(PieceColor.BLACK)
        queen2 = pieces.Queen(PieceColor.WHITE)
        king1 = pieces.King(PieceColor.BLACK)
        king2 = pieces.King(PieceColor.WHITE)
        self.assertTrue(board.addPiece('2a', pawn1))
        self.assertTrue(board.addPiece('7a', pawn2))
        self.assertTrue(board.addPiece('1a', rook1))
        self.assertTrue(board.addPiece('8a', rook2))
        self.assertTrue(board.addPiece('8b', knight1))
        self.assertTrue(board.addPiece('1b', knight2))
        self.assertTrue(board.addPiece('8c', bishop1))
        self.assertTrue(board.addPiece('1c', bishop2))
        self.assertTrue(board.addPiece('8d', queen1))
        self.assertTrue(board.addPiece('1d', queen2))
        self.assertTrue(board.addPiece('8e', king1))
        self.assertTrue(board.addPiece('1e', king2))

        #try to add piece at invalid coordinates
        self.assertFalse(board.addPiece('9e', king2))
        self.assertFalse(board.addPiece('9a', king2))

        #try to add piece at non empty cell
        self.assertFalse(board.addPiece('1d', queen2))
        self.assertFalse(board.addPiece('1e', king2))
Exemplo n.º 6
0
 def __init__(self, anId, players):
     self.board = ChessBoard()
     self.whiteUserName = players[0]
     self.blackUserName = players[1]
     self.whoseTurn = players[0]
     self.columnLetters = ["a", "b", "c", "d", "e", "f", "g", "h"]
     super(ChessGame, self).__init__(anId, "ChessGame", players)
Exemplo n.º 7
0
    def createBoard(self):
        dict = self.ui.comboBox_dict.currentIndex()
        numX = int(self.ui.lineEdit_numX.text())
        numY = int(self.ui.lineEdit_numY.text())
        squareSize = float(self.ui.lineEdit_squareSize.text())
        dpi = int(self.ui.lineEdit_DPI.text())
        imgSize = (float(self.ui.lineEdit_printX.text()),
                   float(self.ui.lineEdit_printY.text()))
        if dict == 0:
            self.boardType = 0
            self.calibBoard = ChessBoard.ChessBoard()
            self.board = self.calibBoard.create((numX, numY), squareSize, dpi,
                                                imgSize)  # Create Board
        else:
            self.boardType = 1
            self.calibBoard = CharucoBoard.CharucoBoard()
            self.board = self.calibBoard.create(numX, numY, dict - 1,
                                                squareSize, imgSize,
                                                dpi)  #Create Board

        if self.board is None:  ## splite Qt segment
            self.ui.label.setText("Create Failed,Please confire parameter!")
            return

        # showBoard
        image = QImage(self.board[:], self.board.shape[1], self.board.shape[0],
                       self.board.shape[1],
                       QImage.Format_Grayscale8)  #ndarray -> QImage
        showBoard = QPixmap(image)  #QImage ->  Qpixmap
        if showBoard.width() > showBoard.height():  #resize Qpixmap
            showBoard = showBoard.scaledToWidth(self.ui.label.width())
        else:
            showBoard = showBoard.scaledToHeight(self.ui.label.height())
        self.ui.label.setPixmap(showBoard)  #show
Exemplo n.º 8
0
 def read_info_form_database(self, filename):  # 从文件读取开局信息
     with open(filename, "r", encoding='utf-8') as f:
         s = f.read().splitlines()
         del s[0]
     for i in range(len(s)):
         s[i] = s[i].split(' ')
     UI = ChessBoard.ChessBoard()
     UI.my_s(1, s)
Exemplo n.º 9
0
 def test3(self, ThreeThree1):
     UI = ChessBoard.ChessBoard()
     board = [[0 for n in range(15)] for i in range(15)]
     for i in range(len(ThreeThree1)):
         x = 7 - ThreeThree1[i][1]
         y = 7 + ThreeThree1[i][0]
         if ThreeThree1[i][2] == 1:
             board[x][y] = 1
     UI.out_gobang_board(self.total, board)
Exemplo n.º 10
0
    def __init__(self, parent, pieceWidth=64, pieceHeight=64):
        Tkinter.Frame.__init__(self, parent)

        self.parent = parent

        self.boardMap = {}

        self.PgnParser = None
        self.stateIndex = 0

        # widget
        self.chessBoard = ChessBoard.ChessBoard(self, pieceWidth, pieceHeight)
        self.chessBoard.setFEN(Common.initChessFEN)
        self.chessBoard.refreshCanvasFromState()

        # status thingies
        self.playerInfoW = Tkinter.Label(self, text="", bg="white", fg="black")
        self.playerTimeW = Tkinter.Label(self, text="", bg="green", fg="black")
        self.playerInfoB = Tkinter.Label(self, text="", bg="black", fg="white")
        self.playerTimeB = Tkinter.Label(self, text="", bg="green", fg="black")

        # buttons go into frame
        self.btnFrame = Tkinter.Frame(self)
        self.btnFlip = Tkinter.Button(self.btnFrame,
                                      text="FLIP",
                                      command=self.btnFlipCb)
        self.btnStart = Tkinter.Button(self.btnFrame,
                                       text="|<",
                                       command=self.btnStartCb)
        self.btnBackward = Tkinter.Button(self.btnFrame,
                                          text="<",
                                          command=self.btnBackwardCb)
        self.btnForward = Tkinter.Button(self.btnFrame,
                                         text=">",
                                         command=self.btnForwardCb)
        self.btnEnd = Tkinter.Button(self.btnFrame,
                                     text=">|",
                                     command=self.btnEndCb)

        self.playerInfoW.grid(row=0, column=1, sticky=Tkinter.E + Tkinter.W)
        self.playerTimeW.grid(row=0, column=0)
        self.playerInfoB.grid(row=0, column=2, sticky=Tkinter.E + Tkinter.W)
        self.playerTimeB.grid(row=0, column=3)

        self.chessBoard.grid(row=1, column=0, columnspan=4)
        self.playerInfoW.grid(row=2, column=1, sticky=Tkinter.E + Tkinter.W)
        self.playerTimeW.grid(row=2, column=0)
        self.playerInfoB.grid(row=2, column=2, sticky=Tkinter.E + Tkinter.W)
        self.playerTimeB.grid(row=2, column=3)

        self.btnFlip.pack(side=Tkinter.LEFT)
        self.btnStart.pack(side=Tkinter.LEFT)
        self.btnBackward.pack(side=Tkinter.LEFT)
        self.btnForward.pack(side=Tkinter.LEFT)
        self.btnEnd.pack(side=Tkinter.LEFT)
        self.btnFrame.grid(row=3, columnspan=4)
Exemplo n.º 11
0
def main():
    #创建棋盘类
    chessboard = ChessBoard()
    #创建
    chessman = ChessMan()  #人的棋子
    chesscomputer = ChessMan()  #电脑的棋子
    #创建Engine对象
    engine = Engine(chessboard)
    #开始游戏
    engine.play(chessboard, chessman, chesscomputer)
Exemplo n.º 12
0
def test2():
    chessboard = ChessBoard()
    chessboard.init_board()
    #在10,8位置上放置黑棋
    chessboard.set_chess((10, 8), 'x')
    #创建一个棋子对象 颜色为白棋 位置为4,7
    chessman = ChessMan()
    chessman.set_pos((4, 7))
    chessman.set_color('o')
    chessboard.set_chessman(chessman)
    chessboard.print_board()
Exemplo n.º 13
0
    def __init__(self):
        self.size = [self.SCREEN_WIDTH, self.SCREEN_HEIGHT]
        self.cb = ChessBoard()
        self.white_to_move = True
        self.destx = 0
        self.desty = 0
        self.x = 0
        self.y = 0
        self.last_move = None

        self.is_square_selected = None
        self.promote_to = Piece.QUEEN
Exemplo n.º 14
0
def test3():
    chessboard = ChessBoard()
    chessboard.init_board()
    #创建Engine对象
    engine = Engine(chessboard)
    #创建chessMan对象 并写入棋子颜色
    chessman = ChessMan()
    chessman.set_color('o')
    engine.computer_go(chessman)  #方法中填入位置
    #把该棋子对象放置到棋盘上
    chessboard.set_chessman(chessman)
    #打印棋盘
    chessboard.print_board()
Exemplo n.º 15
0
def test4():
    chessboard = ChessBoard()
    chessboard.init_board()
    engine = Engine(chessboard)
    #创建chessMan对象 并写入棋子颜色
    chessman = ChessMan()
    chessman.set_color('x')
    input = '13,b'
    engine.parse_uesr_input(input, chessman)
    #把该棋子对象放置到棋盘上
    chessboard.set_chessman(chessman)
    #打印棋盘
    chessboard.print_board()
Exemplo n.º 16
0
def test6():
    chessboard = ChessBoard()
    engine = Engine(chessboard)
    chessboard.init_board()
    chessboard.set_chess((8, 5), 'x')
    chessboard.set_chess((9, 5), 'x')
    chessboard.set_chess((10, 5), 'x')
    chessboard.set_chess((11, 5), 'x')
    chessboard.set_chess((12, 5), 'x')
    print(chessboard.get_board())
    ret = engine.is_Win(chessboard.get_board())
    chessboard.print_board()
    #print(chessboard.get_board())
    print(ret)
Exemplo n.º 17
0
 def testGetCoordinates(self):
     board = ChessBoard.ChessBoard()
     for i in range(10):
         x = random.randint(0, board.BOARD_HEIGHT)
         y = random.randint(0, board.BOARD_WIDTH)
         buf = str(8 - x) + chr(ord('a') + y)
         (x1, y1) = board.getCoordinates(buf)
         self.assertEqual((x, y), (x1, y))
     for i in range(10):
         x = random.randint(board.BOARD_HEIGHT + 2, 100)
         y = random.randint(board.BOARD_WIDTH + 1, 26)
         buf = str(x) + chr(ord('a') + y)
         (x1, y1) = board.getCoordinates(buf)
         self.assertEqual((x1, y1), (-1, -1))
Exemplo n.º 18
0
    def test1(self):
        UI = ChessBoard.ChessBoard()

        ThreeThree = copy.deepcopy(self.ThreeThree)
        for i in range(len(ThreeThree)):
            self.total = i + 1
            # print(ThreeThree[i])
            board = [[0 for n in range(15)] for i in range(15)]
            for j in range(len(ThreeThree[i])):
                x = 7 - ThreeThree[i][j][1]
                y = 7 + ThreeThree[i][j][0]
                if ThreeThree[i][j][2] == 1:
                    board[x][y] = 1
            UI.out_gobang_board(self.total, board)
            print()
Exemplo n.º 19
0
    def test2(self):
        UI = ChessBoard.ChessBoard()

        FourFour = copy.deepcopy(self.FourFour)
        for i in range(len(FourFour)):
            self.total = i + 1
            # print(FourFour[i])
            board = [[0 for n in range(15)] for k in range(15)]
            for j in range(len(FourFour[i])):
                x = 7 - FourFour[i][j][1]
                y = 7 + FourFour[i][j][0]
                if FourFour[i][j][2] == 1:
                    board[x][y] = 1
            UI.out_gobang_board(self.total, board)
            print()
Exemplo n.º 20
0
def mainThread():
    #创建棋盘对象 并初始化
    chessboard = ChessBoard()
    chessboard.init_board()
    print('初始化棋盘如下:')
    chessboard.print_board()
    #创建策略类对象 并初始化
    engine = Engine(chessboard)
    #创建两个棋子线程对象
    chessman = ChessManThread()
    chessman.set_color('x')
    chesspc = ChessManThread()
    chesspc.set_color('o')

    #创建用户线程对象
    userthread = UserThread(engine, chessman)

    userthread.start()

    #创建电脑线程对象 并启动
    computerthread = PcThread(engine, chesspc)
    computerthread.setDaemon(True)
    computerthread.start()

    while True:
        #用户wait
        chessman.do_wait()
        #在棋盘上摆放棋子
        engine.parse_uesr_input(userthread.user_input, chessman)
        chessboard.set_chessman(chessman)
        print('此时棋盘如下')
        chessboard.print_board()
        result = engine.is_Win(chessboard.get_board())
        if result == True:
            break
        # 电脑notify
        chesspc.do_notify()
        # 电脑wait
        chesspc.do_wait()
        # 在棋盘上摆放棋子

        chessboard.set_chessman(chesspc)
        chessboard.print_board()
        result = engine.is_Win(chessboard.get_board())
        if result == True:
            break
        #用户notify
        chessman.do_notify()
Exemplo n.º 21
0
class ChessGame:

    board = ChessBoard()
    player_is_red = True
    def __init__(self):
        self.view = ChessView(self)
        self.view.showMsg("Red")
        self.view.draw_board(self.board)

    def start(self):
        self.view.start()

    def callback(self, event):
        print event.x, event.y
        rx, ry = real_coord(event.x), real_coord(event.y)
        if self.board.select(rx, ry, self.player_is_red):
            self.player_is_red = not self.player_is_red
            self.view.showMsg("Red" if self.player_is_red else "Green")
        self.view.draw_board(self.board)
Exemplo n.º 22
0
def test5():
    chessboard = ChessBoard()
    chessboard.init_board()
    #创建Engine对象
    engine = Engine(chessboard)
    #垂直方向判断
    chessboard.set_chess((3, 5), 'x')
    chessboard.set_chess((4, 5), 'x')
    chessboard.set_chess((5, 5), 'x')
    chessboard.set_chess((6, 5), 'x')
    #chessboard.set_chess((7,5), 'x')
    chessboard.set_chess((8, 5), 'x')
    chessboard.set_chess((9, 5), 'x')
    chessboard.set_chess((10, 5), 'x')
    chessboard.set_chess((11, 5), 'x')
    chessboard.set_chess((12, 5), 'x')
    #打印棋盘
    chessboard.print_board()
    ret = engine.is_won((8, 5), 'x')

    #水平方向判断
    chessboard.set_chess((5, 4), 'x')
    chessboard.set_chess((5, 5), 'x')
    chessboard.set_chess((5, 6), 'x')
    chessboard.set_chess((5, 7), 'x')
    #chessboard.set_chess((5,8), 'x')
    chessboard.set_chess((5, 9), 'x')
    chessboard.set_chess((5, 10), 'x')
    chessboard.set_chess((5, 11), 'x')
    chessboard.set_chess((5, 12), 'x')
    chessboard.set_chess((5, 13), 'x')

    #打印棋盘
    chessboard.print_board()
    ret = engine.is_won((5, 12), 'x')
    print(ret)

    chessman = ChessMan()
    chessman.set_color('x')
    chessman.set_pos((5, 9))
    ret = engine.is_woman(chessman)
    print(ret)
Exemplo n.º 23
0
    def test(self):
        UI = ChessBoard.ChessBoard()
        UI.out_gobang_board(self.total, self.board)

        for i in range(15):
            for j in range(15):
                if self.board[i][j] == 1:
                    if self.charge_three_forbid(i, j):
                        row = chr(ord("A") + i)
                        col = chr(ord("A") + j)
                        s = ""
                        s += row + col
                        print(
                            "�ܲ��Ұ����������˵��װ��Ľ��ֵ㣡�����е��������ֵ�Ϊ (%s) ��"
                            % (s))

                    if self.charge_four_forbid(i, j):
                        row = chr(ord("A") + i)
                        col = chr(ord("A") + j)
                        s = ""
                        s += row + col
                        print(
                            "�ܲ��Ұ����������˵��װ��Ľ��ֵ㣡�����е����Ľ��ֵ�Ϊ (%s) ��"
                            % (s))

                    if self.charge_long_forbid(i, j):
                        row = chr(ord("A") + i)
                        col = chr(ord("A") + j)
                        s = ""
                        s += row + col
                        print(
                            "�ܲ��Ұ����������˵��װ��Ľ��ֵ㣡�����еij������ֵ�Ϊ (%s) ��"
                            % (s))

        player_input = input(
            "�����������ƶ���λ��:")  # ������������������
        x = ord(player_input[0].upper()) - ord("A")  # ת������
        y = ord(player_input[1].upper()) - ord("A")
        self.board[x][y] = 1  # ��������
        self.total += 1

        self.test()
Exemplo n.º 24
0
    def __init__(self, parent, pieceWidth=48, pieceHeight=48):
        Tkinter.Frame.__init__(self, parent)

        self.parent = parent

        # on piece capture, send to other side
        self.transferPieces = 1

        # left side
        self.chessBoard = ChessBoard.ChessBoard(self, pieceWidth, pieceHeight)
        # right side
        self.holdingBoard = HoldingBoard.HoldingBoard(self, pieceWidth,
                                                      pieceHeight)

        self.width = self.chessBoard.width + self.holdingBoard.width
        self.height = self.chessBoard.height

        self.chessBoard.grid(row=0, column=0, padx=2)
        self.holdingBoard.grid(row=0, column=1, pady=2)

        self.boardMap = {}
Exemplo n.º 25
0
    def __init__(self,
                 mode=1,
                 dis=0,
                 showMove=True,
                 showSearch=False,
                 showGUI=True,
                 saveInfo=False):
        self.board = ChessBoard()
        self.Player_Side = False
        self.GameMode = mode
        self.distribution = dis

        self.ai_0 = AI()
        self.ai_1 = AI()

        self.ShowMoveInfo = showMove
        self.ShowSearchInfo = showSearch
        self.ShowGraphUI = showGUI
        self.SaveInfo = saveInfo

        self.view = ChessView(self)
Exemplo n.º 26
0
    def show_the_gobang_board_now(self, board):  # 显示此时的棋盘矩阵
        # _board, open, robot = copy.deepcopy(board), self.Opening_type, self.Robot_gobang_type
        # turn, free_forbid = self.gobang_step_now, self.free_start_forbid_choice
        _board, turn = copy.deepcopy(board), self.gobang_step_now
        total = self.gobang_chess_total

        # if (open == 1 or (open == 2 and free_forbid == 1)) and robot == 1:
        if total != 0:
            noobrobot = NoobRobot.NoobRobot()  # 菜鸟机器人初始化
            noobrobot.board = board  # 菜鸟机器人的棋盘矩阵初始化
            moves = noobrobot.genmove_second(turn)

            forbid_step = ForbidStep.ForbidStep()
            forbid_step.board = board
            for score, row, col in moves:
                if forbid_step.deal_noobrobot_move(row, col):
                    _board[row][col] = -1

        self.update_round()
        UI = ChessBoard.ChessBoard()
        UI.out_gobang_board(self.round, _board)
Exemplo n.º 27
0
    cnt = 1
    for i in range(8):
        for j in range(8):
            x = offset + TILE_SIZE * j
            y = offset + TILE_SIZE * i
            coord = (x, y, TILE_SIZE, TILE_SIZE)
            if (cnt % 2):
                pygame.draw.rect(win, COLOR_WHITE, coord)
            else:
                pygame.draw.rect(win, COLOR_BLACK, coord)
            cnt += 1
        cnt += 1


chess_pieces = Piece.createChessPieces()
board = Board.ChessBoard(chess_pieces)

pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
win.fill(COLOR_GREY)
mask = pygame.Surface((WIDTH, HEIGHT), flags=SRCALPHA)
mask.fill(COLOR_EMPTY)

for i in chess_pieces:
    i.display(mask)

displayBackgroundTiles(win)
copy = win.copy()
win.blit(mask, (0, 0))

selected = None
Exemplo n.º 28
0
def test1():
    chessboard = ChessBoard()
    chessboard.init_board()
    chessboard.print_board()
Exemplo n.º 29
0
                image_name = self.get_image_name(rank_row_index,
                                                 file_column_index)
                image = Image.open(image_name)
                xsize = int(self.root.winfo_width() / 8) - 4
                #print(xsize)
                ysize = int(self.root.winfo_height() / 8) - 4
                #print(ysize)
                if (xsize != 100) or (ysize != 100):
                    image = image.resize((xsize, ysize))
                tk_photo_image: PhotoImage = ImageTk.PhotoImage(image)
                new_tk_photo_image_array.append(tk_photo_image)
                label = tk.Label(self.frame, image=tk_photo_image)
                label.grid(row=rank_row_index,
                           column=file_column_index,
                           sticky='nw')
            # self.root.update()
        self.tk_photo_image_array = new_tk_photo_image_array
        self.root.update()
        # self.root.bind("<Configure>", self.populate_squares)


board = ChessBoard.ChessBoard(
    "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1")
GUI = ChessGUI(board)

# GUI.root.mainloop()

while True:
    GUI.populate_squares()
    time.sleep(5)
Exemplo n.º 30
0
class ChessGame:

    board = ChessBoard()
    player_is_red = True
    cur_round = 1
    game_mode = 0  # 0:HUMAN VS HUMAN 1:HUMAN VS AI 2:AI VS AI
    AI_red = None
    AI_green = None
    AI_dict = AIDict()
    time_red = []
    time_green = []

    def __init__(self):
        self.view = ChessView(self)
        self.view.showMsg("Red")
        self.view.draw_board(self.board)
        self.view.root.update()

    def start(self, game_mode, AI_red=None, AI_green=None):
        # below added by Fei Li
        self.game_mode = game_mode
        if game_mode == 1:
            if AI_red in self.AI_dict.AI:
                self.AI_red = self.AI_dict.AI[AI_red]
                print '-----Round %d-----' % self.cur_round
                self.perform_AI(self.AI_red)
                self.view.draw_board(self.board)
                self.change_player(not self.player_is_red)
            else:
                self.view.showMsg('Please enter a correct AI name')
                self.view.draw_board(self.board)
                self.view.root.update()
                self.quit()
                return
        elif game_mode == 2:
            if AI_red in self.AI_dict.AI and AI_green in self.AI_dict.AI:
                self.AI_red = self.AI_dict.AI[AI_red]
                self.AI_green = self.AI_dict.AI[AI_green]
                print '-----Round %d-----' % self.cur_round
                self.perform_AI(self.AI_red)
                self.view.draw_board(self.board)
            else:
                self.view.showMsg('Please enter correct AI names')
                self.view.draw_board(self.board)
                self.view.root.update()
                self.quit()
                return
        else:
            print '-----Round %d-----' % self.cur_round
        self.view.start()

    def callback(self, event):
        if self.game_mode == 1 and self.player_is_red:
            return
        if self.game_mode == 2:
            return
        rx, ry = real_coord(event.x), real_coord(event.y)
        change = self.board.select(rx, ry, self.player_is_red)
        self.view.draw_board(self.board)
        if self.check_end(self.board):
            self.view.root.update()
            self.quit()
            return
        if change:
            performed = self.change_player(not self.player_is_red)
            if performed:
                self.view.draw_board(self.board)
                if self.check_end(self.board):
                    self.view.root.update()
                    self.quit()
                    return
                self.change_player(not self.player_is_red)

    # below added by Fei Li

    def quit(self):
        time.sleep(Const.end_delay)
        self.view.quit()

    def check_end(self, board):
        red_king = False
        green_king = False
        pieces = board.pieces
        for (x, y) in pieces.keys():
            if pieces[x, y].is_king:
                if pieces[x, y].is_red:
                    red_king = True
                else:
                    green_king = True
        if not red_king:
            print '*****\n*****'
            self.view.showMsg('*****Green Wins at Round %d*****' % self.cur_round)
            self.view.root.update()
            print '*****\n*****'
            with open('GameLog.txt', 'a') as f:
                if len(self.time_red) > 0:
                    avg_red = np.mean(self.time_red)
                else:
                    avg_red = 0.0
                if len(self.time_green) > 0:
                    avg_green = np.mean(self.time_green)
                else:
                    avg_green = 0.0
                f.write('%d\t%d\t%f\t%f\n' % (0, self.cur_round, avg_red, avg_green))
            return True
        elif not green_king:
            print '*****\n*****'
            self.view.showMsg('*****Red Wins at Round %d*****' % self.cur_round)
            self.view.root.update()
            print '*****\n*****'
            with open('GameLog.txt', 'a') as f:
                if len(self.time_red) > 0:
                    avg_red = np.mean(self.time_red)
                else:
                    avg_red = 0.0
                if len(self.time_green) > 0:
                    avg_green = np.mean(self.time_green)
                else:
                    avg_green = 0.0
                f.write('%d\t%d\t%f\t%f\n' % (1, self.cur_round, avg_red, avg_green))
            return True
        elif self.cur_round >= 200:
            print '*****\n*****'
            self.view.showMsg('*****Draw at Round %d*****' % self.cur_round)
            self.view.root.update()
            print '*****\n*****'
            with open('GameLog.txt', 'a') as f:
                if len(self.time_red) > 0:
                    avg_red = np.mean(self.time_red)
                else:
                    avg_red = 0.0
                if len(self.time_green) > 0:
                    avg_green = np.mean(self.time_green)
                else:
                    avg_green = 0.0
                f.write('%f\t%d\t%f\t%f\n' % (0.5, self.cur_round, avg_red, avg_green))
            return True
        return False

    def change_player(self, player_now):
        self.player_is_red = player_now
        if player_now:
            self.cur_round += 1
            print '-----Round %d-----' % self.cur_round
        self.view.showMsg("Red" if self.player_is_red else "Green")
        self.view.root.update()
        if self.game_mode == 0:
            return False
        if self.game_mode == 1:
            if self.player_is_red:
                self.perform_AI(self.AI_red)
                return True
            return False
        elif self.game_mode == 2:
            if self.player_is_red:
                self.perform_AI(self.AI_red)
            else:
                self.perform_AI(self.AI_green)
            return True
        return False

    def perform_AI(self, AI):
        print '...AI is calculating...'
        START_TIME = time.clock()
        move = AI.select_move(self.board, self.player_is_red)
        time_used = time.clock() - START_TIME
        print '...Use %fs...' % time_used
        if self.player_is_red:
            self.time_red.append(time_used)
        else:
            self.time_green.append(time_used)
        if move is not None:
            self.board.move(move[0], move[1], move[2], move[3])
        else:
            self.view.showMsg('Can not move')
            self.view.root.update()
            if self.player_is_red:
                print '*****\n*****'
                self.view.showMsg('*****Red can not move at Round %d*****' % self.cur_round)
                self.view.root.update()
                print '*****\n*****'
            else:
                print '*****\n*****'
                self.view.showMsg('*****Green can not move at Round %d*****' % self.cur_round)
                self.view.root.update()
                print '*****\n*****'

    def game_mode_2(self):
        self.change_player(not self.player_is_red)
        self.view.draw_board(self.board)
        self.view.root.update()
        if self.check_end(self.board):
            return True
        return False