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.format;
19 import java.util.Collections;
20 import java.util.List;
22 import org.hedgecode.chess.pgn.entity.DetailMove;
23 import org.hedgecode.chess.pgn.entity.Move;
24 import org.hedgecode.chess.pgn.entity.Moves;
25 import org.hedgecode.chess.pgn.entity.Variation;
27 import static org.hedgecode.chess.pgn.PGNConstants.*;
32 * @author Dmitry Samoshin aka gotty
34 public class ExportMovesFormat extends AbstractMovesFormat {
37 public String format(List<Move> moves) {
38 Collections.sort(moves);
39 StringBuilder sb = new StringBuilder();
41 for (Move move : moves) {
43 formatSan(move, prevMove)
47 if (move instanceof DetailMove) {
48 DetailMove detailMove = (DetailMove) move;
50 formatAddition(detailMove)
55 return sb.toString().trim();
59 public String format(Moves moves) {
60 Collections.sort(moves.getMoves());
61 StringBuilder sb = new StringBuilder();
63 formatComment(moves.nullMove())
65 DetailMove prevMove = null;
66 for (DetailMove move : moves.getMoves()) {
68 formatSan(move, prevMove)
76 return sb.toString().trim();
79 private String formatSan(Move move, Move prevMove) {
80 return move.ply() % 2 != 0
82 : blackFormat(move, prevMove);
85 private String whiteFormat(Move move) {
87 WHITE_MOVE_FORMAT, move.ply() / 2 + 1, move.move()
91 private String blackFormat(Move move, Move prevMove) {
92 if (prevMove != null && prevMove instanceof DetailMove) {
93 DetailMove detailMove = (DetailMove) prevMove;
94 if (detailMove.comments().size() > 0 || detailMove.variations().size() > 0) {
96 BLACK_MOVE_DOT_FORMAT, move.ply() / 2, move.move()
100 return String.format(BLACK_MOVE_FORMAT, move.move());
103 private String formatAddition(DetailMove move) {
104 StringBuilder sb = new StringBuilder();
108 formatVariation(move)
110 return sb.toString();
113 private String formatComment(DetailMove move) {
114 StringBuilder sb = new StringBuilder();
115 for (String comment : move.comments()) {
117 String.format(COMMENT_FORMAT, comment)
120 return sb.toString();
123 private String formatVariation(DetailMove move) {
124 StringBuilder sb = new StringBuilder();
125 for (Variation variation : move.variations()) {
127 String.format(VARIATION_FORMAT, format(variation))
130 return sb.toString();