Exemplo n.º 1
0
def main():
    string = ""
    for _ in range(8):
        string += input() + '\n'
    matrix = parse_input(string)
    chessboard = Chessboard(matrix)
    chessboard.find_mate()
Exemplo n.º 2
0
    def parse(data):
        def _url_to_piece(url: str):
            line = url.split('/')[-1]
            line = re.sub(r'\.\S+', '', line)
            return Pieces.get(line[1], True if line[0] == 'w' else False)

        chessboard = Chessboard()
        pattern_url = re.compile(r'url\("([^)]+)"\)')
        pattern_square = re.compile("square-(\d+)")
        root = html.fromstring(data)
        element = root.get_element_by_id("game-board")
        pieces_element = element.find_class('pieces')[0]

        squares, pieces = list(), list()

        for p in pieces_element:
            coords = pattern_square.search(p.get('class')).group(1)
            style = p.get('style')
            url = pattern_url.search(style).group(1)
            square = Square.index_to_square(
                int(coords[-2:]) - 1,
                int(coords[:2]) - 1)
            piece = _url_to_piece(url)
            squares.append(square)
            pieces.append(piece)

        chessboard.update_squares(squares, pieces)

        return chessboard
Exemplo n.º 3
0
 def __init__(self):
     """Inicjalizacja gry"""
     self._current_player = Player("Adam", Color.White)
     self._next_player = Player("Eve", Color.Black)
     self._console = Console()
     self._board = Chessboard()
     self._board.init()
Exemplo n.º 4
0
 def __init__(self, console=Console()):
     """Inicjalizacja gry"""
     self._move_count = 0
     self._console = console
     self._board = Chessboard(self._console, self._console.draw)
     self._current_player, self._next_player = PlayerMaker(
         self._console).make()
     self._shelve = shelve.open("chessboard_move_storage", flag='n')
Exemplo n.º 5
0
    def test_new_board_has_ranks_and_files(self):
        board = Chessboard()
        bottom_left_square = board.square('a', 1)
        self.assertTrue(not bottom_left_square.is_white())
        self.assertIsNone(bottom_left_square.piece)

        bottom_right_square = board.square('h', 1)
        self.assertTrue(bottom_right_square.is_white())
Exemplo n.º 6
0
class Game:
    def __init__(self):
        """Inicjalizacja gry"""
        self._current_player = Player("Adam", Color.White)
        self._next_player = Player("Eve", Color.Black)
        self._console = Console()
        self._board = Chessboard()
        self._board.init()

    def run(self):
        """Pętla główna gry"""
        self._board.accept(self._console)
        self._console.draw()
        while True:
            try:
                position_from, position_to = self._current_player.get_move()
                piece = self._board.get_piece(position_from)
                if (piece.is_move_possible(position_from, position_to)
                        and piece.get_color() == self._current_player.get_color()):
                    self._board.move(position_from, position_to)
                else:
                    self._console.illegal_move_error()
                    #print("Move not possible! Try again")
                    continue
            except ValueError as e:
                print(e)
            else:
                self._current_player, self._next_player = self._next_player, self._current_player
                self._board.accept(self._console)
                self._console.draw()
Exemplo n.º 7
0
def init_game():
    global chessboard
    global screen
    global queue
    global ai_proc

    pygame.init()
    screen = pygame.display.set_mode(size, 0, 32)
    chessboard = Chessboard()

    if len(sys.argv) == 2 and sys.argv[1][:2] == '-n':
        chessboard.net = Chessnet()

        if sys.argv[1][2:] == 'r':
            pygame.display.set_caption("red")
            chessboard.side = RED
        elif sys.argv[1][2:] == 'b':
            pygame.display.set_caption("black")
            chessboard.side = BLACK
        else:
            print('>> quit game')
            sys.exit()

        chessboard.net.NET_HOST = sys.argv[2]

    elif len(sys.argv) == 1:
        # text = True: set text mode
        # bufsize = 1: set line buffer mode
        ai_proc = Popen("./harmless", stdin=PIPE, stdout=PIPE, close_fds=ON_POSIX, text=True, bufsize=1)
        chessboard.fin, chessboard.fout = ai_proc.stdin, ai_proc.stdout
        response = Thread(target=enqueue_output, args=(chessboard.fout, queue))
        response.daemon = True
        response.start()

        chessboard.fin.write("ucci\n")

        while True:
            try:
                output = queue.get_nowait()
            except Empty:
                continue
            else:
                print(output)
                if 'ucciok' in output:
                    break

        chessboard.mode = AI
        pygame.display.set_caption("harmless")
        chessboard.side = RED
    else:
        print('>> quit game')
        sys.exit()

    chessboard.fen_parse(fen_str)
