This repository has been archived on 2022-12-29. You can view files and clone it, but cannot push or open issues or pull requests.
zeropod/plugin/chess/util.py

42 lines
1.6 KiB
Python

import re
import itertools
from . import sunfish
def get_all_moves(pos: sunfish.Position):
all_moves = dict()
for src, dst in pos.gen_moves():
all_moves.setdefault(sunfish.render(src), []).append(sunfish.render(dst))
return all_moves
def move_str(move, shift = False):
s = -119 if shift else 0
return sunfish.render(s + move[0]) + " - " + sunfish.render(s + move[1])
def get_color(pos):
return "wb"[1 if pos.board.startswith("\n") else 0]
def parseFEN(fen):
board, color, castling, enpas, _, _ = fen.split()
board = re.sub(r"\d", (lambda m: "."*int(m.group(0))), board)
board = list(21*" " + " ".join(board.split("/")) + 21*" ")
board[9::10] = ["\n"]*12
board = "".join(board)
wc = ("Q" in castling, "K" in castling)
bc = ("k" in castling, "q" in castling)
ep = sunfish.parse(enpas) if enpas != "-" else 0
score = sum(sunfish.pst[p][i] for i,p in enumerate(board) if p.isupper())
score -= sum(sunfish.pst[p.upper()][119-i] for i,p in enumerate(board) if p.islower())
pos = sunfish.Position(board, score, wc, bc, ep, 0)
return pos if color == "w" else pos.rotate()
def renderFEN(pos, half_move_clock=0, full_move_clock=1):
color = get_color(pos)
if color == "b":
pos = pos.rotate()
board = "/".join(pos.board.split())
board = re.sub(r"\.+", (lambda m: str(len(m.group(0)))), board)
castling = "".join(itertools.compress("KQkq", pos.wc[::-1]+pos.bc)) or "-"
ep = sunfish.render(pos.ep) if not pos.board[pos.ep].isspace() else "-"
clock = "{} {}".format(half_move_clock, full_move_clock)
return " ".join((board, color, castling, ep, clock))