[LIB-9] Chessboard squares sorting
[chesshog.git] / src / main / java / org / hedgecode / chess / position / SquareSort.java
1 /*
2  * Copyright (c) 2018. 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.position;
18
19 import java.util.Comparator;
20
21 /**
22  *
23  *
24  * @author Dmitry Samoshin aka gotty
25  */
26 public enum SquareSort {
27
28     A1H8 (
29             new A1H8Comparator()
30     ),
31
32     H8A1 (
33             new H8A1Comparator()
34     ),
35
36     A8H1 (
37             new A8H1Comparator()
38     );
39
40     Comparator<Square> comparator;
41
42     SquareSort(Comparator<Square> comparator) {
43         this.comparator = comparator;
44     }
45
46     public Comparator<Square> comparator() {
47         return comparator;
48     }
49
50     public static SquareSort defaultSort() {
51         return SquareSort.A1H8;
52     }
53
54
55     static class A1H8Comparator implements Comparator<Square> {
56
57         @Override
58         public int compare(Square square1, Square square2) {
59             return square1.getH() == square2.getH()
60                     ? square1.getV() == square2.getV() ? 0
61                     : square1.getV() > square2.getV() ? 1 : -1
62                     : square1.getH() > square2.getH() ? 1 : -1;
63         }
64     }
65
66     static class H8A1Comparator implements Comparator<Square> {
67
68         @Override
69         public int compare(Square square1, Square square2) {
70             return square1.getH() == square2.getH()
71                     ? square1.getV() == square2.getV() ? 0
72                     : square1.getV() < square2.getV() ? 1 : -1
73                     : square1.getH() < square2.getH() ? 1 : -1;
74         }
75     }
76
77     static class A8H1Comparator implements Comparator<Square> {
78
79         @Override
80         public int compare(Square square1, Square square2) {
81             return square1.getH() == square2.getH()
82                     ? square1.getV() == square2.getV() ? 0
83                     : square1.getV() > square2.getV() ? 1 : -1
84                     : square1.getH() < square2.getH() ? 1 : -1;
85         }
86     }
87
88 }