1+ package de .hilling .chess ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+ import java .util .regex .Pattern ;
6+
7+ import org .jspecify .annotations .NonNull ;
8+
9+ /**
10+ * Represents a position on the board.
11+ * Objects of this class are immutable, correct coordinates are checked when the constructor is called.
12+ */
13+
14+ public class Position extends Object {
15+ private static final char [] X_CHARACTERS = {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' };
16+ private static final Map <String , Position > VALID_POSITIONS = new HashMap <>();
17+
18+ public final int x ;
19+ public final int y ;
20+ public final String formattedPosition ;
21+
22+ static {
23+ for (int x = 0 ; x < 8 ; x ++) {
24+ for (int y = 0 ; y < 8 ; y ++) {
25+ Position position = new Position (x , y );
26+ VALID_POSITIONS .put (position .formattedPosition , position );
27+ }
28+ }
29+ }
30+
31+ private Position (int x , int y ) {
32+ validatePosition (x , y );
33+ this .x = x ;
34+ this .y = y ;
35+ formattedPosition = String .format ("%c%d" , X_CHARACTERS [x ], y + 1 );
36+ }
37+
38+ private static void validatePosition (int x , int y ) {
39+ if (x < 0 || y < 0 || x > 7 || y > 7 ) {
40+ throw new IllegalArgumentException ("x and y need to be between 0 and 7" );
41+ }
42+ }
43+
44+ /**
45+ * Access Position object via position string (chess notation).
46+ *
47+ * @param positionString position between "a1 and h8".
48+ * @return Position element
49+ * @throws IllegalArgumentException if positionString is invalid.
50+ */
51+ public static @ NonNull Position of (@ NonNull String positionString ) {
52+ Position position = VALID_POSITIONS .get (positionString );
53+ if (position == null ) {
54+ throw new IllegalArgumentException ("Illegal position: " + positionString );
55+ }
56+ return position ;
57+ }
58+
59+ /**
60+ * Access Position object via offset.
61+ *
62+ * @param x x-offset, starting at 0.
63+ * @param y y-offset, starting at 0
64+ * @return Position element
65+ * @throws IllegalArgumentException if x or y are not between 0 and 7.
66+ */
67+ public static @ NonNull Position of (int x , int y ) {
68+ validatePosition (x , y );
69+ return of (String .format ("%c%d" , X_CHARACTERS [x ], y + 1 ));
70+ }
71+
72+ @ Override
73+ public String toString () {
74+ return formattedPosition ;
75+ }
76+ }
0 commit comments