[LIB-9] Set of entities for PGN parsing and formatting
[chesshog.git] / chesshog-format / src / main / java / org / hedgecode / chess / pgn / format / ReduceMovesFormat.java
1 /*
2  * Copyright (c) 2018-2020. Developed by Hedgecode.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.hedgecode.chess.pgn.format;
18
19 import java.util.Collections;
20 import java.util.List;
21
22 import org.hedgecode.chess.pgn.entity.Move;
23 import org.hedgecode.chess.pgn.entity.Moves;
24
25 import static org.hedgecode.chess.pgn.PGNConstants.*;
26
27 /**
28  * ReduceMovesFormat
29  *
30  * @author Dmitry Samoshin aka gotty
31  */
32 public class ReduceMovesFormat extends AbstractMovesFormat {
33
34     @Override
35     public String format(List<Move> moves) {
36         Collections.sort(moves);
37         StringBuilder sb = new StringBuilder();
38         for (Move move : moves) {
39             sb.append(
40                     formatSan(move)
41             ).append(
42                     PGN_SPACE
43             );
44         }
45         return sb.toString().trim();
46     }
47
48     @Override
49     public String format(Moves moves) {
50         return format(
51                 moves.getMoves().toArray(
52                         new Move[moves.getMoves().size()]
53                 )
54         );
55     }
56
57     private String formatSan(Move move) {
58         return move.ply() % 2 != 0
59                 ? String.format(WHITE_MOVE_FORMAT, move.ply() / 2 + 1, move.move())
60                 : String.format(BLACK_MOVE_FORMAT, move.move());
61     }
62
63 }