Exemplo n.º 8
0
 def test_all_pieces__returns_all_pieces(self):
     board = Chessboard()
     board.set_board()
     all_pieces = board.all_pieces(Piece.ROOK, Piece.BLACK)
     self.assertEqual(len(all_pieces), 2)
     for val in all_pieces:
         position, piece = val
         self.assertEqual(piece.name, piece.ROOK)
         self.assertEqual(piece.color, piece.BLACK)
         file_, rank = position
         self.assertTrue(file_ == 'a' or file_ == 'h')
         self.assertEqual(rank, 8)
Exemplo n.º 9
0
 def __init__(self, black_stone_img, white_stone_img):
     #初始化棋盘
     self.chessboard = Chessboard()
     #初始化神经网络
     #TODO:神经网络还要改
     self.neural = Neural(19, 19)
     #初始化先手棋子
     self.player = BLACK_PLAYER
     #黑白棋棋子图片
     self.black_stone_img = black_stone_img
     self.white_stone_img = white_stone_img
     #初始化赢家
     self.winner = None
     #初始化胜利后的标题
     self.win_text_surface = None
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        x_index: int = chessboard.x_size.index(self.field[0])
        y_index: int = chessboard.y_size.index(self.field[1])

        move: str

        """ Direction right-up """
        for i in range(1, 8 - max(x_index, y_index)):
            move = chessboard.x_size[x_index + i] + chessboard.y_size[y_index + i]
            self.available_moves.append(move)

        """ Direction left-bottom """
        for i in range(1, min(x_index, y_index) + 1):
            move = chessboard.x_size[x_index - i] + chessboard.y_size[y_index - i]
            self.available_moves.append(move)

        """ Direction right-bottom """
        for i in range(1, min(7 - x_index, y_index) + 1):
            move = chessboard.x_size[x_index + i] + chessboard.y_size[y_index - i]
            self.available_moves.append(move)

        """ Direction left-up """
        for i in range(1, min(x_index, 7 - y_index) + 1):
            move = chessboard.x_size[x_index - i] + chessboard.y_size[y_index + i]
            self.available_moves.append(move)

        return self.available_moves
Exemplo n.º 11
0
def main():
    startX, startY = eval(input("Enter a starting point: "))
    width = input("Input a width: ")
    height = input("Input a height: ")
    tr = turtle.Turtle()
    if width == "" and height == "":
        chessboard = Chessboard(tr, startX, startY)
    elif height == "":
        chessboard = Chessboard(tr, startX, startY, width=eval(width))
    elif width == "":
        chessboard = Chessboard(tr, startX, startY, height=eval(height))
    else:
        chessboard = Chessboard(tr, startX, startY, eval(width), eval(height))
    chessboard.draw()
    tr.hideturtle()
    turtle.done()
Exemplo n.º 12
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    play_button = Button(ai_settings, screen, (900, 80), "Play")
    chessbook_button = Button(ai_settings, screen, (900, 200), "Import")
    retract_button = Button(ai_settings, screen, (900, 440), "Retract")
    image_button = Button(ai_settings, screen, (900, 320), "Images")
    pygame.display.set_caption("Tic-Tac-Toe")

    chessboard = Chessboard(screen)
    stats = GameStats(ai_settings)
    pieces = Group()

    # event loop
    while True:
        # listening events from mouse and keyboard
        gf.check_events(chessboard.screen, chessboard, pieces, ai_settings,
                        stats, play_button, chessbook_button, retract_button,
                        image_button)
        # visualize
        if stats.game_active:
            gf.update_pieces(pieces, screen, chessboard, stats, ai_settings)

        gf.update_screen(ai_settings, screen, chessboard, pieces, play_button,
                         stats, chessbook_button, retract_button, image_button)
