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.StringReader;
35 import java.io.StringWriter;
36 import java.io.Writer;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.BitSet;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.HashSet;
43 import java.util.List;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
49 * Represents a snapshot of the game position,
50 * including all the placed and not-yet placed fences and player positions.
51 * It it can print itself to stream in
52 * <a href="http://www.gamerz.net/pbmserv/quoridor.html">ascii art format<a/>
53 * and can it read back. The class is immutable
54 * but it contains {@link #apply(cz.xelfi.quoridor.Move)}
55 * that produce new {@link Board} with position created after
56 * applying some {@link Move}. Use:
58 * Board whiteOnTurn = Board.empty();
59 * Board blackOnTurn = whiteOnTurn.apply(Move.NORTH);
60 * Board whiteAgain = blackOnTurn.apply(Move.SOUTH);
61 * Board withOneFence = whiteAgain.apply(Move.fence('D', 7));
64 * @author Jaroslav Tulach
66 public final class Board {
68 private final Player winner;
70 private final List<Player> players;
71 /** fences placed on board */
72 private final Set<Fence> fences;
73 /** occurpied bits (coordinates encoded by toIndex methods)
76 +-----------------------------------+
94 +-----------------------------------+
95 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
98 * even indexes == position of the pawns
99 * odd indexes == centers of fences
100 * even x odd == side of a fence
101 * odd x even == side of a fence
103 private final BitSet occupied;
104 /** which player's turn is next? */
105 private final int turn;
108 * Creates a new instance of Board
110 private Board (int x1, int y1, int f1, int x2, int y2, int f2) {
111 this.players = Collections.unmodifiableList (Arrays.asList (new Player[] {
112 new Player (x1, y1, f1, Player.Direction.NORTH),
113 new Player (x2, y2, f2, Player.Direction.SOUTH),
115 this.fences = Collections.emptySet ();
117 this.occupied = computeOccupied (players, fences);
118 } catch (IllegalPositionException ex) {
119 throw new IllegalStateException (ex.getMessage ());
125 /** Copy constructor that provides players and fences.
127 private Board (int turn, List<Player> players, Set<Fence> fences)
128 throws IllegalPositionException {
129 this.players = Collections.unmodifiableList (players);
130 this.fences = Collections.unmodifiableSet (fences);
131 this.occupied = computeOccupied (players, fences);
133 for (Player p : players) {
134 if (!accessibleFinalLine (p, p.endDirection, occupied, new BitSet ())) {
135 throw new IllegalPositionException ("Player " + p + " cannot reach " + p.endDirection + " side"); // NOI18N
138 this.turn = turn % players.size();
142 /** Copy constructor for resigning the game */
143 private Board(Board previous, int winner) {
144 this.players = previous.players;
145 this.turn = winner % players.size();
146 this.fences = previous.fences;
147 this.occupied = previous.occupied;
148 this.winner = players.get(this.turn);
151 /** Returns empty board with default starting position.
152 * @return board with two pawns.
154 public static Board empty () {
155 return new Board (8, 0, 10, 8, 16, 10);
158 /** Returns players in the game.
159 * @return player object
161 public List<Player> getPlayers () {
165 /** The fences currently on board.
167 * @return immutable set of Fences
169 public Set<Fence> getFences () {
173 /** The player that is supposed to play now.
174 * @return the player to do next move, null if the game is over
176 public Player getCurrentPlayer() {
177 if (getWinner() != null) {
180 return players.get(turn);
183 /** The play who wins on current board.
185 * @return the winning player or <code>null</code>
187 public Player getWinner() {
188 if (winner != null) {
191 for (Player p : players) {
192 if (p.endDirection.reached(p)) {
199 /** Applies given move to current board.
201 * @param move move creates by one of the factory methods or fields of the {@link Move} class
202 * @return new board derived from this one
204 * @throws cz.xelfi.quoridor.IllegalPositionException throws exception if the move is illegal
206 public Board apply(Move move) throws IllegalPositionException {
207 if (getWinner() != null) {
208 throw new IllegalPositionException("Game finished!"); // NOI18N
211 if (move.direction != null) {
212 return move(getCurrentPlayer(), move.direction);
214 if (move.fence != null) {
215 return fence(getCurrentPlayer(), move.fence);
217 return new Board(this, turn + 1);
222 /** Can the move be applied to current board position?
224 * @param move the move to apply
225 * @return true if one can call {@link #apply} method without getting
228 public boolean isApplicable(Move move) {
230 // trivial implementation is enough for now
233 } catch (IllegalPositionException ex) {
238 /** Moves the player in given direction. The direction usually
239 * is one of Player.Direction constants, but in case the move
240 * is a jump over another players pawn it can be followed by
241 * another (usually, if there is no fence the same) direction.
243 * @param player the player to move
244 * @param where one or two directions saying where
245 * @return the new board
246 * @exception IllegalPositionException if the move is not possible
248 final Board move (Player player, Player.Direction... where) throws IllegalPositionException {
249 if (where.length != 1 && where.length != 2) {
250 throw new IllegalPositionException ("Move over one or two Directions"); // NOI18N
253 int index = players.indexOf (player);
254 Player[] arr = players.toArray (new Player[0]);
256 Player oneStep = newPosition (player, where[0]);
258 if (where.length == 1) {
259 arr[index] = oneStep;
260 return new Board(turn + 1, Arrays.asList (arr), fences);
263 // straight jump over
264 for (Player p : players) {
265 if (p.getXInternal () == oneStep.getXInternal () && p.getYInternal() == oneStep.getYInternal ()) {
266 // ok, we are jumping over this one
267 GO_ON: if (where[0] != where[1]) {
268 // first of all ensure that we cannot go straight
270 newPosition (oneStep, where[0]);
271 } catch (IllegalPositionException ex) {
275 throw new IllegalPositionException ("You have to jump straight if there is no wall"); // NOI18N
277 arr[index] = newPosition (oneStep, where[1]);
278 return new Board (turn + 1, Arrays.asList (arr), fences);
281 throw new IllegalPositionException ("Cannot use multi direction when there is not oponent pawn"); // NOI18N
284 final Board fence (Player player, char x, int y, Fence.Orientation orientation) throws IllegalPositionException {
285 return fence(player, new Fence ((x - 'A') * 2 + 1, y * 2 - 1, orientation));
288 private void columnLine(int width, int spaceX, Writer w) throws IOException {
290 for (int x = 0; x < width - 1; x++) {
291 if (x % (spaceX + 1) == 0 && x > 0) {
293 ch = (char) (ch + 1);
300 private Board fence(Player player, Fence fence) throws IllegalPositionException {
301 if (player.getFences () == 0) {
302 throw new IllegalPositionException ("Not enough fences: " + player); // NOI18N
305 int index = players.indexOf (player);
306 Player[] arr = players.toArray (new Player[0]);
307 arr[index] = new Player (arr[index].getXInternal(), arr[index].getYInternal(), arr[index].getFences() - 1, arr[index].endDirection);
309 HashSet<Fence> fen = new HashSet<Fence> (this.fences);
312 return new Board (turn + 1, Arrays.asList (arr), fen);
319 private static final Pattern northSouthPattern = Pattern.compile("(\\+(\\|*)(\\*)?-+\\+)");
321 /** Reads the board from a reader. Opposite operation to {@link #write(java.io.Writer)}.
323 * @param r the reader
324 * @return the read board
325 * @throws IOException if I/O error occurs
326 * @throws IllegalPositionException if the reader does not contain description
329 public static Board read(Reader r) throws IOException, IllegalPositionException {
330 BufferedReader b = new BufferedReader(r);
332 String s = b.readLine();
334 throw new IOException("No board found!");
336 Matcher m = northSouthPattern.matcher(s);
338 return readFromBetween(b, m);
343 /** Translates the string into board, if possible. String created by
344 * use of {@link #toString()} is accepted, more information about the
345 * format is avaliable in the description of {@link #write(java.io.Writer)}
348 * @param board string to analyze
349 * @return board object, if the string can be read
350 * @throws IllegalPositionException if the string does not represent the board
352 public static Board valueOf(String board) throws IllegalPositionException {
354 return read(new StringReader(board));
355 } catch (IOException ex) {
356 // shall not happen, StringReader does not throw IOException
357 throw (IllegalPositionException)new IllegalPositionException(ex.getMessage()).initCause(ex);
361 private static int assertChar(String s, int pos, char... ch) throws IOException {
362 if (s.length() >= pos) {
363 for (int i = 0; i < ch.length; i++) {
364 if (ch[i] == s.charAt(pos)) {
369 throw new IOException("Not found " + ch[0] + " at " + pos + " in" + s);
372 private static Player findPlayer(
373 Player previous, String line, int y, int spaceX, Player.Direction dir, int fences
375 int index = line.indexOf(dir.player);
379 int x = (index - 1) / (spaceX + 1) * 2;
380 return new Player(x, y - 1, fences, dir);
383 private static Board readFromBetween(BufferedReader b, Matcher firstMatcher)
384 throws IOException, IllegalPositionException {
385 final int from = firstMatcher.start(1);
386 final int to = firstMatcher.end(1);
387 final int northFences = firstMatcher.end(2) - firstMatcher.start(2);
388 final int spaceX = (to - from - 1) / 9 - 1;
389 final int spaceY = 1;
393 Set<Fence> fences = new HashSet<Fence>();
395 StringBuffer sb = new StringBuffer();
397 for (int y = (spaceY + 1) * 9 - 1; y > 0; y--) {
398 String s = b.readLine();
400 throw new EOFException();
404 if (s.length() < to) {
405 throw new IOException("Too short line: " + s); // NOI18N
407 assertChar(s, from, '|');
408 assertChar(s, to - 1, '|');
410 if (y % (spaceY + 1) == 0) {
411 for (int x = 1; x < 9; x++) {
412 switch (assertChar(s, from + (spaceX + 1) * x, '+', '-', '|')) {
414 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.HORIZONTAL));
417 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.VERTICAL));
427 String line = s.substring(from, to);
428 p = findPlayer(p, line, y, spaceX, Player.Direction.NORTH, -1);
429 q = findPlayer(q, line, y, spaceX, Player.Direction.SOUTH, northFences);
433 String last = b.readLine();
435 throw new EOFException();
437 Matcher lastMatcher = northSouthPattern.matcher(last);
438 if (!lastMatcher.find()) {
439 throw new IOException("Unrecognized last line: " + last);
442 List<Player> arr = new ArrayList<Player>(2);
444 int southFences = lastMatcher.end(2) - lastMatcher.start(2);
445 arr.add(new Player(p.getXInternal(), p.getYInternal(), southFences, p.endDirection));
447 int turn = "*".equals(lastMatcher.group(3)) ? 0 : 1; // NOI18N
448 return new Board(turn, arr, fences);
453 /** Writes the board to the provided writer. <b>P</b> denotes position
454 * of the first player and <b>Q</b> of the second. Number of remaining
455 * fences of each player are shown in left bottom and left top corner
456 * as appropriate number of <b>|||</b> - one <b>|</b> per fence. The
457 * player that is supposed to move in this turn has <b>*</b> right after
458 * the set of its fences.
465 +|||||------------------------------+
467 8--| + + + + + + + + |--8
469 7--| + | + +-------+-------+ |--7
471 6--|-------+-------|-------+-------+ |--6
473 5--| + + + + + + + + |--5
475 4--| + + + | + + +-------|--4
477 3--| + + + +-------+ + + |--3
479 2--| + + + + + + + + |--2
481 1--| + + + + + | + + |--1
483 +|||*-------------------------------+
489 * @param w writer to write the board to
490 * @exception IOException if communiction with writer fails
492 public void write (Writer w) throws IOException {
496 private void northSouthSign(int width, char sign, Writer w) throws IOException {
497 int middle = width / 2;
498 for (int x = 0; x < width; x++) {
500 if (x == middle - 1) {
506 if (x == middle + 1) {
511 w.write(System.getProperty("line.separator")); // NOI18N
514 private void subColumnLine(int width, int spaceX, Writer w) throws IOException {
515 for (int x = 0; x < width - 1; x++) {
516 if (x % (spaceX + 1) == 0 && x > 0) {
524 /** This will print the board with provided spacing.
525 * This is example of 3:1 spacing:
531 * and this 4:2 spacing:
539 private void write (Writer w, int spaceX, int spaceY) throws IOException {
540 int width = spaceX * 9 + 10;
541 int height = spaceY * 9 + 10;
542 char[][] desk = new char[height][];
543 for (int i = 0; i < height; i++) {
544 desk[i] = new char[width];
545 for (int j = 0; j < width; j++) {
546 if (i % (spaceY + 1) == 0 && j % (spaceX + 1) == 0) {
553 desk[i][width - 1] = '|';
555 for (int i = 1; i < width - 1; i++) {
557 desk[height -1][i] = '-';
560 desk[0][width - 1] = '+';
561 desk[height - 1][0] = '+';
562 desk[height - 1][width - 1] = '+';
565 for (Player p : players) {
566 int px = p.getXInternal() / 2;
567 int py = p.getYInternal() / 2;
569 [1 + py * (spaceY + 1) + spaceY / 2]
570 [1 + px * (spaceX + 1) + spaceX / 2] = p.endDirection.player;
571 paintLeftFences(desk, p.endDirection, p.getFences(), p.equals(getCurrentPlayer()));
575 for (Fence f : fences) {
576 int fx = (f.getX() / 2 + 1) * (spaceX + 1);
577 int fy = (f.getY() / 2 + 1) * (spaceY + 1);
578 switch (f.getOrientation()) {
580 for (int i = -spaceX; i <= spaceX; i++) {
581 desk[fy][fx + i] = '-';
585 for (int i = -spaceY; i <= spaceY; i++) {
586 desk[fy + i][fx] = '|';
590 throw new IllegalStateException ("Unknown orientation: " + f.getOrientation ()); // NOI18N
594 northSouthSign(width, 'N', w);
595 w.write(System.getProperty("line.separator")); // NOI18N
597 columnLine(width, spaceX, w);
598 w.write(System.getProperty("line.separator")); // NOI18N
600 subColumnLine(width, spaceX, w);
601 w.write(System.getProperty("line.separator")); // NOI18N
603 for (int y = height - 1; y >= 0; y--) {
604 if (y == height / 2) {
609 boolean number = y % (spaceY + 1) == 0 && y > 0 && y < height - 1;
612 w.write(Integer.toString(cnt));
617 for (int x = 0; x < width; x++) {
622 w.write(Integer.toString(cnt));
626 if (y == height / 2) {
629 w.write(System.getProperty("line.separator")); // NOI18N
632 subColumnLine(width, spaceX, w);
633 w.write(System.getProperty("line.separator")); // NOI18N
635 columnLine(width, spaceX, w);
636 w.write(System.getProperty("line.separator")); // NOI18N
637 w.write(System.getProperty("line.separator")); // NOI18N
639 northSouthSign(width, 'S', w);
643 private void paintLeftFences(char[][] desk, Direction endDirection, int fences, boolean currentTurn) {
644 assert fences >= 0 && fences <= 10 : "Players: " + players;
645 switch (endDirection) {
647 for (int i = 0; i < fences; i++) {
648 desk[desk.length - 1][i + 1] = '|';
651 desk[desk.length - 1][fences + 1] = '*';
656 for (int i = 0; i < fences; i++) {
657 desk[0][i + 1] = '|';
660 desk[0][fences + 1] = '*';
676 public int hashCode () {
677 return occupied.hashCode ();
681 public boolean equals (Object o) {
682 if (o instanceof Board) {
684 return occupied.equals (b.occupied) && players.equals (b.players);
689 /** Converts the board into string representation. For more information
690 * about the format see {@link #write(java.io.Writer)}. To read the
691 * string back use {@link #valueOf(java.lang.String)}.
693 * @return string representing the board
696 public String toString() {
697 StringWriter w = new StringWriter();
700 } catch (IOException ex) {
701 return ex.toString();
708 // Validation methods
711 /** Computes new position of a player and checks whether there is no
712 * fence between the old and new.
714 private Player newPosition (Player old, Player.Direction direction) throws IllegalPositionException {
715 return newPosition (old, direction, occupied);
719 private static Player newPosition (Player old, Player.Direction direction, BitSet occupied) throws IllegalPositionException {
742 default: throw new IllegalStateException ("Unknown direction: " + direction); // NOI18N
745 if (nx < 0 || nx > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
746 if (ny < 0 || ny > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
748 int fenceIndex = toIndex (fx, fy);
749 if (occupied.get (fenceIndex)) {
750 throw new IllegalPositionException ("You cannot go over fences"); // NOI18N
753 return new Player (nx, ny, old.getFences (), old.endDirection);
756 /** @param position the current position of the player
757 * @param endDir the side the player wants to reach
758 * @param fences bits set to 1 when fences are placed
759 * @param reached bits on squares that were already reached (modified during run)
760 * @return true if the end line can be reached
762 private static boolean accessibleFinalLine (Player position, Player.Direction endDir, BitSet fences, BitSet reached) {
763 int index = toIndex (position);
764 if (reached.get (index)) {
765 // already visited without success
771 if (position.getYInternal() == 8) return true;
774 if (position.getYInternal() == 0) return true;
777 if (position.getXInternal() == 0) return true;
780 if (position.getXInternal() == 8) return true;
783 throw new IllegalStateException ("Wrong direction: " + endDir); // NOI18N
788 for (Player.Direction oneDirection : Player.Direction.values ()) {
790 if (accessibleFinalLine (newPosition (position, oneDirection, fences), endDir, fences, reached)) {
793 } catch (IllegalPositionException ex) {
801 /** Computes mask of the occupried bits.
803 private static BitSet computeOccupied (
804 Collection<Player> players, Collection<Fence> fences
805 ) throws IllegalPositionException {
806 BitSet occupied = new BitSet (20 * 30); // TBD this is just an upper guess
808 for (Player p : players) {
809 if (p.getXInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
810 if (p.getYInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
812 int index = toIndex (p);
813 if (occupied.get (index)) {
814 throw new IllegalPositionException ("There cannot be two players at " + p); // NOI18N
816 occupied.set (index);
819 for (Fence f : fences) {
821 for (int i = -1; i <= 1; i++) {
822 int index = toIndex (f, i);
823 if (index < 0 || index > occupied.size ()) {
824 throw new IllegalPositionException ("Wrong fence position: " + f); // NOI18N
826 if (occupied.get (index)) {
827 throw new IllegalPositionException ("Fence collition: " + f); // NOI18N
830 occupied.set (index);
838 /** Converts twodimensional coordinates of player to one dimensional index.
840 private static int toIndex (Player p) {
841 return toIndex (p.getXInternal(), p.getYInternal());
844 /** Converts twodimensional coordinates of fence to one dimensional index.
846 * @param whichPart (-1, 0, 1)
848 private static int toIndex (Fence f, int whichPart) {
852 switch (f.getOrientation ()) {
853 case HORIZONTAL: x += whichPart; break;
854 case VERTICAL: y += whichPart; break;
855 default: throw new IllegalStateException ("Wrong orientation: " + f.getOrientation ()); // NOI18N
858 return toIndex (x, y);
861 /** Diagonal conversion of two positive integers to one integer.
870 private static int toIndex (int x, int y) {
872 int baseOnY0 = max * (max + 1) / 2;