[LIB-9] Separate chesshog-uci module
[chesshog.git] / chesshog-uci / src / main / java / org / hedgecode / chess / uci / command / AbstractCommand.java
diff --git a/chesshog-uci/src/main/java/org/hedgecode/chess/uci/command/AbstractCommand.java b/chesshog-uci/src/main/java/org/hedgecode/chess/uci/command/AbstractCommand.java
new file mode 100644 (file)
index 0000000..0f65888
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2018. Developed by Hedgecode.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.hedgecode.chess.uci.command;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.hedgecode.chess.position.Piece;
+import org.hedgecode.chess.position.Square;
+import org.hedgecode.chess.uci.UCICommand;
+import org.hedgecode.chess.uci.UCIConstants;
+
+/**
+ * Abstract UCI command with parsing functionality.
+ *
+ * @author Dmitry Samoshin aka gotty
+ */
+public abstract class AbstractCommand implements UCICommand {
+
+    private static final String NULLMOVE = UCIConstants.NULLMOVE;
+
+    private static final Pattern MOVE_PATTERN = Pattern.compile(UCIConstants.MOVE_REGEX);
+
+    private static final int SQUARE_FROM = UCIConstants.MOVE_REGEX_FROM;
+    private static final int SQUARE_TO = UCIConstants.MOVE_REGEX_TO;
+    private static final int PIECE_PROMOTE = UCIConstants.MOVE_REGEX_PROMOTE;
+
+
+    protected Move parseMove(String move) {
+        if (NULLMOVE.equals(move))
+            return new Move(null, null);
+
+        Matcher matcher = MOVE_PATTERN.matcher(move);
+        if (matcher.find()) {
+            return new Move(
+                    Square.getSquare(matcher.group(SQUARE_FROM)),
+                    Square.getSquare(matcher.group(SQUARE_TO)),
+                    Piece.byLetter(matcher.group(PIECE_PROMOTE))
+            );
+        }
+        return null;
+    }
+
+}