2 * Copyright (c) 2018-2020. 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.pgn.token;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
22 import org.hedgecode.chess.ParseException;
23 import org.hedgecode.chess.pgn.entity.DetailMove;
24 import org.hedgecode.chess.pgn.entity.MoveNumber;
25 import org.hedgecode.chess.pgn.entity.Moves;
26 import org.hedgecode.chess.pgn.nag.Glyph;
27 import org.hedgecode.chess.pgn.token.san.CommonSANToken;
28 import org.hedgecode.chess.pgn.token.san.SANToken;
33 * @author Dmitry Samoshin aka gotty
35 public class MoveToken implements Token<Moves> {
37 public static final String MOVE_REGEX = "^\\s*([PNBRQKa-hx1-8=+#\\-O!?]+)(\\s+\\$([0-9]+))?";
38 private static final Pattern MOVE_PATTERN = Pattern.compile(MOVE_REGEX);
39 private static final int MOVE_GROUP = 1, NAG_GROUP = 3;
41 private final Token<MoveNumber> moveNumberToken = new MoveNumberToken();
42 private final SANToken moveSanToken = new CommonSANToken();
45 public int token(Moves moves, String pgn) throws ParseException {
46 MoveNumber moveNumber = new MoveNumber(
47 moves.currentMove().ply()
49 int numberLength = moveNumberToken.token(moveNumber, pgn);
50 if (numberLength > 0) {
51 pgn = pgn.substring(numberLength);
53 Matcher matcher = MOVE_PATTERN.matcher(pgn);
54 if (!matcher.find()) {
55 throw new ParseException("parse.pgn.incorrect.move", pgn);
57 String move = matcher.group(MOVE_GROUP);
58 moveSanToken.token(move);
59 DetailMove detailMove = new DetailMove(
60 moveNumber.ply(), move
65 String glyph = matcher.group(NAG_GROUP); // todo: more then one NAG
69 Integer.parseInt(glyph)
74 return numberLength + matcher.group().length();