Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add FEN-string validator based on regular expression #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions fen_validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import re

def fenPass(fen):
regexMatch=re.match('\s*^(((?:[rnbqkpRNBQKP1-8]+\/){7})[rnbqkpRNBQKP1-8]+)\s([b|w])\s([K|Q|k|q]{1,4})\s(-|[a-h][1-8])\s(\d+\s\d+)$', fen)
if regexMatch:
regexList = regexMatch.groups()
fen = regexList[0].split("/")
if len(fen) != 8:
raise ValueError("expected 8 rows in position part of fen: {0}".format(repr(fen)))

for fenPart in fen:
field_sum = 0
previous_was_digit, previous_was_piece = False,False

for c in fenPart:
if c in ["1", "2", "3", "4", "5", "6", "7", "8"]:
if previous_was_digit:
raise ValueError("two subsequent digits in position part of fen: {0}".format(repr(fen)))
field_sum += int(c)
previous_was_digit = True
previous_was_piece = False
elif c == "~":
if not previous_was_piece:
raise ValueError("~ not after piece in position part of fen: {0}".format(repr(fen)))
previous_was_digit, previous_was_piece = False,False
elif c.lower() in ["p", "n", "b", "r", "q", "k"]:
field_sum += 1
previous_was_digit = False
previous_was_piece = True
else:
raise ValueError("invalid character in position part of fen: {0}".format(repr(fen)))

if field_sum != 8:
raise ValueError("expected 8 columns per row in position part of fen: {0}".format(repr(fen)))

else: raise ValueError("fen doesn`t match follow this example: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 ")
8 changes: 8 additions & 0 deletions pystockfish.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import re
import subprocess
from random import randint

from fen_validator import fenPass

MAX_MOVES = 200
UCI_MOVE_REGEX = "[a-h]\d[a-h]\d[qrnb]?"
PV_REGEX = " pv (?P<move_list>{0}( {0})*)".format(UCI_MOVE_REGEX)
Expand Down Expand Up @@ -195,6 +198,11 @@ def setfenposition(self, fen):
"""
set position in fen notation. Input is a FEN string i.e. "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"
"""
try:
fenPass(fen)
except ValueError as e:
print(e.message)

self.put('position fen %s' % fen)
self.isready()

Expand Down