Exemplo n.º 13
0
def start_new():
    global chessboard
    chessboard.__del__()
    chessboard = Chessboard()
    return statement(
        "Ok, let's start a new game. Please put all pieces in their starting position."
    )
Exemplo n.º 14
0
def one_step():
    data = {}
    x = int(request.form.get('x', 0))
    y = int(request.form.get('y', 0))
    action = Action(x, y, True)
    cur = _usr_action(action)
    if cur.checkWin(action) is True:
        data['win'] = False
        return jsonify(data)
    # calculate elapsed time
    start = time.clock()
    bestmove, bestscore = cur.alpha_beta(1)
    elapsed = time.clock() - start
    data['elapsed-time'] = math.ceil(elapsed)
    if bestmove is None:
        data['win'] = False
        return jsonify(data)
    data['best'] = str((bestmove.x, bestmove.y))
    bd = cur.board
    x = bestmove.x
    y = bestmove.y
    data.update({'x': x, 'y': y})
    bd[x][y] = _WHITE
    cb = Chessboard(None, bd, bestscore)
    Chessboard.curB = bd
    Chessboard.curV = bestscore
    if abs(bestscore) > 40000:
        if cur.checkWin(bestmove) is True:
            data['win'] = True
    _print_chessboard(bd)
    return jsonify(data)
Exemplo n.º 15
0
 def __init__(self, black_stone_img, white_stone_img):
     self.chessboard = Chessboard()
     self.neural = Neural(19, 19)
     self.player = BLACK_PLAYER
     self.black_stone_img = black_stone_img
     self.white_stone_img = white_stone_img
     self.winner = None
     self.win_text_surface = None
Exemplo n.º 16
0
    def parse(data):
        def _url_to_piece(url: str):
            line = url.split('/')[-1]
            line = re.sub(r'\.\S+', '', line)
            return Pieces.get(line[1], True if line[0] == 'w' else False)

        def _get_translation(line):
            translate_match = pattern.search(line)
            if translate_match is not None:
                x = int(translate_match.group(1))
                y = int(translate_match.group(2))
                return x, y

            else:
                return -1, -1

        chessboard = Chessboard()
        pattern = re.compile(r'translate\((\d+)px,\s*(\d+)px\)')

        root = html.fromstring(data)
        element = root.get_element_by_id("chessboard_boardarea")
        classes = element.find_class('chess_com_piece')

        squares, pieces = list(), list()

        for cls in classes:
            w = int(cls.get('width'))
            h = int(cls.get('height'))
            style = cls.get('style')
            src = cls.get('src')
            x, y = _get_translation(style)
            if x == -1 or y == -1:
                return None
            row, col = 7 - y / h, x / w
            if not row.is_integer() or not col.is_integer():
                return None
            square = Square.index_to_square(int(row), int(col))
            piece = _url_to_piece(src)

            squares.append(square)
            pieces.append(piece)

        chessboard.update_squares(squares, pieces)

        return chessboard
Exemplo n.º 17
0
def test_same_team():
    c = Chessboard()
    lower_case = True
    try:
        assert c.same_team(lower_case, 56) == True
        assert c.same_team(lower_case, 4) == False
        assert c.same_team(not lower_case, 48) == False
        assert c.same_team(lower_case, 1) == False
        assert c.same_team(not lower_case, 60) == False
        assert c.same_team(lower_case, 58) == True
        return True
    except:
        return False
