国际象棋AI收藏

Online Chess Next Step

Next Chess Move

AI repo on Github

Sunfish
Sunfish is a simple, but strong chess engine, written in Python

因为 thuctf 结束后可以放出 writeup 了,清理机器就顺便把当时用的函数放过来,只是基于 sunfish 的简单调用。

def play_against_redbud_ai(s):
    searcher = Searcher()
    pos = Position(initial, 0, (True,True), (True,True), 0, 0)
    is_init = True
    checkmate = False
    while True:
        if checkmate:
            msg = s.recvline()
            if msg.startswith('you win'):
                print(msg)
                return True
        else:
            msg = ''
        msg = msg + s.recvuntil('input your move(like e2e4):\n')
        chess = msg[0:16*8].split('\n')[0:8]
        blank_line = (' '*9 + '\n') * 2
        pos_str = blank_line + ''.join([(' ' + line.replace(' ', '') + '\n') for line in chess]) + blank_line
        # assert(len(pos_str) == 120)
        print(pos_str)
        found_move = False
        if is_init:
            is_init = False
            found_move = True            
        else:
            for move in pos.gen_moves():
                tmpp = pos.move(move)
                if tmpp.board == pos_str:
                    print('AI move: %s' % render(119-move[0])+render(119-move[1]))
                    pos = pos.move(move)
                    found_move = True
                    break
            
        if not found_move:
            print('cannot find ai"s move return false')

        # We query the user until she enters a (pseudo) legal move.
        move = None

        # Fire up the engine to look for a move.
        move, score = searcher.search(pos, secs=1.5)

        if score == MATE_UPPER:
            checkmate = True
            print("Checkmate!")

        # The black player moves from a rotated position, so we have to
        # 'back rotate' the move before printing it.

        line = render(move[0]) + render(move[1])
        print(line)
        s.send(line+chr(0x0a))
        pos = pos.move(move)
    return True


def main():
    win_cnt = 0
    s = remote("misc.thuctf2018.game.redbud.info", 4004)
    data = s.recvuntil('Give me xxxx:')
    inputs = re.findall("sha256\(xxxx\+(.*)\) ==(.*)", data)[0]
    suffix = inputs[0]
    digest = inputs[1]
    result = PoW(suffix, digest)
    print("PoW done")
    s.sendline(result)
    s.recvuntil('Press enter key to continue:\n')
    while win_cnt < 20:
        s.recvuntil('game starts\n')
        if play_against_redbud_ai(s):
            print(win_cnt+1, "  I Win!")
            win_cnt += 1
    s.interactive()

猜你喜欢

转载自blog.csdn.net/cyz14/article/details/82824280