Showing x when a move to certain position is impossible, showing o when it is fine. Adding Board.findMove method to keep the allowed move logic.
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.Writer;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.BitSet;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashSet;
41 import java.util.List;
43 import java.util.TreeSet;
44 import java.util.logging.Level;
45 import java.util.logging.Logger;
46 import java.util.regex.Matcher;
47 import java.util.regex.Pattern;
50 * Represents a snapshot of the game position,
51 * including all the placed and not-yet placed fences and player positions.
52 * It it can print itself to stream in
53 * <a href="http://www.gamerz.net/pbmserv/quoridor.html">ascii art format<a/>
54 * and can it read back. The class is immutable
55 * but it contains {@link #apply(cz.xelfi.quoridor.Move)}
56 * that produce new {@link Board} with position created after
57 * applying some {@link Move}. Use:
59 * Board whiteOnTurn = Board.empty();
60 * Board blackOnTurn = whiteOnTurn.apply(Move.NORTH);
61 * Board whiteAgain = blackOnTurn.apply(Move.SOUTH);
62 * Board withOneFence = whiteAgain.apply(Move.fence('D', 7));
65 * @author Jaroslav Tulach
67 public final class Board {
69 private final Player winner;
71 private final List<Player> players;
72 /** fences placed on board */
73 private final Set<Fence> fences;
74 /** occurpied bits (coordinates encoded by toIndex methods)
77 +-----------------------------------+
95 +-----------------------------------+
96 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
99 * even indexes == position of the pawns
100 * odd indexes == centers of fences
101 * even x odd == side of a fence
102 * odd x even == side of a fence
104 private final BitSet occupied;
105 /** which player's turn is next? */
106 private final int turn;
109 * Creates a new instance of Board
111 private Board (int x1, int y1, int f1, int x2, int y2, int f2) {
112 this.players = Collections.unmodifiableList (Arrays.asList (new Player[] {
113 new Player (x1, y1, f1, Player.Direction.NORTH),
114 new Player (x2, y2, f2, Player.Direction.SOUTH),
116 this.fences = Collections.emptySet ();
118 this.occupied = computeOccupied (players, fences);
119 } catch (IllegalPositionException ex) {
120 throw new IllegalStateException (ex.getMessage ());
126 /** Copy constructor that provides players and fences.
128 private Board (int turn, List<Player> players, Set<Fence> fences)
129 throws IllegalPositionException {
130 this.players = Collections.unmodifiableList (players);
131 this.fences = Collections.unmodifiableSet (fences);
132 this.occupied = computeOccupied (players, fences);
134 for (Player p : players) {
135 BitSet bs = new BitSet(17 * 17);
136 if (!accessibleFinalLine (p, p.endDirection, occupied, bs)) {
137 throw new IllegalPositionException ("Player " + p + " cannot reach " + p.endDirection + " side"); // NOI18N
140 this.turn = turn % players.size();
144 /** Copy constructor for resigning the game */
145 private Board(Board previous, int winner) {
146 this.players = previous.players;
147 this.turn = winner % players.size();
148 this.fences = previous.fences;
149 this.occupied = previous.occupied;
150 this.winner = players.get(this.turn);
153 /** Returns empty board with default starting position.
154 * @return board with two pawns.
156 public static Board empty () {
157 return new Board (8, 0, 10, 8, 16, 10);
160 /** Returns players in the game.
161 * @return player object
163 public List<Player> getPlayers () {
167 /** The fences currently on board.
169 * @return immutable set of Fences
171 public Set<Fence> getFences () {
175 /** The player that is supposed to play now.
176 * @return the player to do next move, null if the game is over
178 public Player getCurrentPlayer() {
179 if (getWinner() != null) {
182 return players.get(turn);
185 /** The play who wins on current board.
187 * @return the winning player or <code>null</code>
189 public Player getWinner() {
190 if (winner != null) {
193 for (Player p : players) {
194 if (p.endDirection.reached(p)) {
201 /** Applies given move to current board.
203 * @param move move creates by one of the factory methods or fields of the {@link Move} class
204 * @return new board derived from this one
206 * @throws cz.xelfi.quoridor.IllegalPositionException throws exception if the move is illegal
208 public Board apply(Move move) throws IllegalPositionException {
209 if (getWinner() != null) {
210 throw new IllegalPositionException("Game finished!"); // NOI18N
212 return apply(move, getCurrentPlayer());
215 private Board apply(Move move, Player p) throws IllegalPositionException {
216 if (move.direction != null) {
217 return move(p, move.direction);
219 if (move.fence != null) {
220 return fence(p, move.fence);
222 return new Board(this, turn + 1);
227 /** Is there a move that would take the player onto given position while
228 * respecting situation on board?
230 * @param p the player to try to move
231 * @param column desired x-coordinate. Between 0-8. See {@link Player#getColumn()}.
232 * @param row desired y-coordinate. Between 0-8. See {@link Player#getRow()}.
233 * @return the move that can be {@link #apply applied} to the position and
234 * that would move the player p into desired position or null, if such
235 * move does not exist
238 public Move findMove(Player p, int column, int row) {
239 int idx = getPlayers().indexOf(p);
243 for (Move m : Move.allMovements()) {
247 } catch (IllegalPositionException ex) {
251 b.getPlayers().get(idx).getColumn() == column &&
252 b.getPlayers().get(idx).getRow() == row
260 /** Can the move be applied to current board position?
262 * @param move the move to apply
263 * @return true if one can call {@link #apply} method without getting
266 public boolean isApplicable(Move move) {
268 // trivial implementation is enough for now
271 } catch (IllegalPositionException ex) {
276 /** Moves the player in given direction. The direction usually
277 * is one of Player.Direction constants, but in case the move
278 * is a jump over another players pawn it can be followed by
279 * another (usually, if there is no fence the same) direction.
281 * @param player the player to move
282 * @param where one or two directions saying where
283 * @return the new board
284 * @exception IllegalPositionException if the move is not possible
286 final Board move (Player player, Player.Direction... where) throws IllegalPositionException {
287 if (where.length != 1 && where.length != 2) {
288 throw new IllegalPositionException ("Move over one or two Directions"); // NOI18N
291 int index = players.indexOf (player);
292 Player[] arr = players.toArray (new Player[0]);
294 Player oneStep = newPosition (player, where[0]);
296 if (where.length == 1) {
297 arr[index] = oneStep;
298 return new Board(turn + 1, Arrays.asList (arr), fences);
301 // straight jump over
302 for (Player p : players) {
303 if (p.getXInternal () == oneStep.getXInternal () && p.getYInternal() == oneStep.getYInternal ()) {
304 // ok, we are jumping over this one
305 GO_ON: if (where[0] != where[1]) {
306 // first of all ensure that we cannot go straight
308 newPosition (oneStep, where[0]);
309 } catch (IllegalPositionException ex) {
313 throw new IllegalPositionException ("You have to jump straight if there is no wall"); // NOI18N
315 arr[index] = newPosition (oneStep, where[1]);
316 if (arr[index].equals(player)) {
317 throw new IllegalPositionException("You cannot jump forth and back"); // NOI18N
319 return new Board (turn + 1, Arrays.asList (arr), fences);
322 throw new IllegalPositionException ("Cannot use multi direction when there is not oponent pawn"); // NOI18N
325 final Board fence (Player player, char x, int y, Fence.Orientation orientation) throws IllegalPositionException {
326 return fence(player, new Fence ((x - 'A') * 2 + 1, y * 2 - 1, orientation));
329 private void columnLine(int width, int spaceX, Writer w) throws IOException {
331 for (int x = 0; x < width - 1; x++) {
332 if (x % (spaceX + 1) == 0 && x > 0) {
334 ch = (char) (ch + 1);
341 private Board fence(Player player, Fence fence) throws IllegalPositionException {
342 if (player.getFences () == 0) {
343 throw new IllegalPositionException ("Not enough fences: " + player); // NOI18N
346 int index = players.indexOf (player);
347 Player[] arr = players.toArray (new Player[0]);
348 arr[index] = new Player (arr[index].getXInternal(), arr[index].getYInternal(), arr[index].getFences() - 1, arr[index].endDirection);
350 HashSet<Fence> fen = new HashSet<Fence> (this.fences);
351 if (!fen.add (fence)) {
352 throw new IllegalPositionException ("Fence already prsent: " + fence); // NOI18N
355 return new Board (turn + 1, Arrays.asList (arr), fen);
362 private static final Pattern northSouthPattern = Pattern.compile("(\\+(\\|*)(\\*)?-+\\+)");
364 /** Reads the board from a reader. Opposite operation to {@link #write(java.io.Writer)}.
366 * @param r the reader
367 * @return the read board
368 * @throws IOException if I/O error occurs
369 * @throws IllegalPositionException if the reader does not contain description
372 public static Board read(Reader r) throws IOException, IllegalPositionException {
373 BufferedReader b = new BufferedReader(r);
375 String s = b.readLine();
377 throw new IOException("No board found!");
379 Matcher m = northSouthPattern.matcher(s);
381 return readFromBetween(b, m);
386 /** Translates the string into board, if possible. String created by
387 * use of {@link #toString()} is accepted, more information about the
388 * format is avaliable in the description of {@link #write(java.io.Writer)}
391 * @param board string to analyze
392 * @return board object, if the string can be read
393 * @throws IllegalPositionException if the string does not represent the board
395 public static Board valueOf(String board) {
396 return new Board(board);
399 private static int assertChar(String s, int pos, char... ch) throws IOException {
400 if (s.length() >= pos) {
401 for (int i = 0; i < ch.length; i++) {
402 if (ch[i] == s.charAt(pos)) {
407 throw new IOException("Not found " + ch[0] + " at " + pos + " in" + s);
410 private static Player findPlayer(
411 Player previous, String line, int y, int spaceX, Player.Direction dir, int fences
413 int index = line.indexOf(dir.player);
417 int x = (index - 1) / (spaceX + 1) * 2;
418 return new Player(x, y - 1, fences, dir);
421 private static Board readFromBetween(BufferedReader b, Matcher firstMatcher)
422 throws IOException, IllegalPositionException {
423 final int from = firstMatcher.start(1);
424 final int to = firstMatcher.end(1);
425 final int northFences = firstMatcher.end(2) - firstMatcher.start(2);
426 final int spaceX = (to - from - 1) / 9 - 1;
427 final int spaceY = 1;
431 Set<Fence> fences = new HashSet<Fence>();
433 StringBuffer sb = new StringBuffer();
435 for (int y = (spaceY + 1) * 9 - 1; y > 0; y--) {
436 String s = b.readLine();
438 throw new EOFException();
442 if (s.length() < to) {
443 throw new IOException("Too short line: " + s); // NOI18N
445 assertChar(s, from, '|');
446 assertChar(s, to - 1, '|');
448 if (y % (spaceY + 1) == 0) {
449 for (int x = 1; x < 9; x++) {
450 switch (assertChar(s, from + (spaceX + 1) * x, '+', '-', '|')) {
452 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.HORIZONTAL));
455 fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.VERTICAL));
465 String line = s.substring(from, to);
466 p = findPlayer(p, line, y, spaceX, Player.Direction.NORTH, -1);
467 q = findPlayer(q, line, y, spaceX, Player.Direction.SOUTH, northFences);
471 String last = b.readLine();
473 throw new EOFException();
475 Matcher lastMatcher = northSouthPattern.matcher(last);
476 if (!lastMatcher.find()) {
477 throw new IOException("Unrecognized last line: " + last);
480 List<Player> arr = new ArrayList<Player>(2);
482 int southFences = lastMatcher.end(2) - lastMatcher.start(2);
483 arr.add(new Player(p.getXInternal(), p.getYInternal(), southFences, p.endDirection));
485 int turn = "*".equals(lastMatcher.group(3)) ? 0 : 1; // NOI18N
486 return new Board(turn, arr, fences);
491 /** Writes the board to the provided writer. <b>P</b> denotes position
492 * of the first player and <b>Q</b> of the second. Number of remaining
493 * fences of each player are shown in left bottom and left top corner
494 * as appropriate number of <b>|||</b> - one <b>|</b> per fence. The
495 * player that is supposed to move in this turn has <b>*</b> right after
496 * the set of its fences.
503 +|||||------------------------------+
505 8--| + + + + + + + + |--8
507 7--| + | + +-------+-------+ |--7
509 6--|-------+-------|-------+-------+ |--6
511 5--| + + + + + + + + |--5
513 4--| + + + | + + +-------|--4
515 3--| + + + +-------+ + + |--3
517 2--| + + + + + + + + |--2
519 1--| + + + + + | + + |--1
521 +|||*-------------------------------+
527 * @param w writer to write the board to
528 * @exception IOException if communiction with writer fails
530 public void write (Writer w) throws IOException {
534 private void northSouthSign(int width, char sign, Writer w) throws IOException {
535 int middle = width / 2;
536 for (int x = 0; x < width; x++) {
538 if (x == middle - 1) {
544 if (x == middle + 1) {
549 w.write(System.getProperty("line.separator")); // NOI18N
552 private void subColumnLine(int width, int spaceX, Writer w) throws IOException {
553 for (int x = 0; x < width - 1; x++) {
554 if (x % (spaceX + 1) == 0 && x > 0) {
562 /** This will print the board with provided spacing.
563 * This is example of 3:1 spacing:
569 * and this 4:2 spacing:
577 private void write (Writer w, int spaceX, int spaceY) throws IOException {
578 int width = spaceX * 9 + 10;
579 int height = spaceY * 9 + 10;
580 char[][] desk = new char[height][];
581 for (int i = 0; i < height; i++) {
582 desk[i] = new char[width];
583 for (int j = 0; j < width; j++) {
584 if (i % (spaceY + 1) == 0 && j % (spaceX + 1) == 0) {
591 desk[i][width - 1] = '|';
593 for (int i = 1; i < width - 1; i++) {
595 desk[height -1][i] = '-';
598 desk[0][width - 1] = '+';
599 desk[height - 1][0] = '+';
600 desk[height - 1][width - 1] = '+';
603 for (Player p : players) {
604 int px = p.getXInternal() / 2;
605 int py = p.getYInternal() / 2;
607 [1 + py * (spaceY + 1) + spaceY / 2]
608 [1 + px * (spaceX + 1) + spaceX / 2] = p.endDirection.player;
609 paintLeftFences(desk, p.endDirection, p.getFences(), p.equals(getCurrentPlayer()));
613 for (Fence f : fences) {
614 int fx = (f.getX() / 2 + 1) * (spaceX + 1);
615 int fy = (f.getY() / 2 + 1) * (spaceY + 1);
616 switch (f.getOrientation()) {
618 for (int i = -spaceX; i <= spaceX; i++) {
619 desk[fy][fx + i] = '-';
623 for (int i = -spaceY; i <= spaceY; i++) {
624 desk[fy + i][fx] = '|';
628 throw new IllegalStateException ("Unknown orientation: " + f.getOrientation ()); // NOI18N
632 northSouthSign(width, 'N', w);
633 w.write(System.getProperty("line.separator")); // NOI18N
635 columnLine(width, spaceX, w);
636 w.write(System.getProperty("line.separator")); // NOI18N
638 subColumnLine(width, spaceX, w);
639 w.write(System.getProperty("line.separator")); // NOI18N
641 for (int y = height - 1; y >= 0; y--) {
642 if (y == height / 2) {
647 boolean number = y % (spaceY + 1) == 0 && y > 0 && y < height - 1;
650 w.write(Integer.toString(cnt));
655 for (int x = 0; x < width; x++) {
660 w.write(Integer.toString(cnt));
664 if (y == height / 2) {
667 w.write(System.getProperty("line.separator")); // NOI18N
670 subColumnLine(width, spaceX, w);
671 w.write(System.getProperty("line.separator")); // NOI18N
673 columnLine(width, spaceX, w);
674 w.write(System.getProperty("line.separator")); // NOI18N
675 w.write(System.getProperty("line.separator")); // NOI18N
677 northSouthSign(width, 'S', w);
681 private void paintLeftFences(char[][] desk, Direction endDirection, int fences, boolean currentTurn) {
682 assert fences >= 0 && fences <= 10 : "Players: " + players;
683 switch (endDirection) {
685 for (int i = 0; i < fences; i++) {
686 desk[desk.length - 1][i + 1] = '|';
689 desk[desk.length - 1][fences + 1] = '*';
694 for (int i = 0; i < fences; i++) {
695 desk[0][i + 1] = '|';
698 desk[0][fences + 1] = '*';
714 public int hashCode () {
715 return occupied.hashCode ();
719 public boolean equals (Object o) {
720 if (o instanceof Board) {
722 return occupied.equals (b.occupied) && players.equals (b.players);
727 /** Converts the board into string representation. For more information
728 * about the format see {@link #write(java.io.Writer)}. To read the
729 * string back use {@link #valueOf(java.lang.String)}.
731 * @return string representing the board
734 public String toString() {
739 // Validation methods
742 /** Computes new position of a player and checks whether there is no
743 * fence between the old and new.
745 private Player newPosition (Player old, Player.Direction direction) throws IllegalPositionException {
746 return newPosition (old, direction, occupied);
750 private static Player newPosition (Player old, Player.Direction direction, BitSet occupied) throws IllegalPositionException {
773 default: throw new IllegalStateException ("Unknown direction: " + direction); // NOI18N
776 if (nx < 0 || nx > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
777 if (ny < 0 || ny > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
779 int fenceIndex = toIndex (fx, fy);
780 if (occupied.get (fenceIndex)) {
781 throw new IllegalPositionException ("You cannot go over fences"); // NOI18N
784 return new Player (nx, ny, old.getFences (), old.endDirection);
787 /** @param position the current position of the player
788 * @param endDir the side the player wants to reach
789 * @param fences bits set to 1 when fences are placed
790 * @param reached bits on squares that were already reached (modified during run)
791 * @return true if the end line can be reached
793 private static boolean accessibleFinalLine (Player position, Player.Direction endDir, BitSet fences, BitSet reached) {
794 int index = toIndex (position);
795 if (reached.get (index)) {
796 // already visited without success
800 if (endDir.reached(position)) {
806 for (Player.Direction oneDirection : Player.Direction.values ()) {
808 if (accessibleFinalLine (newPosition (position, oneDirection, fences), endDir, fences, reached)) {
811 } catch (IllegalPositionException ex) {
819 /** Computes mask of the occupried bits.
821 private static BitSet computeOccupied (
822 Collection<Player> players, Collection<Fence> fences
823 ) throws IllegalPositionException {
824 BitSet occupied = new BitSet (17 * 17);
826 for (Player p : players) {
827 if (p.getXInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
828 if (p.getYInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
830 int index = toIndex (p);
831 if (occupied.get (index)) {
832 throw new IllegalPositionException ("There cannot be two players at " + p); // NOI18N
834 occupied.set (index);
837 for (Fence f : fences) {
839 for (int i = -1; i <= 1; i++) {
840 int index = toIndex (f, i);
841 if (index < 0 || index > occupied.size ()) {
842 throw new IllegalPositionException ("Wrong fence position: " + f); // NOI18N
844 if (occupied.get (index)) {
845 throw new IllegalPositionException ("Fence collition: " + f); // NOI18N
848 occupied.set (index);
856 /** Converts twodimensional coordinates of player to one dimensional index.
858 private static int toIndex (Player p) {
859 return toIndex (p.getXInternal(), p.getYInternal());
862 /** Converts twodimensional coordinates of fence to one dimensional index.
864 * @param whichPart (-1, 0, 1)
866 private static int toIndex (Fence f, int whichPart) {
870 switch (f.getOrientation ()) {
871 case HORIZONTAL: x += whichPart; break;
872 case VERTICAL: y += whichPart; break;
873 default: throw new IllegalStateException ("Wrong orientation: " + f.getOrientation ()); // NOI18N
876 return toIndex (x, y);
879 /** Diagonal conversion of two positive integers to one integer.
888 private static int toIndex (int x, int y) {
889 assert x >= 0 && x < 17;
890 assert y >= 0 && y < 17;
894 Board(String hashCode) throws IllegalStateException{
895 this.fences = new HashSet<Fence>();
896 if((hashCode != null) && (hashCode.length() > 6)){
897 char[]c = hashCode.toCharArray();
898 this.players = Collections.unmodifiableList (Arrays.asList (new Player[] {
899 new Player ((c[0]-'A')*2, (c[1]-'0')*2, c[2]-'a', Player.Direction.NORTH),
900 new Player ((c[3]-'A')*2, (c[4]-'0')*2, c[5]-'a', Player.Direction.SOUTH),
910 this.winner = this.players.get(0);
913 this.winner = this.players.get(1);
918 for(int i=7; i<c.length;i+=2){
919 int f = Integer.parseInt(hashCode.substring(i, i+2),16);
920 Fence.Orientation o = Fence.Orientation.HORIZONTAL;
922 o = Fence.Orientation.VERTICAL;
925 fences.add(new Fence((f/8)*2+1, (f%8)*2+1,o));
928 this.players = Collections.unmodifiableList (Arrays.asList (new Player[] {
929 new Player (8,0,10,Player.Direction.NORTH),
930 new Player (8,16,10,Player.Direction.SOUTH),
936 this.occupied = computeOccupied (players, fences);
937 } catch (IllegalPositionException ex) {
938 throw new IllegalStateException (ex.getMessage ());
942 public final String getCode() {
944 StringBuilder sb = new StringBuilder();
945 for(Player p: b.getPlayers()){
946 sb.append((char)(p.getColumn() + 'A'));
947 sb.append((char)(p.getRow() + '0'));
948 sb.append((char)(p.getFences() + 'a'));
950 Player winner = b.getWinner();
952 if(b.players.indexOf(b.getCurrentPlayer())==0)
954 else if(b.players.indexOf(b.getCurrentPlayer())==1)
959 if(b.players.indexOf(winner)==0)
961 else if(b.players.indexOf(winner)==1)
967 TreeSet<Integer> fences = new TreeSet<Integer>();
968 for(Fence f: b.getFences()){
969 int a = (f.getColumn() - 'A')*8 + (f.getRow()-1);
970 if(f.getOrientation().equals(Fence.Orientation.VERTICAL))
977 sb.append(Integer.toHexString(f));
979 return sb.toString();