Exemplo n.º 18
0
    def __init__(self,
                 dimension=(5, 5),
                 square_size=(80, 80),
                 default_rewards=0,
                 agent_born_at=(0, 0),
                 agent_born_facing='E'):
        # create a chessboard-style map for the environment
        self.map = Chessboard(dimension)
        self.default_rewards = default_rewards

        # set walls, user can still call .set_walls() to add new walls
        self.walls = []
        rows, columns = dimension
        for row in range(rows):
            self.walls.append((row, -1))
            self.walls.append((row, columns))
        for column in range(columns):
            self.walls.append((-1, column))
            self.walls.append((rows, column))

        # create a drawing manager, which creates a tkinter window in a new thread
        self.drawing_manager = DrawingManager(dimension, square_size).wait()

        # draw chessboard
        self.drawing_manager.draw_chessboard()

        # create an action space
        self.action_space = ActionSpace(('N', 'S', 'W', 'E'))

        # create agent and set its born location and facing direction
        self.agent = Agent(agent_born_at, agent_born_facing)

        # whether environment changes should be displayed on screen
        self._show = True

        # track total steps agent has walked
        self._steps = 0

        # reset environment
        self.reset()
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        """ Movement horizontally """
        for x_field in chessboard.x_size:
            if x_field != self.field[0]:
                self.available_moves.append(x_field + self.field[1])

        """ Movement vertically """
        for y_field in chessboard.y_size:
            if y_field != self.field[1]:
                self.available_moves.append(self.field[0] + y_field)

        return self.available_moves
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        """ Can move forward one square """
        short_move: str = self.field[0] + str(int(self.field[1]) + 1)
        if chessboard.validate_field(short_move):
            self.available_moves.append(short_move)

        """ Pawn can move forward two squares at the beginning """
        if int(self.field[1]) == 2:
            long_move: str = self.field[0] + str(int(self.field[1]) + 2)
            if chessboard.validate_field(long_move):
                self.available_moves.append(long_move)

        return self.available_moves
Exemplo n.º 21
0
def test_valid_input():
    c = Chessboard()
    try:
        assert c.valid_input('D2') == True
        assert c.valid_input('e5') == True
        assert c.valid_input('Zs') == False
        assert c.valid_input('1D') == False
        assert c.valid_input('231') == False
        assert c.valid_input('Þ34') == False
        assert c.valid_input('3e') == False
        assert c.valid_input('-3') == False
        assert c.valid_input(' d2') == False
        assert c.valid_input('d2 ') == False
        assert c.valid_input('') == False
        return True
    except:
        return False
Exemplo n.º 22
0
    def test_set_board_places_pieces(self):
        board = Chessboard()
        board.set_board()
        white_rook = board.square('a', 1).piece
        self.assertEqual(white_rook.name, Piece.ROOK)
        self.assertTrue(white_rook.is_white())

        black_queen = board.square('d', 8).piece
        self.assertEqual(black_queen.name, Piece.QUEEN)
        self.assertTrue(not black_queen.is_white())

        white_pawn = board.square('f', 2).piece
        self.assertEqual(white_pawn.name, Piece.PAWN)
        self.assertTrue(white_pawn.is_white())
