コード例 #1
0
def test_start_moves():
    board = ChessBoard("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
    assert board.possible_moves("a2") == ["a3", "a4"]
    assert board.possible_moves("a7") == ["a6", "a5"]
    assert board.possible_moves("a1") == []
    assert board.possible_moves("b1") == ["a3", "c3"]
    assert board.possible_moves("c1") == []
    assert board.possible_moves("d1") == []
コード例 #2
0
ファイル: game.py プロジェクト: swatia-code/chess
class ChessGame:
    STATUS_WHITE_MOVE = "white_move"
    STATUS_BLACK_MOVE = "black_move"
    STATUS_WHITE_VICTORY = "white_victory"
    STATUS_BLACK_VICTORY = "black_victory"

    def __init__(self, renderer: InputRender = None):
        self._finished = False
        self._board = ChessBoard()
        self._renderer = renderer
        self._status = ChessGame.STATUS_WHITE_MOVE

    def run(self):
        self._renderer.render(self.get_game_state())
        while not self._finished:
            command = self._parse_command()
            if command is None and self._renderer is not None:
                self._renderer.print_line("Invalid command, please re-enter.")
                continue
            if not self._try_move(command):
                self._renderer.print_line("Invalid command, please re-enter.")
                continue

            self._board.execute_move(command)
            if self._status == ChessGame.STATUS_WHITE_MOVE:
                self._status = ChessGame.STATUS_BLACK_MOVE
            elif self._status == ChessGame.STATUS_BLACK_MOVE:
                self._status = ChessGame.STATUS_WHITE_MOVE
            self._renderer.render(self.get_game_state())

    def _try_move(self, command: MoveCommand):
        board_copy = deepcopy(self._board)
        src_piece = board_copy.get_piece(command.src)
        if src_piece is None:
            return False
        if (self._status == ChessGame.STATUS_WHITE_MOVE and src_piece.color == Piece.BLACK) or \
                (self._status == ChessGame.STATUS_BLACK_MOVE and src_piece.color == Piece.WHITE):
            return False
        if command.dst not in src_piece.get_moveable_positions(board_copy) and \
                command.dst not in src_piece.get_threatened_positions(board_copy):
            return False
        board_copy.execute_move(command)
        for piece in board_copy.pieces:
            if self._status == ChessGame.STATUS_WHITE_MOVE and \
                    board_copy.white_king_position in piece.get_threatened_positions(board_copy):
                return False
            elif self._status == ChessGame.STATUS_BLACK_MOVE and \
                    board_copy.black_king_position in piece.get_threatened_positions(board_copy):
                return False
        return True

    def _parse_command(self):
        input_ = input()
        return MoveCommand.from_string(input_)

    def get_game_state(self):
        return ChessGameState(self._board.pieces, self._board.size)
コード例 #3
0
def test_all_possible_moves():
    board = ChessBoard("8/7R/6R1/8/8/4K3/7k/8 w - - 0 1")
    assert board.all_moves("b") == {}
    board = ChessBoard("8/7R/8/8/8/4K1R1/7k/8 w - - 0 1")
    assert board.all_moves("b") == {"h2": ["g3"]}
    board = ChessBoard("8/7R/8/3K4/8/1p4R1/2b4k/8 w - - 0 1")
    assert board.all_moves("b") == {"c2": ["h7"], "h2": ["g3"]}
コード例 #4
0
ファイル: chessai.py プロジェクト: centreon/chess-ai
    def __init__(
        self,
        ai_depth=3,
        starting_pos="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
    ):
        """
        input: ai_depth is amount of moves to search into the future.

        in the future, we can try to add different parameter constrains
        # such as time limit, cpu compute speed.
        """
        ChessBoard.__init__(self, starting_pos=starting_pos)
        self.depth = ai_depth
コード例 #5
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption('Шахматы')
        pygame.display.set_icon(pygame.image.load('images/icon.jpg'))
        self.screen = pygame.display.set_mode((860, 565))

        self.clock = pygame.time.Clock()
        self.board = ChessBoard()

        self.main_menu = pygame.image.load('images/main_menu.jpg')
        self.main_menu = pygame.transform.scale(self.main_menu, (860, 565))
        self.board_img = pygame.image.load('images/board.png')
        self.win_background = pygame.Surface((860, 565))
        self.poss_target = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.target_image = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.target_enemy_image = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.move_history = pygame.Surface((270, 310))

        self.win_background.set_alpha(150)
        self.poss_target.set_alpha(125)
        self.target_image.set_alpha(125)
        self.target_enemy_image.set_alpha(125)

        pygame.draw.rect(self.win_background, (255, 255, 255),
                         self.win_background.get_rect())
        pygame.draw.rect(self.poss_target, (173, 255, 182),
                         self.poss_target.get_rect())
        pygame.draw.rect(self.target_image, (173, 255, 255),
                         self.target_image.get_rect())
        pygame.draw.rect(self.target_enemy_image, (255, 173, 173),
                         self.target_enemy_image.get_rect())

        self.w_figures_captured_images = []
        self.b_figures_captured_images = []

        self.new_game = False
        self.pause = True
        self.winner = None

        self.target = None
        self.target_poss_moves = ()
        self.all_poss_moves = self.get_all_poss_moves()

        self.main_loop()
コード例 #6
0
ファイル: app.py プロジェクト: MichalGawor/sigmaChess
    def launchSingleplayerGame(self):
        # board client handles logic of chess board moves and attacks
        self.boardClient = ChessBoard()
        # view client handles drawing everything
        self.viewClient = AppWindow(self.root, self.boardClient)
        self.viewClient.pack()

        self.bindGameEvents()
コード例 #7
0
ファイル: ai.py プロジェクト: ykozxy/GoBang
def min_max_search(board: ChessBoard, ai_num: int, control_bar, depth: int = 6):
    """
    Min-max search to find the best place of setting chess
    :param control_bar: class Bar from main.py
    :param ai_num: The player number which ai is
    :param board: chessboard
    :param depth: depth of calculation NOTE: GREAT NUMBER OF DEPTH MAY SPEND A LONG TIME
    :return: the coordinate of best position
    """
    # If the board is empty
    for x in board.board:
        for y in x:
            if y != 0:
                break
        else:
            continue
        break
    else:
        control_bar.exit()
        return 7, 7

    max_v = -99999999
    points = points_gen(board, ai_num)
    candidates = []

    # Show progress bar
    for point in points:
        control_bar.step_in()

        board.board[point[0]][point[1]] = ai_num
        cur_v = search_point(
            board, ai_num, 1 if ai_num == 2 else 2, depth, -9999999999, 9999999999
        )
        if cur_v == max_v:
            candidates.append(point)
        elif cur_v > max_v:
            max_v = cur_v
            candidates = [point]
        board.board[point[0]][point[1]] = 0
    result = sample(candidates, 1)[0]
    control_bar.exit()
    return result
コード例 #8
0
ファイル: app.py プロジェクト: MichalGawor/sigmaChess
    def launchMultiplayerGame(self):
        # connection handler makes chess playable in multiplayer
        self.multiplayerClient = ConnectionHandler()

        # board client handles logic of chess board moves and attacks
        self.boardClient = ChessBoard()
        # view client handles drawing everything
        self.viewClient = AppWindow(self.root, self.boardClient)
        self.viewClient.pack()

        self.bindGameEvents()
コード例 #9
0
ファイル: ai.py プロジェクト: ykozxy/GoBang
def search_point(
        board: ChessBoard, ai_num: int, player: int, depth: int, alpha: int, beta: int
):
    """
    This function use alpha-beta pruning to calculate best-fit point
    :param board: chessboard
    :param ai_num: The player number which ai is
    :param player: current player number
    :param depth: maximum depth of calculation
    :param alpha: max value when calculate
    :param beta: min value when calculate
    :return: the maximum score of the position
    """
    # Computer - Human
    split_board = list(board.split_board())
    v = board.evaluate(ai_num, split_board) - board.evaluate(
        1 if ai_num == 2 else 2, split_board
    )
    if depth <= 0 or board.win_determine() in [WHITE_WIN, BLACK_WIN, TIE]:
        return v
    points = points_gen(board, player)

    if player == ai_num:
        # Computer turn, max level
        for point in points:
            board.board[point[0]][point[1]] = player
            cur_v = search_point(
                board, ai_num, 1 if player == 2 else 2, depth - 1, alpha, beta
            )
            board.board[point[0]][point[1]] = 0
            alpha = max(alpha, cur_v)
            # Prune
            if beta < alpha:
                # print("Pruned {} nodes".format(len(points) - points.index(point) - 1))
                break
        return alpha
    else:
        # Human turn, min level
        for point in points:
            board.board[point[0]][point[1]] = player
            cur_v = search_point(
                board, ai_num, 1 if player == 2 else 2, depth - 1, alpha, beta
            )
            board.board[point[0]][point[1]] = 0
            beta = min(beta, cur_v)
            # Prune
            if beta < alpha:
                print("Pruned {} nodes".format(len(points) - points.index(point) - 1))
                break
        return beta
コード例 #10
0
ファイル: game.py プロジェクト: just8do8it/TUES
    def __init__(self, w_figs, b_figs, board):
        chess_board = ChessBoard()
        ok = 1
        passed = -1

        if w_figs == [] and b_figs == [] and board == None:
            w_figures, b_figures = self.generate_figures(chess_board)
        else:
            w_figures, b_figures, chess_board = w_figs, b_figs, board

        chess_board.change_board(w_figures, b_figures)

        alive_figures = []
        for x in w_figures:
            alive_figures.append([x.curr_pos_ltr, x.curr_pos_num, x.player])
        for x in b_figures:
            alive_figures.append([x.curr_pos_ltr, x.curr_pos_num, x.player])

        w_player = Player("white", w_figures)
        b_player = Player("black", b_figures)

        self.chess_board = chess_board
        self.w_player = w_player
        self.b_player = b_player
        self.command_counter = None
        self.is_moved = None
        self.curr_player = None
        self.opponent = None
        self.alive_figures = alive_figures
        self.ok = ok
        self.passed = passed
        self.w_check = 0
        self.b_check = 0
        self.w_checkmate = 0
        self.b_checkmate = 0
        self.draw = 0
        self.ended = 0
コード例 #11
0
def game_setup():
    chess_board = ChessBoard()
    chess_board.create_board()
    # print(chess_board.get_board())
    move = PawnMovementLogic(chess_board.get_board(), 1, 2, 3, 2,
                             ChessBoard.PLAYER_ONE_INDICATOR, True)
    move.move_pawn()
    move = PawnMovementLogic(chess_board.get_board(), 6, 3, 5, 3,
                             ChessBoard.PLAYER_TWO_INDICATOR, True)
    move.move_pawn()
    move = PawnMovementLogic(chess_board.get_board(), 3, 2, 4, 2,
                             ChessBoard.PLAYER_ONE_INDICATOR, False)
    move.move_pawn()
    print("here_1")
    move = PawnMovementLogic(chess_board.get_board(), 5, 3, 4, 2,
                             ChessBoard.PLAYER_TWO_INDICATOR, False)
    move.capture_piece()
コード例 #12
0
ファイル: app.py プロジェクト: MichalGawor/sigmaChess
    def __init__(self):
        self.root = Tk()

        #board client handles logic of chess board moves and attacks
        self.boardClient = ChessBoard()
        #view client handles drawing everything
        self.viewClient = AppWindow(self.root, self.boardClient)
        self.viewClient.pack()

        # connection handler makes chess playable in multiplayer
        self.multiplayerClient = ConnectionHandler()
        #event handler handles event performed on windows
        self.eventsClient = EventHandler(self.boardClient, self.viewClient,
                                         self.multiplayerClient)
        self.root.mainloop()
コード例 #13
0
def run_game():
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Chess")
    board = ChessBoard(settings, screen)
    board.set_initial_board()

    while True:
        gf.check_events(board)
        gf.update_board(board)
        screen.fill(settings.bg_color)
        board.draw()
        pygame.display.flip()
コード例 #14
0
ファイル: main.py プロジェクト: vtad4f/chess-ui
    def __init__(self, exe_path, turn_limit_s, thread):
        """
         BRIEF  Set up the UI
      """
        super().__init__()

        self.board = ChessBoard(self)

        if os.path.isfile(exe_path):
            self.player_b = AiPlayer(exe_path, turn_limit_s, Player.BLACK,
                                     thread, self.board)
            self.player_w = AiPlayer(exe_path, turn_limit_s, Player.WHITE,
                                     thread, self.board)
        else:
            self.player_b = Player(Player.BLACK, thread, self.board)
            self.player_w = Player(Player.WHITE, thread, self.board)

        player_options_b = PlayerOptions(self.player_b, self)
        board_controls = BoardControls(self.board)
        player_options_w = PlayerOptions(self.player_w, self)

        v_layout = QVBoxLayout()
        v_layout.addStretch()
        v_layout.addWidget(player_options_b)
        v_layout.addStretch()
        v_layout.addWidget(board_controls)
        v_layout.addStretch()
        v_layout.addWidget(player_options_w)
        v_layout.addStretch()

        h_layout = QHBoxLayout()
        h_layout.addWidget(self.board)
        h_layout.addLayout(v_layout)
        h_layout.addSpacing(50)

        self.setLayout(h_layout)
コード例 #15
0
class MainView(QMainWindow):
    def __init__(self):
        super().__init__()
        self.board = ChessBoard(self)
        self.init()

    def init(self):
        self.create_menu()
        self.layout()

        self.setWindowTitle("NChess")
        self.setWindowIcon(QIcon("rsc/icon.png"))
        self.resize(1160, 900)

        self.center()

        self.show()

        self.board.startpos()

    def layout(self):
        layout = BorderLayout()
        layout.addWidget(self.board, BorderLayout.Center)

        vbox = QVBoxLayout()

        show_best_move = QCheckBox("Show Best Move")
        show_best_move.setChecked(True)
        show_best_move.stateChanged.connect(self.board.show_best_move_changed)
        vbox.addWidget(show_best_move)

        engine_selector = QComboBox()
        engine_selector.addItem("Stockfish")
        engine_selector.addItem("Leela")
        engine_selector.addItem("Komodo")
        engine_selector.addItem("NCE")
        engine_selector.currentIndexChanged.connect(
            lambda: self.board.change_engine(engine_selector.currentText()))
        vbox.addWidget(engine_selector)

        self.game_score = QLabel()
        self.game_score.setText("Score: 0")
        self.game_score.setWordWrap(True)
        self.game_score.setMaximumWidth(200)
        self.game_score.setMinimumWidth(200)
        vbox.addWidget(self.game_score)

        next_btn = QPushButton()
        next_btn.setText("Next")
        next_btn.clicked.connect(lambda: self.board.next_move())
        vbox.addWidget(next_btn)

        undo_btn = QPushButton()
        undo_btn.setText("Back")
        undo_btn.clicked.connect(lambda: self.board.back_move())
        vbox.addWidget(undo_btn)

        reset_btn = QPushButton()
        reset_btn.setText("Reset")
        reset_btn.clicked.connect(lambda: self.board.startpos())
        vbox.addWidget(reset_btn)

        self.fen_field = QLineEdit()
        self.fen_field.setText(STARTING_FEN)
        self.fen_field.setMinimumWidth(200)
        self.fen_field.setMaximumWidth(200)
        vbox.addWidget(self.fen_field)

        set_fen_btn = QPushButton()
        set_fen_btn.setText("Set fen")
        set_fen_btn.clicked.connect(
            lambda: self.board.loadfen(self.fen_field.text()))
        vbox.addWidget(set_fen_btn)

        self.engine_thoughts = QLabel()
        self.engine_thoughts.setText("...")
        self.engine_thoughts.setWordWrap(True)
        self.engine_thoughts.setMaximumWidth(200)
        self.engine_thoughts.setMinimumWidth(200)
        vbox.addWidget(self.engine_thoughts)

        vbox.addStretch(1)

        east_widget = QWidget()
        east_widget.setLayout(vbox)
        layout.addWidget(east_widget, BorderLayout.East)

        central_widget = QWidget()
        central_widget.setLayout(layout)

        self.setCentralWidget(central_widget)

    def create_menu(self):
        menubar = self.menuBar()
        file = menubar.addMenu("File")

        exit_action = QAction(QIcon("rsc/exit.png"), "Exit", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)

        file.addAction(exit_action)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def mousePressEvent(self, event):
        self.board.mouse_press(event)

    def mouseReleaseEvent(self, event):
        self.board.mouse_release(event)

    def closeEvent(self, event):
        self.board.engine_handler.stockfish.quit()
        self.board.engine_handler.leela.quit()
        self.board.engine_handler.komodo.quit()
        self.board.engine_handler.nce.quit()
コード例 #16
0
ファイル: chess.py プロジェクト: zahari/pyChess
Mohammad Kebbi; 1496572
Sheetal Gour; 1547017

Main Functon that initializes the User Interface class to run the chess
Game on pygame
"""

import pygame
from board import ChessBoard
from userInterface import UserInterface

if __name__ == "__main__":
    pygame.init()  # initialize pygame
    # set window size for create pygame window for chess program
    surface = pygame.display.set_mode(
        [600, 600], 0, 0
    )  # (Re adjust the coordinate if you want to change size of game's window

    # sets the title of the window
    pygame.display.set_caption('pyChess')

    # Initialize chessBoard class. Used for our interface
    Board = ChessBoard()

    # create and initialize User interface object to run pygame chess program
    UI = UserInterface(surface, Board)

    UI.playGame()  # call play game function to start the game

    pygame.quit()  # Close program
コード例 #17
0
class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption('Шахматы')
        pygame.display.set_icon(pygame.image.load('images/icon.jpg'))
        self.screen = pygame.display.set_mode((860, 565))

        self.clock = pygame.time.Clock()
        self.board = ChessBoard()

        self.main_menu = pygame.image.load('images/main_menu.jpg')
        self.main_menu = pygame.transform.scale(self.main_menu, (860, 565))
        self.board_img = pygame.image.load('images/board.png')
        self.win_background = pygame.Surface((860, 565))
        self.poss_target = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.target_image = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.target_enemy_image = pygame.Surface(
            (self.board.cell_size, self.board.cell_size))
        self.move_history = pygame.Surface((270, 310))

        self.win_background.set_alpha(150)
        self.poss_target.set_alpha(125)
        self.target_image.set_alpha(125)
        self.target_enemy_image.set_alpha(125)

        pygame.draw.rect(self.win_background, (255, 255, 255),
                         self.win_background.get_rect())
        pygame.draw.rect(self.poss_target, (173, 255, 182),
                         self.poss_target.get_rect())
        pygame.draw.rect(self.target_image, (173, 255, 255),
                         self.target_image.get_rect())
        pygame.draw.rect(self.target_enemy_image, (255, 173, 173),
                         self.target_enemy_image.get_rect())

        self.w_figures_captured_images = []
        self.b_figures_captured_images = []

        self.new_game = False
        self.pause = True
        self.winner = None

        self.target = None
        self.target_poss_moves = ()
        self.all_poss_moves = self.get_all_poss_moves()

        self.main_loop()

    def main_loop(self):
        running = True

        while running:
            self.draw_window()

            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                if event.type == MOUSEBUTTONUP and event.button == 1:
                    self.get_click()
            self.clock.tick(60)

    def draw_window(self):
        if not self.new_game:
            # Вывод главного меню
            self.draw_main_menu()
        else:
            # Вывод доски
            self.draw_board()
        if self.winner:
            # Вывод победного меню
            self.draw_win_menu()
        pygame.display.update()

    def reset(self):
        # Обнуление игры
        self.screen.fill((250, 232, 167))
        self.new_game = False
        self.pause = True
        self.winner = None
        self.figure_untarget()
        self.all_poss_moves = self.get_all_poss_moves()
        self.board.reset()
        self.draw_window()

    def draw_main_menu(self):
        # Главное меню
        new_game = pygame.Surface((400, 85))
        exit = pygame.Surface((250, 85))

        new_game.set_alpha(150)
        exit.set_alpha(150)
        # Фон для кнопок
        pygame.draw.rect(new_game, (105, 105, 105), new_game.get_rect())
        pygame.draw.rect(exit, (105, 105, 105), exit.get_rect())

        self.screen.blit(self.main_menu, (0, 0))
        self.screen.blit(new_game, (225, 210))
        self.screen.blit(exit, (305, 310))

        self.message_display('Новая игра', (425, 250),
                             font_color=(255, 255, 255))
        self.message_display('Выход', (425, 350), font_color=(255, 255, 255))

        pygame.display.update()

    def draw_board(self):
        # Отрисовка всего на доске
        self.screen.fill((250, 232, 167))
        self.screen.blit(self.board_img, (0, 0))

        # Выделение фигуры
        if not self.pause:
            if self.target:
                self.screen.blit(self.target_image,
                                 self.get_coords(self.target.pos))
                # Выделение доступных для хода клеток
                if self.target_poss_moves:
                    for move in self.target_poss_moves:
                        # Если пустая
                        if self.board.field[move[0]][move[1]]:
                            self.screen.blit(self.target_enemy_image,
                                             self.get_coords(move))
                        # Если вражеская фигура
                        else:
                            self.screen.blit(self.target_image,
                                             self.get_coords(move))
            else:
                # Фигуры текущего игрока, которые могут ходить
                for cell in self.all_poss_moves.keys():
                    if self.all_poss_moves[cell]:
                        self.screen.blit(self.poss_target,
                                         self.get_coords(cell))

        # Отрисовка координатного поля на доске
        for i in range(8, 0, -1):
            x, y = self.get_coords((0, i - 1))
            self.message_display('%s' % i,
                                 (int(x - self.board.edge * 0.5),
                                  int(y + self.board.cell_size * 0.5)), 24)
            x, y = self.get_coords((i - 1, 7))
            self.message_display('%s' % self.get_cell_name((i - 1, 7)),
                                 (int(x + self.board.edge),
                                  int(y + self.board.cell_size * 1.25)), 24)

        # Отрисовка фигур
        for figure in self.board.alive_figures():
            figure_pos = self.get_coords(figure.pos)
            figure_img = pygame.image.load(figure.image)
            figure_img = pygame.transform.scale(figure_img, (50, 50))
            self.screen.blit(figure_img,
                             (figure_pos[0] + 7, figure_pos[1] + 7))

        # Отрисовка бокового меню
        self.draw_side_menu()

    def draw_side_menu(self):
        # Боковое меню
        player = 'белых' if self.board.curr_player == 'w' else 'черных'
        history_list = self.board.move_history
        hist_y = 3
        b_x, b_y = 570, 5
        w_x, w_y = 570, 505

        self.move_history.fill((250, 232, 167))
        self.message_display('Ход: %s' % player, (710, 120), 38)

        # Отображение истории ходов
        for move in history_list if len(
                history_list) < 12 else history_list[-12:]:
            move = str(history_list.index(move) + 1) + '. ' + move
            self.message_display(move, (15, hist_y), 23, align_left=1)
            hist_y += 25

        # Вставка таблицы на основной экран
        self.screen.blit(self.move_history, (577, 160))
        pygame.draw.rect(self.screen, (0, 0, 0), (577, 160, 270, 310), 3)

        # Отображение побеждённых чёрных фигур
        i = 0
        for b_fig in self.b_figures_captured_images:
            # Если фигур становится больше 8, то отрисовка идёт в 2 ряда
            if i == 9:
                b_x = 570
                b_y += 30

            b_fig = pygame.image.load(b_fig)
            b_fig = pygame.transform.scale(b_fig, (25, 25))
            self.screen.blit(b_fig, (b_x, b_y))
            b_x += 30
            i += 1

        # Отображение побеждённых белых фигур
        i = 0
        for w_fig in self.w_figures_captured_images:
            # Если фигур становится больше 8, то отрисовка идёт в 2 ряда
            if i == 9:
                w_x = 570
                w_y += 30
            w_fig = pygame.image.load(w_fig)
            w_fig = pygame.transform.scale(w_fig, (25, 25))
            self.screen.blit(w_fig, (w_x, w_y))
            w_x += 30
            i += 1

    def draw_win_menu(self):
        # Победное меню
        yes = pygame.Surface((90, 75))
        no = pygame.Surface((90, 75))

        yes.set_alpha(100)
        no.set_alpha(100)
        # Фон под кнопки
        pygame.draw.rect(yes, (100, 100, 100), yes.get_rect())
        pygame.draw.rect(no, (100, 100, 100), no.get_rect())
        # Отрисовка фона
        self.screen.blit(self.win_background, (0, 0))
        self.screen.blit(yes, (255, 365))
        self.screen.blit(no, (455, 365))

        self.message_display('Шах и Мат!', (425, 130))
        self.message_display('%s победили!' % self.winner, (425, 230))
        self.message_display('Вернутся в главное меню?', (425, 330), 56)
        self.message_display('Да', (300, 400), 48)
        self.message_display('Нет', (500, 400), 48)

        pygame.display.update()

    def get_coords(self, cell):
        # Клетка в координаты
        return cell[0] * self.board.cell_size + self.board.edge,\
               cell[1] * self.board.cell_size + self.board.edge

    def get_cell(self, coords):
        # Координаты в клетку
        x, y = (coords[0] - self.board.edge) // self.board.cell_size, \
               (coords[1] - self.board.edge) // self.board.cell_size
        if 0 <= x <= 7 and 0 <= y <= 7:
            return x, y

    def get_cell_name(self, cell, for_history=0):
        # Возвращает название клетки в виде ЦИФРАБУКВА (пример: (1,3) => 'B3')
        conversions = {
            0: 'A',
            1: 'B',
            2: 'C',
            3: 'D',
            4: 'E',
            5: 'F',
            6: 'G',
            7: 'H'
        }
        if for_history:
            return str(conversions[cell[0]]) + str(cell[1] + 1)
        return str(conversions[cell[0]])

    def get_click(self):
        x, y = pygame.mouse.get_pos()
        # Обработка клика мыши
        # Получение клетки из координат
        cell = self.get_cell((x, y))
        # Если не пауза
        if not self.pause:
            if cell:
                # Фигура на клетке. Нужна для смены фокуса на другую союзную фигуру без повторного клика по текущей.
                cell_figure = self.board.figure_at(cell)
                # Если фигура не выбрана:
                if not self.target:
                    # Фокус на данную клетку
                    if self.is_curr_player_figure_at(cell):
                        self.figure_target(cell)
                # Если фигура уже выбрана:
                else:
                    # Убирает фокус при повторном нажатии
                    if cell == self.target.pos:
                        self.figure_untarget()
                    # Меняет фокус на другую союзную фигуру
                    elif cell_figure and cell_figure.color == self.board.curr_player:
                        self.figure_target(cell)
                    # Если клетка находится в доступных шагах:
                    elif cell in self.target_poss_moves:
                        # Является ли фигура королём
                        if self.target.name == 'King' and cell in self.board.castle_moves_for_player(
                        ):
                            # Castle that king
                            self.add_move(self.target.pos, cell)
                            self.board.castle_king(self.target, cell)
                        else:
                            # Движение фигуры
                            self.add_move(self.target.pos, cell)
                            self.move_figure(self.target, cell)
                            # Повышение пешки
                            if self.target.name == 'Pawn' and (cell[1] == 0 or
                                                               cell[1] == 7):
                                self.board.field[cell[0]][cell[1]] = None
                                self.board.field[cell[0]][cell[1]] = Queen(
                                    self.board.curr_player, cell)

                        # Снятие фокуса
                        self.figure_untarget()
                        # Смена игрока
                        self.change_player()
                        # Проверка на шах и мат, и обновление списка со всеми возможными ходами
                        self.all_poss_moves = self.get_all_poss_moves()
                        checkmate = True
                        for figures_pos in self.all_poss_moves:
                            if len(self.all_poss_moves[figures_pos]) != 0:
                                checkmate = False
                        # Если шах и мат:
                        if checkmate:
                            # Определение победителя
                            self.winner = 'Белые' if self.board.curr_player == 'b' else 'Чёрные'
                            self.pause = True
                            self.draw_board()
                            self.draw_win_menu()
        # Иначе переключение на победное/главное меню
        else:
            # Если есть победитель, то переключение на победное меню
            if self.winner:
                if 365 <= y <= 440:
                    # Если "да", то происходит сброс и возврат в гланое меню
                    if 255 <= x <= 345:
                        self.reset()
                    # Если "нет", то выход из игры
                    elif 455 <= x <= 545:
                        quit()
                    else:
                        pass
            # Иначе главное меню
            else:
                # Если "Новая игра"
                if 225 <= x <= 625 and 210 <= y <= 295:
                    self.new_game = True
                    self.pause = False
                # Если "Выход"
                elif 305 <= x <= 555 and 310 <= y <= 395:
                    quit()

    def get_target_poss_moves(self):
        # Получить возможные ходы
        return self.all_poss_moves[self.target.pos]

    def get_all_poss_moves(self):
        # Получить все возожные ходы для игрока
        moves = {}
        figures = self.board.curr_player_figures()
        for figure in figures:
            f_moves = self.board.possible_moves_for(figure)
            moves[figure.pos] = self.board.is_player_in_check(figure, f_moves)
        return moves

    def figure_target(self, cell):
        # Фокус на фигуру
        self.target = self.board.figure_at(cell)
        self.target_poss_moves = self.get_target_poss_moves()

    def figure_untarget(self):
        # Снятие фокуса
        self.target = None
        self.target_poss_moves = None

    def is_curr_player_figure_at(self, cell):
        # Является ли фигура фигруой текущего игрока
        for figure in self.board.curr_player_figures():
            if cell == figure.pos:
                return True

    def change_player(self):
        # Смена игрока
        self.board.curr_player = 'w' if self.board.curr_player == 'b' else 'b'

    def move_figure(self, figure, cell):
        # Движение фигуры и захват срезанной фигуры, если есть
        figure_captured = self.board.move_figure(figure, cell)
        if figure_captured:
            self.figure_was_captured(figure_captured)

    def add_move(self, pos_1, pos_2):
        # Добавление хода в историю
        name = 'Б: ' if self.board.curr_player == 'w' else 'Ч: '
        move = name + self.get_cell_name(
            pos_1, for_history=1) + ' => ' + self.get_cell_name(pos_2,
                                                                for_history=1)
        self.board.move_history.append(move)

    def figure_was_captured(self, figure):
        # Получегие изображения захваченной фигуры
        if figure.color == 'w':
            self.w_figures_captured_images.append(figure.image)
        else:
            self.b_figures_captured_images.append(figure.image)

    def message_display(self,
                        text,
                        coords,
                        font_size=68,
                        font_color=(0, 0, 0),
                        align_left=0):
        # Отображение сообщения
        font_dir = pygame.font.match_font('verdana')
        text_font = pygame.font.Font(font_dir, font_size)
        text_surface = text_font.render(text, True, font_color)
        if not align_left:
            text_rect = text_surface.get_rect()
            text_rect.center = (coords)
            self.screen.blit(text_surface, text_rect)
        else:
            self.move_history.blit(text_surface, coords)
コード例 #18
0
ファイル: boardwindow.py プロジェクト: MichalGawor/sigmaChess
                            self.__translateBoardCoords(i, j),
                            image=self.piecesImages[tilePiece.name + "Black"])

    def addBinding(self, eventName, function):
        self.piecesCanvas.bind(eventName, function)

    def __translateBoardCoords(self, boardPositionX, boardPositionY):
        """translates integer position on the chess board to pixel position in canvas"""
        return (boardPositionX * 64 + 32,
                (64 * 8) - (boardPositionY * 64) - 32)


############################################################################
###############################DEBUG########################################

if __name__ == "__main__":
    from board import ChessBoard

    x = ChessBoard()
    root = Tk()
    app = BoardWindow(root)
    app.drawBoard(x)

    input("w")
    p = x.getPiece(0, 1)
    x.movePiece(p, 0, 2)
    app.drawBoard(x)
    root.mainloop()

############################################################################
############################################################################
コード例 #19
0
    def test_taking_figures(self):
        chess_board = ChessBoard()

        b_R1 = Figure("R1", chess_board.board, 'A', 8, "black")
        b_H1 = Figure("H1", chess_board.board, 'B', 8, "black")
        b_B1 = Figure("B1", chess_board.board, 'C', 8, "black")
        b_Q1 = Figure("Q1", chess_board.board, 'D', 8, "black")
        b_K1 = Figure("K1", chess_board.board, 'E', 8, "black")
        b_B2 = Figure("B2", chess_board.board, 'F', 8, "black")
        b_H2 = Figure("H2", chess_board.board, 'G', 8, "black")
        b_R2 = Figure("R2", chess_board.board, 'H', 8, "black")
        b_P1 = Figure("P1", chess_board.board, 'A', 7, "black")
        b_P2 = Figure("P2", chess_board.board, 'B', 7, "black")
        b_P3 = Figure("P3", chess_board.board, 'C', 7, "black")
        b_P4 = Figure("P4", chess_board.board, 'D', 7, "black")
        b_P5 = Figure("P5", chess_board.board, 'E', 7, "black")
        b_P6 = Figure("P6", chess_board.board, 'F', 7, "black")
        b_P7 = Figure("P7", chess_board.board, 'G', 7, "black")
        b_P8 = Figure("P8", chess_board.board, 'H', 7, "black")

        w_R1 = Figure("R1", chess_board.board, 'A', 1, "white")
        w_H1 = Figure("H1", chess_board.board, 'B', 1, "white")
        w_B1 = Figure("B1", chess_board.board, 'C', 1, "white")
        w_Q1 = Figure("Q1", chess_board.board, 'D', 1, "white")
        w_K1 = Figure("K1", chess_board.board, 'E', 1, "white")
        w_B2 = Figure("B2", chess_board.board, 'F', 1, "white")
        w_H2 = Figure("H2", chess_board.board, 'G', 1, "white")
        w_R2 = Figure("R2", chess_board.board, 'H', 1, "white")
        w_P1 = Figure("P1", chess_board.board, 'A', 2, "white")
        w_P2 = Figure("P2", chess_board.board, 'B', 2, "white")
        w_P3 = Figure("P3", chess_board.board, 'C', 2, "white")
        w_P4 = Figure("P4", chess_board.board, 'D', 2, "white")
        w_P5 = Figure("P5", chess_board.board, 'E', 2, "white")
        w_P6 = Figure("P6", chess_board.board, 'F', 2, "white")
        w_P7 = Figure("P7", chess_board.board, 'G', 2, "white")
        w_P8 = Figure("P8", chess_board.board, 'H', 2, "white")

        w_figs = [
            w_R1, w_H1, w_B1, w_Q1, w_K1, w_B2, w_H2, w_R2, w_P1, w_P2, w_P3,
            w_P4, w_P5, w_P6, w_P7, w_P8
        ]
        b_figs = [
            b_R1, b_H1, b_B1, b_Q1, b_K1, b_B2, b_H2, b_R2, b_P1, b_P2, b_P3,
            b_P4, b_P5, b_P6, b_P7, b_P8
        ]

        moves = [
            "A2-A4",
            "B7-B5",
            "C2-C4",
            "D7-D5",
            "E2-E4",
            "F7-F5",  # moving the pawns 
            "G2-G4",
            "H7-H5",
            "A4-B5",
            "D5-C4",
            "E4-F5",
            "H5-G4",  # out of the way
            "A1-A7",
            "A8-A7",
            "F1-C4",
            "E8-F7",
            "C4-E6",
            "F7-E6",
            "B1-A3",
            "D8-D2",
            "C1-D2",
            "G8-H6",
            "E1-E2",
            "H6-F5",
            "exit"
        ]

        board = [{
            "A": None,
            "B": b_H1,
            "C": b_B1,
            "D": None,
            "E": None,
            "F": b_B2,
            "G": None,
            "H": b_R2
        }, {
            "A": b_R1,
            "B": None,
            "C": b_P3,
            "D": None,
            "E": b_P5,
            "F": None,
            "G": b_P7,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": b_K1,
            "F": None,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": w_P1,
            "C": None,
            "D": None,
            "E": None,
            "F": b_H2,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": None,
            "G": b_P8,
            "H": None
        }, {
            "A": w_H1,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": None,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": w_P2,
            "C": None,
            "D": w_B1,
            "E": w_K1,
            "F": w_P6,
            "G": None,
            "H": w_P8
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": w_Q1,
            "E": None,
            "F": None,
            "G": w_H2,
            "H": w_R2
        }]

        board = reverse_board(board)

        game = Game(w_figs, b_figs, chess_board)
        game.run(moves)

        self.assertEqual(game.chess_board.board, board)
        self.assertEqual(game.w_player.won_figures,
                         [b_P2, b_P6, b_P1, b_P4, b_Q1])
        self.assertEqual(game.b_player.won_figures,
                         [w_P3, w_P7, w_R1, w_B2, w_P4, w_P5])
コード例 #20
0
def main():

    chess_board = ChessBoard()
    chess_board.start()
コード例 #21
0
def main():
    board = ChessBoard('./images/tests/2.png')
    for column in board.get_board():
        print(column)
コード例 #22
0
ファイル: main.py プロジェクト: ykozxy/GoBang
    def __init__(self, pack_label: bool = False):
        self.chessBoard = ChessBoard("p", "p")
        self.root = Tk()
        self.root.resizable(width=FALSE, height=FALSE)
        self.root.title("GoBang")

        self.button_freeze = False

        # Total chessboard
        self.boardFrame = Frame(self.root)

        # Menu
        self._init_menu()

        # Create canvas
        self.gap = 25
        self.mainBoard = Canvas(self.boardFrame,
                                width=self.gap * 16,
                                height=self.gap * 16)  # size: 400 * 400
        self._draw_lines()

        # Bind mouse action
        self.mainBoard.bind("<Button-1>", self.mouse_click)

        # Generate all positions
        self.all_positions = {(x, y)
                              for x in range(self.gap, self.gap * 16, self.gap)
                              for y in range(self.gap, self.gap * 16, self.gap)
                              }
        self.operate = []
        # print(self.all_positions)

        # Create control frame
        self.controlFrame = Labelframe(self.root, text="Control Panel")
        self.turn = Label(self.controlFrame, text="Next player: black")
        self.turn.pack(pady=10)
        # Evaluate part
        self.score1 = Label(self.controlFrame, text="Black: 0")
        self.score2 = Label(self.controlFrame, text="White: 0")
        self.evaluateButton = Button(self.controlFrame,
                                     text="Evaluate",
                                     command=self.button_evaluate)
        # AI part
        self.aiCalculateButton = Button(self.controlFrame,
                                        text="AI Calculate (beta)",
                                        command=self.ai_calculate)
        self.score1.pack()
        self.score2.pack()
        # self.evaluateButton.pack()
        self.aiCalculateButton.pack(pady=10)

        # Create Label frames
        self.horLabel = Frame(self.boardFrame)
        self.verLabel = Frame(self.boardFrame)
        self._draw_label()

        # Pack Widgets
        if pack_label:
            self.horLabel.grid(row=0, column=1, pady=0)
            self.verLabel.grid(row=1, column=0, padx=0)
        self.mainBoard.grid(row=1, column=1, padx=0, pady=0)
        self.boardFrame.grid()
        # Some bugs here, cannot click canvas after click button....
        self.controlFrame.grid(row=0, column=1, padx=5)
コード例 #23
0
ファイル: main.py プロジェクト: ykozxy/GoBang
class ChessBoardInterface:
    def __init__(self, pack_label: bool = False):
        self.chessBoard = ChessBoard("p", "p")
        self.root = Tk()
        self.root.resizable(width=FALSE, height=FALSE)
        self.root.title("GoBang")

        self.button_freeze = False

        # Total chessboard
        self.boardFrame = Frame(self.root)

        # Menu
        self._init_menu()

        # Create canvas
        self.gap = 25
        self.mainBoard = Canvas(self.boardFrame,
                                width=self.gap * 16,
                                height=self.gap * 16)  # size: 400 * 400
        self._draw_lines()

        # Bind mouse action
        self.mainBoard.bind("<Button-1>", self.mouse_click)

        # Generate all positions
        self.all_positions = {(x, y)
                              for x in range(self.gap, self.gap * 16, self.gap)
                              for y in range(self.gap, self.gap * 16, self.gap)
                              }
        self.operate = []
        # print(self.all_positions)

        # Create control frame
        self.controlFrame = Labelframe(self.root, text="Control Panel")
        self.turn = Label(self.controlFrame, text="Next player: black")
        self.turn.pack(pady=10)
        # Evaluate part
        self.score1 = Label(self.controlFrame, text="Black: 0")
        self.score2 = Label(self.controlFrame, text="White: 0")
        self.evaluateButton = Button(self.controlFrame,
                                     text="Evaluate",
                                     command=self.button_evaluate)
        # AI part
        self.aiCalculateButton = Button(self.controlFrame,
                                        text="AI Calculate (beta)",
                                        command=self.ai_calculate)
        self.score1.pack()
        self.score2.pack()
        # self.evaluateButton.pack()
        self.aiCalculateButton.pack(pady=10)

        # Create Label frames
        self.horLabel = Frame(self.boardFrame)
        self.verLabel = Frame(self.boardFrame)
        self._draw_label()

        # Pack Widgets
        if pack_label:
            self.horLabel.grid(row=0, column=1, pady=0)
            self.verLabel.grid(row=1, column=0, padx=0)
        self.mainBoard.grid(row=1, column=1, padx=0, pady=0)
        self.boardFrame.grid()
        # Some bugs here, cannot click canvas after click button....
        self.controlFrame.grid(row=0, column=1, padx=5)

    def ai_calculate(self):
        """
        Call min_max search in ai.py to find the best place to set chess
        """
        if self.button_freeze:
            return
        print("Perform AI Evaluate!", end=" ")
        start_time = time.time()
        self.chessBoard.freeze = True
        self.button_freeze = True

        bar = Bar(len(points_gen(self.chessBoard, self.chessBoard.next_turn)))
        position = min_max_search(self.chessBoard,
                                  self.chessBoard.next_turn,
                                  bar,
                                  depth=2)

        print(position)
        position = self.convert_coordinate(position[0], position[1])
        temp_coo = namedtuple("Coordinate", ["x", "y"])
        print("Used time: {}".format(round(time.time() - start_time, 3)))

        self.chessBoard.freeze = False
        self.button_freeze = False
        self.mouse_click(temp_coo(position[0], position[1]))

    def button_evaluate(self):
        """
        Evaluate and score the situation on chessboard for both players
        """
        if self.button_freeze:
            return
        print("Perform evaluate_point!")
        split = list(self.chessBoard.split_board())
        self.score1["text"] = "Black: {}".format(
            self.chessBoard.evaluate(1, split))
        self.score2["text"] = "White: {}".format(
            self.chessBoard.evaluate(2, split))
        self.root.update()

    def mouse_click(self, click):
        x, y = self._nearest_position(click)
        converted_coo = self.convert_coordinate(x, y)

        # Calculate is the place already has a chess
        if self.chessBoard.board[converted_coo[0]][converted_coo[1]] != 0:
            return

        # If the board is frozen...
        if self.chessBoard.freeze:
            return

        # Draw chess
        chess_size = self.gap * 2 // 5
        if self.chessBoard.next_turn == 1:
            color = "Black"
        else:
            color = "White"
        new_position = self.convert_coordinate(x, y)
        print("{} chess at position({}, {})".format(color, new_position[0],
                                                    new_position[1]))
        self.operate.append(
            self.mainBoard.create_oval(
                x - chess_size,
                y - chess_size,
                x + chess_size,
                y + chess_size,
                fill=color,
                tag="{} {}".format(x, y),
            ))
        self.mainBoard.update()

        # Update Chessboard
        result = self.chessBoard.set_chess(converted_coo[0], converted_coo[1])
        # If the game is ended
        if result == TIE:
            print("Tie!")
            self.chessBoard.freeze = True
            ok_window = OkWindow(TIE)
            self.root.wait_window(ok_window.root)
            print("Restart: {}".format(ok_window.final_restart))
            # Restart game
            if ok_window.final_restart:
                self.restart_game()

        elif result != CONTINUE:
            if result == BLACK_WIN:
                winner = "Black"
            else:
                winner = "White"
            print("{} won!".format(winner))
            self.chessBoard.freeze = True
            ok_window = OkWindow(winner)
            self.root.wait_window(ok_window.root)
            print("Restart: {}".format(ok_window.final_restart))
            # Restart game
            if ok_window.final_restart:
                self.restart_game()

        # Update gui
        self.turn["text"] = "Next player: {}".format(
            "black" if self.chessBoard.next_turn == 1 else "white")
        self.button_evaluate()
        # print(self.chessBoard)

    def _nearest_position(self, click) -> Tuple[int, int]:
        x, y = click.x, click.y
        return (
            sorted(
                range(self.gap, self.gap * 16, self.gap),
                key=lambda temp_x: abs(temp_x - x),
            )[0],
            sorted(
                range(self.gap, self.gap * 16, self.gap),
                key=lambda temp_y: abs(temp_y - y),
            )[0],
        )

    @staticmethod
    def convert_coordinate(x: int, y: int) -> Tuple[int, int]:
        if x > 16 or y > 16:
            return x // 25 - 1, y // 25 - 1
        else:
            return (x + 1) * 25, (y + 1) * 25

    def _init_menu(self):
        menu = Menu(self.root, tearoff=0)
        self.root.config(menu=menu)
        game_menu = Menu(menu)
        game_menu.add_command(label="New game", command=self.restart_game)
        # game_menu.add_command(label="Evaluate", command=self.button_evaluate)
        game_menu.add_command(label="Withdraw", command=self.withdraw)
        game_menu.add_command(label="Exit", command=self.root.destroy)
        menu.add_cascade(label="Game", menu=game_menu)

    def _draw_label(self):
        for x in range(15):
            Label(self.horLabel, text=format_number(x)).pack(side=LEFT,
                                                             padx=3,
                                                             pady=0)
        for y in range(15):
            Label(self.verLabel, text=format_number(y)).pack(side=TOP,
                                                             pady=2,
                                                             padx=0)

    def _draw_lines(self):
        # horizontal
        for index in range(1, 16):
            self.mainBoard.create_line(self.gap * index, self.gap,
                                       self.gap * index, 25 * 15)
            self.mainBoard.create_line(self.gap, self.gap * index, 25 * 15,
                                       self.gap * index)

    def restart_game(self):
        global user_info, bd
        del bd
        print("\n----------Restart Game!----------")
        self.root.destroy()
        bd = ChessBoardInterface(pack_label=user_info["pack_label"])
        bd.root.mainloop()

    def withdraw(self):
        # Check if the chessboard is frozen
        if self.chessBoard.freeze or self.button_freeze:
            return

        withdraw_gen = self.chessBoard.withdraw()
        last_chess = next(withdraw_gen)
        player, position = last_chess
        print("Withdraw {} chess at ({}, {})".format(
            "Black" if player == 1 else "White", position[0], position[1]))

        # Change next player
        self.chessBoard.next_turn = 1 if self.chessBoard.next_turn == 2 else 2

        # Delete picture
        self.mainBoard.delete(self.operate.pop())

        self.button_evaluate()
コード例 #24
0
 def __init__(self):
     super().__init__()
     self.board = ChessBoard(self)
     self.init()
コード例 #25
0
    def test_basic_movement(self):
        chess_board = ChessBoard()

        b_R1 = Figure("R1", chess_board.board, 'A', 8, "black")
        b_H1 = Figure("H1", chess_board.board, 'B', 8, "black")
        b_B1 = Figure("B1", chess_board.board, 'C', 8, "black")
        b_Q1 = Figure("Q1", chess_board.board, 'D', 8, "black")
        b_K1 = Figure("K1", chess_board.board, 'E', 8, "black")
        b_B2 = Figure("B2", chess_board.board, 'F', 8, "black")
        b_H2 = Figure("H2", chess_board.board, 'G', 8, "black")
        b_R2 = Figure("R2", chess_board.board, 'H', 8, "black")
        b_P1 = Figure("P1", chess_board.board, 'A', 7, "black")
        b_P2 = Figure("P2", chess_board.board, 'B', 7, "black")
        b_P3 = Figure("P3", chess_board.board, 'C', 7, "black")
        b_P4 = Figure("P4", chess_board.board, 'D', 7, "black")
        b_P5 = Figure("P5", chess_board.board, 'E', 7, "black")
        b_P6 = Figure("P6", chess_board.board, 'F', 7, "black")
        b_P7 = Figure("P7", chess_board.board, 'G', 7, "black")
        b_P8 = Figure("P8", chess_board.board, 'H', 7, "black")

        w_R1 = Figure("R1", chess_board.board, 'A', 1, "white")
        w_H1 = Figure("H1", chess_board.board, 'B', 1, "white")
        w_B1 = Figure("B1", chess_board.board, 'C', 1, "white")
        w_Q1 = Figure("Q1", chess_board.board, 'D', 1, "white")
        w_K1 = Figure("K1", chess_board.board, 'E', 1, "white")
        w_B2 = Figure("B2", chess_board.board, 'F', 1, "white")
        w_H2 = Figure("H2", chess_board.board, 'G', 1, "white")
        w_R2 = Figure("R2", chess_board.board, 'H', 1, "white")
        w_P1 = Figure("P1", chess_board.board, 'A', 2, "white")
        w_P2 = Figure("P2", chess_board.board, 'B', 2, "white")
        w_P3 = Figure("P3", chess_board.board, 'C', 2, "white")
        w_P4 = Figure("P4", chess_board.board, 'D', 2, "white")
        w_P5 = Figure("P5", chess_board.board, 'E', 2, "white")
        w_P6 = Figure("P6", chess_board.board, 'F', 2, "white")
        w_P7 = Figure("P7", chess_board.board, 'G', 2, "white")
        w_P8 = Figure("P8", chess_board.board, 'H', 2, "white")

        w_figs = [
            w_R1, w_H1, w_B1, w_Q1, w_K1, w_B2, w_H2, w_R2, w_P1, w_P2, w_P3,
            w_P4, w_P5, w_P6, w_P7, w_P8
        ]
        b_figs = [
            b_R1, b_H1, b_B1, b_Q1, b_K1, b_B2, b_H2, b_R2, b_P1, b_P2, b_P3,
            b_P4, b_P5, b_P6, b_P7, b_P8
        ]

        moves = [
            "A2-A4",
            "B7-B5",
            "C2-C4",
            "D7-D5",
            "E2-E4",
            "F7-F5",  # moving the pawns 
            "G2-G4",
            "H7-H5",
            "A4-B5",
            "D5-C4",
            "E4-F5",
            "H5-G4",  # out of the way
            "A1-C1",
            "A1-A10",
            "A1-B3",
            "A1-C3",
            "A1-A5",  # rook movement
            "G8-G7",
            "G8-G5",
            "G8-H7",
            "G8-F5",
            "G8-H6",  # horse movement 
            "A5-D5",
            "C1-B2",
            "C1-A3",
            "C1-D2",
            "C1-F4",
            "C1-C3",  # bishop movement
            "D1-D2",
            "D1-D4",
            "D1-H5",
            "D1-B3",  # queen movement 
            "E8-E7",
            "E8-E5",
            "E8-F8",
            "E8-F7",  # king movement
            "F1-D3",
            "exit"  # last bishop move
        ]

        board = [{
            "A": b_R1,
            "B": b_H1,
            "C": b_B1,
            "D": b_Q1,
            "E": None,
            "F": b_B2,
            "G": None,
            "H": b_R2
        }, {
            "A": b_P1,
            "B": None,
            "C": b_P3,
            "D": None,
            "E": b_P5,
            "F": b_K1,
            "G": b_P7,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": None,
            "G": None,
            "H": b_H2
        }, {
            "A": w_R1,
            "B": w_P1,
            "C": None,
            "D": None,
            "E": None,
            "F": w_P5,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": b_P4,
            "D": None,
            "E": None,
            "F": None,
            "G": b_P8,
            "H": None
        }, {
            "A": None,
            "B": w_Q1,
            "C": None,
            "D": w_B2,
            "E": None,
            "F": None,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": w_P2,
            "C": None,
            "D": w_P4,
            "E": None,
            "F": w_P6,
            "G": None,
            "H": w_P8
        }, {
            "A": None,
            "B": w_H1,
            "C": w_B1,
            "D": None,
            "E": w_K1,
            "F": None,
            "G": w_H2,
            "H": w_R2
        }]

        board = reverse_board(board)

        game = Game(w_figs, b_figs, chess_board)
        game.run(moves)

        self.assertEqual(game.chess_board.board, board)
コード例 #26
0
ファイル: ai.py プロジェクト: ykozxy/GoBang
def has_neighbor(board: ChessBoard, point: Tuple[int, int], depth: int) -> bool:
    """
    Determine whether a point has neighbor which is filled
    :param depth: depth of calculation
    :param board: chessboard
    :param point: point wants to calculate
    :return: whether a point has neighbor which is filled
    """
    x, y = point
    all_points = [
        board.board[cx][cy]
        # (cx, cy)
        for cx in range(
            x - depth if x - depth >= 0 else 0, x + depth + 1 if x + depth <= 14 else 15
        )
        for cy in range(
            y - depth if y - depth >= 0 else 0, y + depth + 1 if y + depth <= 14 else 15
        )
    ]
    if any((1 in all_points, 2 in all_points)):
        return True
    return False


if __name__ == "__main__":
    a = ChessBoard("p", "p")
    a.set_chess(4, 6)
    print(has_neighbor(a, (3, 4), depth=2))
    print(points_gen(a, 1))
コード例 #27
0
    def test_end(self):
        chess_board = ChessBoard()

        b_R1 = Figure("R1", chess_board.board, 'A', 8, "black")
        b_H1 = Figure("H1", chess_board.board, 'B', 8, "black")
        b_B1 = Figure("B1", chess_board.board, 'C', 8, "black")
        b_Q1 = Figure("Q1", chess_board.board, 'D', 8, "black")
        b_K1 = Figure("K1", chess_board.board, 'E', 8, "black")
        b_B2 = Figure("B2", chess_board.board, 'F', 8, "black")
        b_H2 = Figure("H2", chess_board.board, 'G', 8, "black")
        b_R2 = Figure("R2", chess_board.board, 'H', 8, "black")
        b_P1 = Figure("P1", chess_board.board, 'A', 7, "black")
        b_P2 = Figure("P2", chess_board.board, 'B', 7, "black")
        b_P3 = Figure("P3", chess_board.board, 'C', 7, "black")
        b_P4 = Figure("P4", chess_board.board, 'D', 7, "black")
        b_P5 = Figure("P5", chess_board.board, 'E', 7, "black")
        b_P6 = Figure("P6", chess_board.board, 'F', 7, "black")
        b_P7 = Figure("P7", chess_board.board, 'G', 7, "black")
        b_P8 = Figure("P8", chess_board.board, 'H', 7, "black")

        w_R1 = Figure("R1", chess_board.board, 'A', 1, "white")
        w_H1 = Figure("H1", chess_board.board, 'B', 1, "white")
        w_B1 = Figure("B1", chess_board.board, 'C', 1, "white")
        w_Q1 = Figure("Q1", chess_board.board, 'D', 1, "white")
        w_K1 = Figure("K1", chess_board.board, 'E', 1, "white")
        w_B2 = Figure("B2", chess_board.board, 'F', 1, "white")
        w_H2 = Figure("H2", chess_board.board, 'G', 1, "white")
        w_R2 = Figure("R2", chess_board.board, 'H', 1, "white")
        w_P1 = Figure("P1", chess_board.board, 'A', 2, "white")
        w_P2 = Figure("P2", chess_board.board, 'B', 2, "white")
        w_P3 = Figure("P3", chess_board.board, 'C', 2, "white")
        w_P4 = Figure("P4", chess_board.board, 'D', 2, "white")
        w_P5 = Figure("P5", chess_board.board, 'E', 2, "white")
        w_P6 = Figure("P6", chess_board.board, 'F', 2, "white")
        w_P7 = Figure("P7", chess_board.board, 'G', 2, "white")
        w_P8 = Figure("P8", chess_board.board, 'H', 2, "white")

        w_figs = [
            w_R1, w_H1, w_B1, w_Q1, w_K1, w_B2, w_H2, w_R2, w_P1, w_P2, w_P3,
            w_P4, w_P5, w_P6, w_P7, w_P8
        ]
        b_figs = [
            b_R1, b_H1, b_B1, b_Q1, b_K1, b_B2, b_H2, b_R2, b_P1, b_P2, b_P3,
            b_P4, b_P5, b_P6, b_P7, b_P8
        ]

        moves = ["E2-E4", "F7-F6", "D2-D4", "G7-G5", "D1-H5", "exit"]

        board = [{
            "A": b_R1,
            "B": b_H1,
            "C": b_B1,
            "D": b_Q1,
            "E": b_K1,
            "F": b_B2,
            "G": b_H2,
            "H": b_R2
        }, {
            "A": b_P1,
            "B": b_P2,
            "C": b_P3,
            "D": b_P4,
            "E": b_P5,
            "F": None,
            "G": None,
            "H": b_P8
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": b_P6,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": None,
            "G": b_P7,
            "H": w_Q1
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": w_P4,
            "E": w_P5,
            "F": None,
            "G": None,
            "H": None
        }, {
            "A": None,
            "B": None,
            "C": None,
            "D": None,
            "E": None,
            "F": None,
            "G": None,
            "H": None
        }, {
            "A": w_P1,
            "B": w_P2,
            "C": w_P3,
            "D": None,
            "E": None,
            "F": w_P6,
            "G": w_P7,
            "H": w_P8
        }, {
            "A": w_R1,
            "B": w_H1,
            "C": w_B1,
            "D": None,
            "E": w_K1,
            "F": w_B2,
            "G": w_H2,
            "H": w_R2
        }]

        board = reverse_board(board)

        game = Game(w_figs, b_figs, chess_board)
        game.run(moves)

        self.assertEqual(game.b_checkmate, 1)
コード例 #28
0
ファイル: main.py プロジェクト: arBalasquide/terminal_chess
def show_board():
    game = ChessBoard()
    game.show()
コード例 #29
0
# image = pygame.image.load(r'C:\Users\user\Pictures\geek.jpg') 
# screen.blit(image, (x,y))   
# pygame.transform.scale(img, (1280, 720))
# rect = picture.get_rect()


SCREEN_WIDTH = 680
SCREEN_HEIGHT = 680
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))

COLORS = {"green":(0,255,0),"blue":(0,0,255),"red":(255,0,0),"black":(0,0,0),"white":(255,255,255),
          "golden":(255,215,0)}

KEYS = {"UP":pygame.K_UP,"DOWN":pygame.K_DOWN,"LEFT":pygame.K_LEFT,"RIGHT":pygame.K_RIGHT}

my_chess_board = ChessBoard(screen,SCREEN_WIDTH)

blacks_team = blacks.BlackTeam(surface=screen,board=my_chess_board)
blacks_team.DrawAllPlayers()
whites_team = whites.WhiteTeam(surface=screen,board=my_chess_board)
whites_team.DrawAllPlayers()

blacks_team.opponent = whites_team
whites_team.opponent = blacks_team

def GamePlay():
    running = True    
    while running:

        for event in pygame.event.get():
            if event.type==QUIT:
コード例 #30
0
ファイル: test.py プロジェクト: we3x/chess-rec
          [-6, 0, 0, -6, 0, -2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 2, 6, 0, 0, 0], [0, 0, 2, 0, 0, 0, 0, 0],
          [6, 6, 6, 0, 3, 6, 6, 6], [1, 0, 3, 5, 4, 0, 0, 1]]

board4 = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1],
          [0, 0, 0, 0, 0, -5, 0, -4], [0, 0, 0, 5, 0, 0, 2, 0],
          [0, 0, 0, -6, 0, 0, 0, 0], [6, 6, 0, 0, 0, -6, 6, 6],
          [0, 0, 0, 0, 0, -2, 0, 4], [0, 0, 0, 0, -1, 0, 0, 0]]

board5 = [[0, 0, 0, -5, -2, -1, -4, 0], [0, 0, 0, -1, -3, -6, -6, -6],
          [-6, -6, -2, -6, -6, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 0],
          [0, 0, 6, 0, 2, 5, 0, 0], [0, 6, 0, 0, 0, 0, 6, 0],
          [6, 3, 0, 0, 6, 6, 4, 6], [0, 0, 1, 1, 0, 0, 0, 0]]

print('test1')
board = ChessBoard('./images/tests/1.png')
npt.assert_equal(board1, board.get_board())

print('test2')
board = ChessBoard('./images/tests/2.png')
npt.assert_equal(board2, board.get_board())

print('test3')
board = ChessBoard('./images/tests/3.png')
npt.assert_equal(board3, board.get_board())

print('test4')
board = ChessBoard('./images/tests/4.png')
npt.assert_equal(board4, board.get_board())

print('test5')