2 * Copyright (c) 2018. Developed by Hedgecode.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.hedgecode.chess.wiki;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
24 import org.hedgecode.chess.position.ParseException;
25 import org.hedgecode.chess.position.Parser;
26 import org.hedgecode.chess.position.Position;
27 import org.hedgecode.chess.position.Positions;
28 import org.hedgecode.chess.position.Square;
31 * Wikipedia chess diagram parser.
33 * @author Dmitry Samoshin aka gotty
35 public final class WikiParser implements Parser {
37 private static final String LINE_REGEX = "\\r?\\n";
38 private static final String SQUARE_REGEX = String.format("[%s]", Wiki.SEPARATOR);
40 private static final Pattern PATTERN =
42 String.format("^([%s][^%s]*){%d}$", Wiki.SEPARATOR, Wiki.SEPARATOR, Square.getSize())
45 private static Parser _instance = new WikiParser();
47 private WikiParser() {
51 public Position parse(String string) throws ParseException {
53 string.split(LINE_REGEX)
57 private Position _parse(String[] strings) throws ParseException {
58 List<String> lines = new ArrayList<>();
59 for (String line : strings) {
60 Matcher matcher = PATTERN.matcher(line);
67 if (lines.size() != Square.getSize())
68 throw new ParseException("parse.wiki.incorrect.board");
69 Position position = Positions.EMPTY.getPosition();
72 new String[lines.size()]
79 private void _parsePieces(String[] lines, Position position) throws ParseException {
80 for (int i = 0; i < lines.length; ++i) {
81 int line = lines.length - i;
82 String[] pieces = lines[i].split(SQUARE_REGEX, -1);
83 if (pieces.length != Square.getSize() + 1)
84 throw new ParseException("parse.wiki.incorrect.board");
85 for (int j = 1; j < pieces.length; ++j) {
87 Wiki.getColorPiece(pieces[j]),
88 Square.getSquare(j - 1, line - 1)
94 public static Parser getInstance() {
99 public static void main(String[] args) throws ParseException {
100 Position position = getInstance().parse(
101 "{{Шахматная диаграмма\n" +
104 "|rd|nd|bd|qd|kd|bd|nd|rd\n" +
105 "|pd|pd| |pd|pd|pd|pd|pd\n" +
106 "| | | | | | | |\n" +
107 "| | | | | | | |\n" +
108 "| | | |pd|pl| | |\r\n" +
109 "| | |pl| | | | |\n" +
110 "|pl|pl| | | |pl|pl|pl\n" +
111 "|rl|nl|bl|ql|kl|bl|nl|rl\n" +
114 System.out.println(position);