Exemplo n.º 23
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Chess made by xujing")
    #对象
    chessboard = Chessboard(ai_settings, screen)
    chesspoints = []
    occupied = [[0] * ai_settings.num for i in range(ai_settings.num)]

    while True:
        screen.fill(ai_settings.bk_color)
        gf.check_events(ai_settings, screen, chesspoints, occupied)
        gf.update_screen(ai_settings, screen, chessboard, chesspoints)
        pygame.display.flip()
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        x_index: int = chessboard.x_size.index(self.field[0])
        y_index: int = chessboard.y_size.index(self.field[1])

        move: str

        """ Direction up """
        if y_index < 6:
            if x_index != 0:
                move = chessboard.x_size[x_index - 1] + chessboard.y_size[y_index + 2]
                self.available_moves.append(move)
            if x_index != 7:
                move = chessboard.x_size[x_index + 1] + chessboard.y_size[y_index + 2]
                self.available_moves.append(move)

        """ Direction bottom """
        if y_index > 1:
            if x_index != 0:
                move = chessboard.x_size[x_index - 1] + chessboard.y_size[y_index - 2]
                self.available_moves.append(move)
            if x_index != 7:
                move = chessboard.x_size[x_index + 1] + chessboard.y_size[y_index - 2]
                self.available_moves.append(move)

        """ Direction right """
        if x_index < 6:
            if y_index != 0:
                move = chessboard.x_size[x_index + 2] + chessboard.y_size[y_index - 1]
                self.available_moves.append(move)
            if y_index != 7:
                move = chessboard.x_size[x_index + 2] + chessboard.y_size[y_index + 1]
                self.available_moves.append(move)

        """ Direction left """
        if x_index > 1:
            if y_index != 0:
                move = chessboard.x_size[x_index - 2] + chessboard.y_size[y_index - 1]
                self.available_moves.append(move)
            if y_index != 7:
                move = chessboard.x_size[x_index - 2] + chessboard.y_size[y_index + 1]
                self.available_moves.append(move)

        return self.available_moves
Exemplo n.º 25
0
def run_game():

    pygame.init()
    settings = Settings()
    settings.player_color = "white"
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_heigh))
    chessboard = Chessboard(screen, settings)
    chessmans = Group()
    cue_stats = 'player'
    while 1:
        stats = gf.check_events(screen, settings, chessmans, chessboard)
        if 'win' not in cue_stats:
            if stats:
                cue_stats = stats
            cue_board = Cueboard(settings, screen, cue_stats)
            gf.update_screen(screen, settings, chessmans, chessboard,
                             cue_board)
Exemplo n.º 26
0
class GameManager:
    def __init__(self):
        self.count = 1
        self.disks = []
        self.my_disk = None
        self.chessboard = Chessboard(6, 7)

    def prepare_to_drop(self):
        # called when mousePressed
        row, column = self.chessboard.get_row_column(mouseX)
        if row:
            x, y = self.chessboard.row_column_to_xy(row, column)
            self.my_disk = Disk(x, 0, x, y, row, column, self.count)
        else:
            self.my_disk = None

    def start_drop(self):
        # called when mouseReleased
        if self.my_disk:
            self.my_disk.intact = False
            self.count += 1
            self.disks.append(self.my_disk)
            self.chessboard.occupy(self.my_disk.row, self.my_disk.column, 1)
            self.my_disk = None
            return True
        return False

    def computer_to_drop(self):
        aiX = score.ai_play(self.chessboard)
        row, column = self.chessboard.get_row_column(aiX)
        x, y = self.chessboard.row_column_to_xy(row, column)
        ai_disk = Disk(x, 0, x, y, row, column, self.count)
        ai_disk.intact = False
        self.count += 1
        self.disks.append(ai_disk)
        self.chessboard.occupy(row, column, 2)

    def all_disk_arrived(self):
        for self.disk in self.disks:
            if not self.disk.arrived():
                return False
        return True
