import random def rand(maxVal) : return random.randrange(maxVal+1) def getFileName(setId) : filename = "Set" if setId < 10 : filename += "0" filename += str(setId) filename += ".txt" return filename def howManyDigits(line, pos) : num = 0 while line[pos].isdigit() : num += 1 pos += 1 return num def getStipulation(line) : pos = line.find('#') if pos < 0 : return 2 else : num = howManyDigits(line, pos+1) return int(line[pos+1:pos+1+num]) def getPieces(line) : pos = line.find('[') pos2 = line.find(']') res = [] if pos < 0 or pos2 < 0: return res pieces = line[pos+1:pos2] #print(pieces) list = pieces.split(",") for i in range(len(list)) : list[i] = list[i].strip() for i in range(len(list)) : if len(list[i]) > 3 : return [] # fairy pieces on board - give up #print(len(list)) return list def getX(desc) : ch = desc[1] if ch.isupper() : return ord(ch) - ord("A") else : return ord(ch) - ord("a") def getY(desc) : #print(desc) ch = desc[2] return ord(ch) - ord("0") - 1; def getPiece(desc, isWhite) : if isWhite : return desc[0].upper() else : return desc[0].lower() def makeFENFromBoard(board) : fen = "" for y in range(7,-1,-1) : noPieces = 0 for x in range(8) : if board[x][y] == " " : noPieces += 1 else : if noPieces > 0 : fen += chr(noPieces + ord("0")) noPieces = 0 if board[x][y] == "S" : fen += "N" else : if board[x][y] == "s" : fen += "n" else : fen += board[x][y] if noPieces > 0 : fen += chr(noPieces + ord("0")) noPieces = 0 if y != 0 : fen += "/" #print(fen) return fen def makeFEN(white, black) : w, h = 8, 8 board = [[" " for x in range(w)] for y in range(h)] #print(white) #print(black) for i in range(len(white)) : x = getX(white[i]) y = getY(white[i]) piece = getPiece(white[i], True) board[x][y] = piece for i in range(len(black)) : x = getX(black[i]) y = getY(black[i]) piece = getPiece(black[i], False) board[x][y] = piece return makeFENFromBoard(board) def drawProblem(setId) : probId = 0 filename = getFileName(setId) stipulations = [] fens = [] solutions = [] with open(filename, 'r', errors='ignore') as f: for line in f: if line.startswith("stipulation: ") : curStipulation = getStipulation(line) else : if line.startswith(" white: ") : #print(line) curWhite = getPieces(line) #print(len(curWhite)) else : if line.startswith(" black: ") : curBlack = getPieces(line) #print(len(curBlack)) else : if line == "---\n" : if probId > 0 : if len(curWhite) > 0 and len(curBlack) > 0 : # empty, if fairy pieces on board stipulations.append(curStipulation) fens.append(makeFEN(curWhite, curBlack)) #solutions.append(curSolution) probId += 1 probNum = rand(len(fens) - 1) res = [] res.append(stipulations[probNum]) res.append(fens[probNum]); return res if __name__ == "__main__": for i in range(1,16) : res = drawProblem(i) print(res)