Rotating the display of the board - north is on top. Enhancing the display with row ids and column numbers and compass directions.
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * The contents of this file are subject to the terms of either the GNU
5 * General Public License Version 2 only ("GPL") or the Common
6 * Development and Distribution License("CDDL") (collectively, the
7 * "License"). You may not use this file except in compliance with the
8 * License. You can obtain a copy of the License at
9 * http://www.netbeans.org/cddl-gplv2.html
10 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
11 * specific language governing permissions and limitations under the
12 * License. When distributing the software, include this License Header
13 * Notice in each file and include the License file at
14 * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
15 * particular file as subject to the "Classpath" exception as provided
16 * by Sun in the GPL Version 2 section of the License file that
17 * accompanied this code. If applicable, add the following below the
18 * License Header, with the fields enclosed by brackets [] replaced by
19 * your own identifying information:
20 * "Portions Copyrighted [year] [name of copyright owner]"
24 * Portions Copyrighted 2009 Jaroslav Tulach
27 package cz.xelfi.quoridor;
29 import cz.xelfi.quoridor.Player.Direction;
30 import java.io.BufferedReader;
31 import java.io.EOFException;
32 import java.io.IOException;
33 import java.io.Reader;
34 import java.io.StringWriter;
35 import java.io.Writer;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.BitSet;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
48 * Represents a snapshot of the game position,
49 * including all the placed and not-yet placed fences and player positions.
50 * It it can print itself to stream in
51 * <a href="http://www.gamerz.net/pbmserv/quoridor.html">ascii art format<a/>
52 * and can it read back. The class is immutable
53 * but it contains {@link #apply(cz.xelfi.quoridor.Move)}
54 * that produce new {@link Board} with position created after
55 * applying some {@link Move}. Use:
57 * Board whiteOnTurn = Board.empty();
58 * Board blackOnTurn = whiteOnTurn.apply(Move.NORTH);
59 * Board whiteAgain = blackOnTurn.apply(Move.SOUTH);
60 * Board withOneFence = whiteAgain.apply(Move.fence('D', 7));
63 * @author Jaroslav Tulach
65 public final class Board {
67 private final List<Player> players;
68 /** fences placed on board */
69 private final Set<Fence> fences;
70 /** occurpied bits (coordinates encoded by toIndex methods)
73 +-----------------------------------+
91 +-----------------------------------+
92 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
95 * even indexes == position of the pawns
96 * odd indexes == centers of fences
97 * even x odd == side of a fence
98 * odd x even == side of a fence
100 private final BitSet occupied;
101 /** which player's turn is next? */
102 private final int turn;
105 * Creates a new instance of Board
107 private Board (int x1, int y1, int f1, int x2, int y2, int f2) {
108 this.players = Collections.unmodifiableList (Arrays.asList (new Player[] {
109 new Player (x1, y1, f1, Player.Direction.NORTH),
110 new Player (x2, y2, f2, Player.Direction.SOUTH),
112 this.fences = Collections.emptySet ();
114 this.occupied = computeOccupied (players, fences);
115 } catch (IllegalPositionException ex) {
116 throw new IllegalStateException (ex.getMessage ());
121 /** Copy constructor that provides players and fences.
123 private Board (int turn, List<Player> players, Set<Fence> fences)
124 throws IllegalPositionException {
125 this.players = Collections.unmodifiableList (players);
126 this.fences = Collections.unmodifiableSet (fences);
127 this.occupied = computeOccupied (players, fences);
129 for (Player p : players) {
130 if (!accessibleFinalLine (p, p.endDirection, occupied, new BitSet ())) {
131 throw new IllegalPositionException ("Player " + p + " cannot reach " + p.endDirection + " side"); // NOI18N
134 this.turn = turn % players.size();
137 /** Returns empty board with default starting position.
138 * @return board with two pawns.
140 public static Board empty () {
141 return new Board (8, 0, 10, 8, 16, 10);
144 /** Returns players in the game.
145 * @return player object
147 public List<Player> getPlayers () {
151 /** The fences currently on board.
153 * @return immutable set of Fences
155 public Set<Fence> getFences () {
159 /** The player that is supposed to play now.
160 * @return the player to do next move
162 public Player getCurrentPlayer() {
163 return players.get(turn);
166 /** The play who wins on current board.
168 * @return the winning player or <code>null</code>
170 public Player getWinner() {
171 for (Player p : players) {
172 if (p.endDirection.reached(p)) {
179 /** Applies given move to current board.
181 * @param move move creates by one of the factory methods or fields of the {@link Move} class
182 * @return new board derived from this one
184 * @throws cz.xelfi.quoridor.IllegalPositionException throws exception if the move is illegal
186 public Board apply(Move move) throws IllegalPositionException {
187 if (getWinner() != null) {
188 throw new IllegalPositionException("Game finished!"); // NOI18N
191 if (move.direction != null) {
192 return move(getCurrentPlayer(), move.direction);
194 return fence(getCurrentPlayer(), move.fence);
198 /** Can the move be applied to current board position?
200 * @param move the move to apply
201 * @return true if one can call {@link #apply} method without getting
204 public boolean isApplicable(Move move) {
206 // trivial implementation is enough for now
209 } catch (IllegalPositionException ex) {
214 /** Moves the player in given direction. The direction usually
215 * is one of Player.Direction constants, but in case the move
216 * is a jump over another players pawn it can be followed by
217 * another (usually, if there is no fence the same) direction.
219 * @param player the player to move
220 * @param where one or two directions saying where
221 * @return the new board
222 * @exception IllegalPositionException if the move is not possible
224 final Board move (Player player, Player.Direction... where) throws IllegalPositionException {
225 if (where.length != 1 && where.length != 2) {
226 throw new IllegalPositionException ("Move over one or two Directions"); // NOI18N
229 int index = players.indexOf (player);
230 Player[] arr = players.toArray (new Player[0]);
232 Player oneStep = newPosition (player, where[0]);
234 if (where.length == 1) {
235 arr[index] = oneStep;
236 return new Board(turn + 1, Arrays.asList (arr), fences);
239 // straight jump over
240 for (Player p : players) {
241 if (p.getXInternal () == oneStep.getXInternal () && p.getYInternal() == oneStep.getYInternal ()) {
242 // ok, we are jumping over this one
243 GO_ON: if (where[0] != where[1]) {
244 // first of all ensure that we cannot go straight
246 newPosition (oneStep, where[0]);
247 } catch (IllegalPositionException ex) {
251 throw new IllegalPositionException ("You have to jump straight if there is no wall"); // NOI18N
253 arr[index] = newPosition (oneStep, where[1]);
254 return new Board (turn + 1, Arrays.asList (arr), fences);
257 throw new IllegalPositionException ("Cannot use multi direction when there is not oponent pawn"); // NOI18N
260 final Board fence (Player player, char x, int y, Fence.Orientation orientation) throws IllegalPositionException {
261 return fence(player, new Fence ((x - 'A') * 2 + 1, y * 2 - 1, orientation));
264 private void columnLine(int width, int spaceX, Writer w) throws IOException {
266 for (int x = 0; x < width - 1; x++) {
267 if (x % (spaceX + 1) == 0 && x > 0) {
269 ch = (char) (ch + 1);
276 private Board fence(Player player, Fence fence) throws IllegalPositionException {
277 if (player.getFences () == 0) {
278 throw new IllegalPositionException ("Not enough fences: " + player); // NOI18N
281 int index = players.indexOf (player);
282 Player[] arr = players.toArray (new Player[0]);
283 arr[index] = new Player (arr[index].getXInternal(), arr[index].getYInternal(), arr[index].getFences() - 1, arr[index].endDirection);
285 HashSet<Fence> fen = new HashSet<Fence> (this.fences);
288 return new Board (turn + 1, Arrays.asList (arr), fen);
295 private static final Pattern northSouthPattern = Pattern.compile("(\\+(\\|*)(\\*)?-+\\+)");
296 public static Board read(Reader r) throws IOException, IllegalPositionException {
297 BufferedReader b = new BufferedReader(r);
299 String s = b.readLine();
301 throw new IOException("No board found!");
303 Matcher m = northSouthPattern.matcher(s);
305 return readFromBetween(b, m);
310 private static int assertChar(String s, int pos, char... ch) throws IOException {
311 if (s.length() >= pos) {
312 for (int i = 0; i < ch.length; i++) {
313 if (ch[i] == s.charAt(pos)) {
318 throw new IOException("Not found " + ch[0] + " at " + pos + " in" + s);
321 private static Player findPlayer(
322 Player previous, String line, int y, int spaceX, Player.Direction dir, int fences
324 int index = line.indexOf(dir.player);
328 int x = (index - 1) / (spaceX + 1) * 2;
329 return new Player(x, y - 1, fences, dir);
332 private static Board readFromBetween(BufferedReader b, Matcher firstMatcher)
333 throws IOException, IllegalPositionException {
334 final int from = firstMatcher.start(1);
335 final int to = firstMatcher.end(1);
336 final int northFences = firstMatcher.end(2) - firstMatcher.start(2);
337 final int spaceX = (to - from - 1) / 9 - 1;
338 final int spaceY = 1;
342 Set<Fence> fences = new HashSet<Fence>();
344 StringBuffer sb = new StringBuffer();
346 for (int y = (spaceY + 1) * 9 - 1; y > 0; y--) {
347 String s = b.readLine();
349 throw new EOFException();
353 if (s.length() < to) {
354 throw new IOException("Too short line: " + s); // NOI18N
356 assertChar(s, from, '|');
357 assertChar(s, to - 1, '|');
359 if (y % (spaceY + 1) == 0) {
360 for (int x = 1; x < 9; x++) {
361 switch (assertChar(s, from + (spaceX + 1) * x, '+', '-', '|')) {
363 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.HORIZONTAL));
366 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.VERTICAL));
376 String line = s.substring(from, to);
377 p = findPlayer(p, line, y, spaceX, Player.Direction.NORTH, -1);
378 q = findPlayer(q, line, y, spaceX, Player.Direction.SOUTH, northFences);
382 String last = b.readLine();
384 throw new EOFException();
386 Matcher lastMatcher = northSouthPattern.matcher(last);
387 if (!lastMatcher.find()) {
388 throw new IOException("Unrecognized last line: " + last);
391 List<Player> arr = new ArrayList<Player>(2);
393 int southFences = lastMatcher.end(2) - lastMatcher.start(2);
394 arr.add(new Player(p.getXInternal(), p.getYInternal(), southFences, p.endDirection));
396 int turn = "*".equals(lastMatcher.group(3)) ? 0 : 1; // NOI18N
397 return new Board(turn, arr, fences);
402 /** Writes the board to the provided writer. <b>P</b> denotes position
403 * of the first player and <b>Q</b> of the second. Number of remaining
404 * fences of each player are shown in left bottom and left top corner
405 * as appropriate number of <b>|||</b> - one <b>|</b> per fence. The
406 * player that is supposed to move in this turn has <b>*</b> right after
407 * the set of its fences.
414 +|||||------------------------------+
416 8--| + + + + + + + + |--8
418 7--| + | + +-------+-------+ |--7
420 6--|-------+-------|-------+-------+ |--6
422 5--| + + + + + + + + |--5
424 4--| + + + | + + +-------|--4
426 3--| + + + +-------+ + + |--3
428 2--| + + + + + + + + |--2
430 1--| + + + + + | + + |--1
432 +|||*-------------------------------+
438 * @param w writer to write the board to
439 * @exception IOException if communiction with writer fails
441 public void write (Writer w) throws IOException {
445 private void northSouthSign(int width, char sign, Writer w) throws IOException {
446 int middle = width / 2;
447 for (int x = 0; x < width; x++) {
449 if (x == middle - 1) {
455 if (x == middle + 1) {
460 w.write(System.getProperty("line.separator")); // NOI18N
463 private void subColumnLine(int width, int spaceX, Writer w) throws IOException {
464 for (int x = 0; x < width - 1; x++) {
465 if (x % (spaceX + 1) == 0 && x > 0) {
473 /** This will print the board with provided spacing.
474 * This is example of 3:1 spacing:
480 * and this 4:2 spacing:
488 private void write (Writer w, int spaceX, int spaceY) throws IOException {
489 int width = spaceX * 9 + 10;
490 int height = spaceY * 9 + 10;
491 char[][] desk = new char[height][];
492 for (int i = 0; i < height; i++) {
493 desk[i] = new char[width];
494 for (int j = 0; j < width; j++) {
495 if (i % (spaceY + 1) == 0 && j % (spaceX + 1) == 0) {
502 desk[i][width - 1] = '|';
504 for (int i = 1; i < width - 1; i++) {
506 desk[height -1][i] = '-';
509 desk[0][width - 1] = '+';
510 desk[height - 1][0] = '+';
511 desk[height - 1][width - 1] = '+';
514 for (Player p : players) {
515 int px = p.getXInternal() / 2;
516 int py = p.getYInternal() / 2;
518 [1 + py * (spaceY + 1) + spaceY / 2]
519 [1 + px * (spaceX + 1) + spaceX / 2] = p.endDirection.player;
520 paintLeftFences(desk, p.endDirection, p.getFences(), p.equals(getCurrentPlayer()));
524 for (Fence f : fences) {
525 int fx = (f.getX() / 2 + 1) * (spaceX + 1);
526 int fy = (f.getY() / 2 + 1) * (spaceY + 1);
527 switch (f.getOrientation()) {
529 for (int i = -spaceX; i <= spaceX; i++) {
530 desk[fy][fx + i] = '-';
534 for (int i = -spaceY; i <= spaceY; i++) {
535 desk[fy + i][fx] = '|';
539 throw new IllegalStateException ("Unknown orientation: " + f.getOrientation ()); // NOI18N
543 northSouthSign(width, 'N', w);
544 w.write(System.getProperty("line.separator")); // NOI18N
546 columnLine(width, spaceX, w);
547 w.write(System.getProperty("line.separator")); // NOI18N
549 subColumnLine(width, spaceX, w);
550 w.write(System.getProperty("line.separator")); // NOI18N
552 for (int y = height - 1; y >= 0; y--) {
553 if (y == height / 2) {
558 boolean number = y % (spaceY + 1) == 0 && y > 0 && y < height - 1;
561 w.write(Integer.toString(cnt));
566 for (int x = 0; x < width; x++) {
571 w.write(Integer.toString(cnt));
575 if (y == height / 2) {
578 w.write(System.getProperty("line.separator")); // NOI18N
581 subColumnLine(width, spaceX, w);
582 w.write(System.getProperty("line.separator")); // NOI18N
584 columnLine(width, spaceX, w);
585 w.write(System.getProperty("line.separator")); // NOI18N
586 w.write(System.getProperty("line.separator")); // NOI18N
588 northSouthSign(width, 'S', w);
592 private void paintLeftFences(char[][] desk, Direction endDirection, int fences, boolean currentTurn) {
593 assert fences >= 0 && fences <= 10 : "Players: " + players;
594 switch (endDirection) {
596 for (int i = 0; i < fences; i++) {
597 desk[desk.length - 1][i + 1] = '|';
600 desk[desk.length - 1][fences + 1] = '*';
605 for (int i = 0; i < fences; i++) {
606 desk[0][i + 1] = '|';
609 desk[0][fences + 1] = '*';
625 public int hashCode () {
626 return occupied.hashCode ();
630 public boolean equals (Object o) {
631 if (o instanceof Board) {
633 return occupied.equals (b.occupied) && players.equals (b.players);
639 public String toString() {
640 StringWriter w = new StringWriter();
643 } catch (IOException ex) {
644 return ex.toString();
651 // Validation methods
654 /** Computes new position of a player and checks whether there is no
655 * fence between the old and new.
657 private Player newPosition (Player old, Player.Direction direction) throws IllegalPositionException {
658 return newPosition (old, direction, occupied);
662 private static Player newPosition (Player old, Player.Direction direction, BitSet occupied) throws IllegalPositionException {
685 default: throw new IllegalStateException ("Unknown direction: " + direction); // NOI18N
688 if (nx < 0 || nx > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
689 if (ny < 0 || ny > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
691 int fenceIndex = toIndex (fx, fy);
692 if (occupied.get (fenceIndex)) {
693 throw new IllegalPositionException ("You cannot go over fences"); // NOI18N
696 return new Player (nx, ny, old.getFences (), old.endDirection);
699 /** @param position the current position of the player
700 * @param endDir the side the player wants to reach
701 * @param fences bits set to 1 when fences are placed
702 * @param reached bits on squares that were already reached (modified during run)
703 * @return true if the end line can be reached
705 private static boolean accessibleFinalLine (Player position, Player.Direction endDir, BitSet fences, BitSet reached) {
706 int index = toIndex (position);
707 if (reached.get (index)) {
708 // already visited without success
714 if (position.getYInternal() == 8) return true;
717 if (position.getYInternal() == 0) return true;
720 if (position.getXInternal() == 0) return true;
723 if (position.getXInternal() == 8) return true;
726 throw new IllegalStateException ("Wrong direction: " + endDir); // NOI18N
731 for (Player.Direction oneDirection : Player.Direction.values ()) {
733 if (accessibleFinalLine (newPosition (position, oneDirection, fences), endDir, fences, reached)) {
736 } catch (IllegalPositionException ex) {
744 /** Computes mask of the occupried bits.
746 private static BitSet computeOccupied (
747 Collection<Player> players, Collection<Fence> fences
748 ) throws IllegalPositionException {
749 BitSet occupied = new BitSet (20 * 30); // TBD this is just an upper guess
751 for (Player p : players) {
752 if (p.getXInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
753 if (p.getYInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
755 int index = toIndex (p);
756 if (occupied.get (index)) {
757 throw new IllegalPositionException ("There cannot be two players at " + p); // NOI18N
759 occupied.set (index);
762 for (Fence f : fences) {
764 for (int i = -1; i <= 1; i++) {
765 int index = toIndex (f, i);
766 if (index < 0 || index > occupied.size ()) {
767 throw new IllegalPositionException ("Wrong fence position: " + f); // NOI18N
769 if (occupied.get (index)) {
770 throw new IllegalPositionException ("Fence collition: " + f); // NOI18N
773 occupied.set (index);
781 /** Converts twodimensional coordinates of player to one dimensional index.
783 private static int toIndex (Player p) {
784 return toIndex (p.getXInternal(), p.getYInternal());
787 /** Converts twodimensional coordinates of fence to one dimensional index.
789 * @param whichPart (-1, 0, 1)
791 private static int toIndex (Fence f, int whichPart) {
795 switch (f.getOrientation ()) {
796 case HORIZONTAL: x += whichPart; break;
797 case VERTICAL: y += whichPart; break;
798 default: throw new IllegalStateException ("Wrong orientation: " + f.getOrientation ()); // NOI18N
801 return toIndex (x, y);
804 /** Diagonal conversion of two positive integers to one integer.
813 private static int toIndex (int x, int y) {
815 int baseOnY0 = max * (max + 1) / 2;