Exemplo n.º 27
0
def test_bishopValidity():
    c = Chessboard()
    c.move_piece(51, 35)  # p to D4
    c.move_piece(58, 37)  # b to F4
    '''{ 0:'R',  1:'N',  2:'B',  3:'Q',  4:'K',  5:'B',  6:'N',  7:'R', 
         8:'P',  9:'P', 10:'P', 11:'P', 12:'P', 13:'P', 14:'P', 15:'P',
        16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
        24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:' ',
        32:' ', 33:' ', 34:' ', 35:'p', 36:' ', 37:'b', 38:' ', 39:' ',
        40:' ', 41:' ', 42:' ', 43:' ', 44:' ', 45:' ', 46:' ', 47:' ',
        48:'p', 49:'p', 50:'p', 51:' ', 52:'p', 53:'p', 54:'p', 55:'p',
        56:'r', 57:'n', 58:' ', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}'''
    try:
        assert c.bishopValidity(37, 45) == False  # move vertically
        assert c.bishopValidity(37, 36) == False  # move horizontally
        assert c.bishopValidity(37, 23) == True  # move diagonally
        assert c.bishopValidity(37, 1) == False  # jump over piece
        assert c.bishopValidity(37, 10) == True  # kill P
        return True
    except:
        return False
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        x_index: int = chessboard.x_size.index(self.field[0])
        y_index: int = chessboard.y_size.index(self.field[1])

        """ Can move one square in every direction """
        for x_field in range(x_index - 1, x_index + 2):

            for y_field in range(y_index - 1, y_index + 2):

                if (
                    (x_index != x_field or y_index != y_field)
                    and (x_field != -1 and y_field != -1)
                    and (x_field != 8 and y_field != 8)
                ):

                    move: str = chessboard.x_size[x_field] + chessboard.y_size[y_field]
                    self.available_moves.append(move)

        return self.available_moves
    def list_available_moves(self) -> List[str]:
        chessboard: Chessboard = Chessboard()

        x_index: int = chessboard.x_size.index(self.field[0])
        y_index: int = chessboard.y_size.index(self.field[1])

        """ Movement horizontally """
        for x_field in chessboard.x_size:
            if x_field != self.field[0]:
                self.available_moves.append(x_field + self.field[1])

        """ Movement vertically """
        for y_field in chessboard.y_size:
            if y_field != self.field[1]:
                self.available_moves.append(self.field[0] + y_field)

        move: str

        """ Direction right-up """
        for i in range(1, 8 - max(x_index, y_index)):
            move = chessboard.x_size[x_index + i] + chessboard.y_size[y_index + i]
            self.available_moves.append(move)

        """ Direction left-bottom """
        for i in range(1, min(x_index, y_index) + 1):
            move = chessboard.x_size[x_index - i] + chessboard.y_size[y_index - i]
            self.available_moves.append(move)

        """ Direction right-bottom """
        for i in range(1, min(7 - x_index, y_index) + 1):
            move = chessboard.x_size[x_index + i] + chessboard.y_size[y_index - i]
            self.available_moves.append(move)

        """ Direction left-up """
        for i in range(1, min(x_index, 7 - y_index) + 1):
            move = chessboard.x_size[x_index - i] + chessboard.y_size[y_index + i]
            self.available_moves.append(move)

        return self.available_moves
Exemplo n.º 30
0
class GameFlow(object):
    """description of class"""
    def __init__(self, black_stone_img, white_stone_img):
        self.chessboard = Chessboard()
        self.neural = Neural(19, 19)
        self.player = BLACK_PLAYER
        self.black_stone_img = black_stone_img
        self.white_stone_img = white_stone_img
        self.winner = None
        self.win_text_surface = None

    def reset(self):
        self.chessboard.reset()
        self.neural.reset()
        self.player = BLACK_PLAYER
        self.winner = None
        self.win_text_surface = None

    def _change_player(self):
        if self.player == BLACK_PLAYER:
            self.player = WHITE_PLAYER
        elif self.player == WHITE_PLAYER:
            self.player = BLACK_PLAYER
        else:
            assert(false)
            self.player = BLACK_PLAYER
            
    def get_player_name(self):
        if self.player == BLACK_PLAYER:
            return 'Black'
        elif self.player == WHITE_PLAYER:
            return 'White'
        else:
            return 'Unknown'

    def _is_win(self, x, y):
        for dir in range(1,5):
            if self.neural.get_connected_count(x,y,dir) >= 5:
                return True
        return False
        
    def update(self, pos):
        px, py = pos
        # update button
        if self.chessboard.in_range_reset_btn(px, py):
            # reset
            self.reset()
            return

        # update go
        if self.winner:
            return
        ix, iy = self.chessboard.get_stone_index(px, py)
        if ix is None or iy is None:
            return
        if self.neural.set_value(ix, iy, self.player):
            if self._is_win(ix, iy):
                self.winner = self.player
                msg = u'%s is winner!' % self.get_player_name()
                self.win_text_surface = self.chessboard.font.render(msg, True, (0,0,0), (255, 255, 255))
            self._change_player()
        

    def _get_img(self, player):
        if player == BLACK_PLAYER:
            return self.black_stone_img
        elif player == WHITE_PLAYER:
            return self.white_stone_img
        else:
            assert(False)
            return None
        
    def get_mouse_cursor(self):
        return self._get_img(self.player)

    def draw(self, screen):
        for w in range(self.neural.width):
            for h in range(self.neural.height):
                value = self.neural.get_value(w,h)
                if not value:
                    continue
                play_img = self._get_img(value)
                x, y = self.chessboard.get_pos(w,h)
                if x is None or y is None:
                    continue

                x-= play_img.get_width() / 2
                y-= play_img.get_height() / 2
                #计算光标的左上角位置
                screen.blit(play_img, (x, y))

        self.chessboard.draw(screen)
Exemplo n.º 31
0
#!/usr/bin/python

import socket
import sys
from chessboard import Chessboard
from cui import CUI

chessboard = Chessboard('xinuc.org', 7387)
cui = CUI()
while 1:
	coord = chessboard.getRaw()
	if (len(coord)==10):
		print chessboard.rawBoard
		chessboard.parseCoord(coord)
		cui.printBoard(chessboard.board)
Exemplo n.º 32
0
rl = Role()		# init the computer role
while True:
	# receive command from judge program
	command = receiveMessage()
	command = command.split()
	
	if command[0].upper() == "QUIT" or command[0].upper() == "Q":	# quit the game
		sendMessage("bye")
		exit()

	elif command[0].upper() == "START":	# play a new game
		if command[1].upper() == "BLACK":
			# wait the opponent player to make a move
			sendMessage("ok")
			cb = Chessboard(-1)	# black first always
			continue
		else:
			# computer make a movement at the begin
			cb = Chessboard(0)	# black first always
			movePosition = rl.search(cb.board, cb.currentRole)
			moveResult = cb.move(movePosition[0], movePosition[1])
			sendMessage("%d %d"%(movePosition[0], movePosition[1]))
		continue
	
	if command[0].upper() == "MOVE":	# make a move
		# opponent player's turn
		cb.changePlayRole()
		moveResult = cb.move(int(command[1]), int(command[2]))

		# computer's turn
Exemplo n.º 33
0
 def test_board_sets_piece_color(self):
     board = Chessboard()
     board.set_board()
     black_queen = board.square('d', 8).piece
     self.assertEqual(black_queen.color, Piece.BLACK)
Exemplo n.º 34
0
import sys
import json
from chessboard import Chessboard

# Read config file
with open('config.json') as data_file:
    data_file = data_file.read()
    data = json.loads(data_file)

# Setup chessboard
try:
    board = Chessboard()
    board.set_current_player(data['state']['player_turn'])
    board.import_board(data['state']['board'])
except Exception as e:
    sys.exit(e)

# Print out board state (for debugging)
# board.debug()

# Output all valid moves
moves = board.get_valid_moves()
print("Legal moves available:")
for move in moves:
    print(move)
Exemplo n.º 35
0
import sys
from subprocess import *
from chessboard import Chessboard

def sendMessage(proc, message):
	proc.stdin.write(message + "\n")
	proc.stdin.flush()

def receiveMessage(proc):
	message = proc.stdout.readline()
	proc.stdout.flush()
	return message[:len(message) - 1]


if __name__ == '__main__':
	cb = Chessboard(0)	# init a chessboard

	# commuate computer engine wite pipe
	procBlack = Popen('python ./game.py', stdin=PIPE, stdout=PIPE, shell=True)
	procWhite = Popen('python ./game.py', stdin=PIPE, stdout=PIPE, shell=True)

	# send start command to 2 engines
	command = "start black"
	sendMessage(procWhite, command)
	print "send to white : " + command
	result = receiveMessage(procWhite)
	print "receive from white : " + result
	command = "start white"
	sendMessage(procBlack, command)
	print "send to black : " + command
	result = receiveMessage(procBlack)