quoridor/src/main/java/cz/xelfi/quoridor/Board.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 22 Sep 2009 23:06:16 +0200
changeset 107 152aedcc45d0
parent 92 de3dd5710a5c
child 178 4b78d4f028b3
permissions -rw-r--r--
Cannot place the same fence twice
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     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]"
    21  *
    22  * Contributor(s):
    23  *
    24  * Portions Copyrighted 2009 Jaroslav Tulach
    25  */
    26 
    27 package cz.xelfi.quoridor;
    28 
    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;
    44 import java.util.Set;
    45 import java.util.regex.Matcher;
    46 import java.util.regex.Pattern;
    47 
    48 /**
    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:
    57  * <pre>
    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));
    62  * </pre>
    63  * 
    64  * @author Jaroslav Tulach
    65  */
    66 public final class Board {
    67     /** winner, if any */
    68     private final Player winner;
    69     /** players */
    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) 
    74                          [N]
    75                
    76         +-----------------------------------+
    77      6  |                                   |          
    78      5  |   +   +   +   +   +   +   +   +   |  
    79      4  |                                   |          
    80      3  |   +   +   +   +   +   +   +   +   |  
    81      2  |                                   |          
    82      1  |   +   +   +   +   +   +   +   +   |  
    83      0  |                                   |
    84      9  |   +   +   +   +   +   +   +   +   |
    85 [W]  8  |                                   |     [E]
    86      7  |   +   +   +   +   +   +   +   +   |
    87      6  |                                   |
    88      5  |   +   +   +   +   +   +   +   +   |
    89      4  |                                   |
    90      3  |   +   +   +   +   +   +   +   +   |
    91      2  |                                   |
    92      1  |   +   +   +   +   +   +   +   +   |
    93      0  |                                   |
    94         +-----------------------------------+
    95           0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
    96                          [S]
    97      
    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
   102      */
   103     private final BitSet occupied;
   104     /** which player's turn is next? */
   105     private final int turn;
   106     
   107     /**
   108      * Creates a new instance of Board 
   109      */
   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),
   114         }));
   115         this.fences = Collections.emptySet ();
   116         try {
   117             this.occupied = computeOccupied (players, fences);
   118         } catch (IllegalPositionException ex) {
   119             throw new IllegalStateException (ex.getMessage ());
   120         }
   121         this.turn = 0;
   122         this.winner = null;
   123     }
   124     
   125     /** Copy constructor that provides players and fences.
   126      */
   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);
   132 
   133         for (Player p : players) {
   134             BitSet bs = new BitSet(17 * 17);
   135             if (!accessibleFinalLine (p, p.endDirection, occupied, bs)) {
   136                 throw new IllegalPositionException ("Player " + p + " cannot reach " + p.endDirection + " side"); // NOI18N
   137             }
   138         }
   139         this.turn = turn % players.size();
   140         this.winner = null;
   141     }
   142 
   143     /** Copy constructor for resigning the game */
   144     private Board(Board previous, int winner) {
   145         this.players = previous.players;
   146         this.turn = winner % players.size();
   147         this.fences = previous.fences;
   148         this.occupied = previous.occupied;
   149         this.winner = players.get(this.turn);
   150     }
   151     
   152     /** Returns empty board with default starting position.
   153      * @return board with two pawns.
   154      */
   155     public static Board empty () {
   156         return new Board (8, 0, 10, 8, 16, 10);
   157     }
   158     
   159     /** Returns players in the game.
   160      * @return player object
   161      */
   162     public List<Player> getPlayers () {
   163         return players;
   164     }
   165     
   166     /** The fences currently on board. 
   167      * 
   168      * @return immutable set of Fences
   169      */
   170     public Set<Fence> getFences () {
   171         return fences;
   172     }
   173 
   174     /** The player that is supposed to play now.
   175      * @return the player to do next move, null if the game is over
   176      */
   177     public Player getCurrentPlayer() {
   178         if (getWinner() != null) {
   179             return null;
   180         }
   181         return players.get(turn);
   182     }
   183 
   184     /** The play who wins on current board.
   185      *
   186      * @return the winning player or <code>null</code>
   187      */
   188     public Player getWinner() {
   189         if (winner != null) {
   190             return winner;
   191         }
   192         for (Player p : players) {
   193             if (p.endDirection.reached(p)) {
   194                 return p;
   195             }
   196         }
   197         return null;
   198     }
   199 
   200     /** Applies given move to current board.
   201      *
   202      * @param move move creates by one of the factory methods or fields of the {@link Move} class
   203      * @return new board derived from this one
   204      *
   205      * @throws cz.xelfi.quoridor.IllegalPositionException throws exception if the move is illegal
   206      */
   207     public Board apply(Move move) throws IllegalPositionException {
   208         if (getWinner() != null) {
   209             throw new IllegalPositionException("Game finished!"); // NOI18N
   210         }
   211 
   212         if (move.direction != null) {
   213             return move(getCurrentPlayer(), move.direction);
   214         } else {
   215             if (move.fence != null) {
   216                 return fence(getCurrentPlayer(), move.fence);
   217             } else {
   218                 return new Board(this, turn + 1);
   219             }
   220         }
   221     }
   222 
   223     /** Can the move be applied to current board position?
   224      * 
   225      * @param move the move to apply
   226      * @return true if one can call {@link #apply} method without getting 
   227      *   an exception
   228      */
   229     public boolean isApplicable(Move move) {
   230         try {
   231             // trivial implementation is enough for now
   232             apply(move);
   233             return true;
   234         } catch (IllegalPositionException ex) {
   235             return false;
   236         }
   237     }
   238     
   239     /** Moves the player in given direction. The direction usually
   240      * is one of Player.Direction constants, but in case the move
   241      * is a jump over another players pawn it can be followed by
   242      * another (usually, if there is no fence the same) direction.
   243      *
   244      * @param player the player to move
   245      * @param where one or two directions saying where
   246      * @return the new board
   247      * @exception IllegalPositionException if the move is not possible
   248      */
   249     final Board move (Player player, Player.Direction... where) throws IllegalPositionException {
   250         if (where.length != 1 && where.length != 2) {
   251             throw new IllegalPositionException ("Move over one or two Directions"); // NOI18N
   252         }
   253         
   254         int index = players.indexOf (player);
   255         Player[] arr = players.toArray (new Player[0]);
   256 
   257         Player oneStep = newPosition (player, where[0]);
   258         
   259         if (where.length == 1) {
   260             arr[index] = oneStep;
   261             return new Board(turn + 1, Arrays.asList (arr), fences);
   262         }
   263 
   264         // straight jump over
   265         for (Player p : players) {
   266             if (p.getXInternal () == oneStep.getXInternal () && p.getYInternal() == oneStep.getYInternal ()) {
   267                 // ok, we are jumping over this one
   268                 GO_ON: if (where[0] != where[1]) {
   269                     // first of all ensure that we cannot go straight
   270                     try {
   271                         newPosition (oneStep, where[0]);
   272                     } catch (IllegalPositionException ex) {
   273                         // ok
   274                         break GO_ON;
   275                     }
   276                     throw new IllegalPositionException ("You have to jump straight if there is no wall"); // NOI18N
   277                 }
   278                 arr[index] = newPosition (oneStep, where[1]);
   279                 return new Board (turn + 1, Arrays.asList (arr), fences);
   280             }
   281         }
   282         throw new IllegalPositionException ("Cannot use multi direction when there is not oponent pawn"); // NOI18N
   283     }
   284     
   285     final Board fence (Player player, char x, int y, Fence.Orientation orientation) throws IllegalPositionException {
   286         return fence(player, new Fence ((x - 'A') * 2 + 1, y * 2 - 1, orientation));
   287     }
   288 
   289     private void columnLine(int width, int spaceX, Writer w) throws IOException {
   290         char ch = 'A';
   291         for (int x = 0; x < width - 1; x++) {
   292             if (x % (spaceX + 1) == 0 && x > 0) {
   293                 w.write(ch);
   294                 ch = (char) (ch + 1);
   295             } else {
   296                 w.write(' ');
   297             }
   298         }
   299     }
   300 
   301     private Board fence(Player player, Fence fence) throws IllegalPositionException {
   302         if (player.getFences () == 0) {
   303             throw new IllegalPositionException ("Not enough fences: " + player); // NOI18N
   304         }
   305 
   306         int index = players.indexOf (player);
   307         Player[] arr = players.toArray (new Player[0]);
   308         arr[index] = new Player (arr[index].getXInternal(), arr[index].getYInternal(), arr[index].getFences() - 1, arr[index].endDirection);
   309         
   310         HashSet<Fence> fen = new HashSet<Fence> (this.fences);
   311         if (!fen.add (fence)) {
   312             throw new IllegalPositionException ("Fence already prsent: " + fence); // NOI18N
   313         }
   314         
   315         return new Board (turn + 1, Arrays.asList (arr), fen);
   316     }
   317 
   318     //
   319     // Serialization
   320     //
   321 
   322     private static final Pattern northSouthPattern = Pattern.compile("(\\+(\\|*)(\\*)?-+\\+)");
   323 
   324     /** Reads the board from a reader. Opposite operation to {@link #write(java.io.Writer)}.
   325      *
   326      * @param r the reader
   327      * @return the read board
   328      * @throws IOException if I/O error occurs
   329      * @throws IllegalPositionException if the reader does not contain description
   330      *   of the board
   331      */
   332     public static Board read(Reader r) throws IOException, IllegalPositionException {
   333         BufferedReader b = new BufferedReader(r);
   334         for (;;) {
   335             String s = b.readLine();
   336             if (s == null) {
   337                 throw new IOException("No board found!");
   338             }
   339             Matcher m = northSouthPattern.matcher(s);
   340             if (m.find()) {
   341                 return readFromBetween(b, m);
   342             }
   343         }
   344     }
   345 
   346     /** Translates the string into board, if possible. String created by
   347      * use of {@link #toString()} is accepted, more information about the
   348      * format is avaliable in the description of {@link #write(java.io.Writer)}
   349      * method.
   350      *
   351      * @param board string to analyze
   352      * @return board object, if the string can be read
   353      * @throws IllegalPositionException if the string does not represent the board
   354      */
   355     public static Board valueOf(String board) throws IllegalPositionException {
   356         try {
   357             return read(new StringReader(board));
   358         } catch (IOException ex) {
   359             // shall not happen, StringReader does not throw IOException
   360             throw (IllegalPositionException)new IllegalPositionException(ex.getMessage()).initCause(ex);
   361         }
   362     }
   363 
   364     private static int assertChar(String s, int pos, char... ch) throws IOException {
   365         if (s.length() >= pos) {
   366             for (int i = 0; i < ch.length; i++) {
   367                 if (ch[i] == s.charAt(pos)) {
   368                     return i;
   369                 }
   370             }
   371         }
   372         throw new IOException("Not found " + ch[0] + " at " + pos + " in" + s);
   373     }
   374 
   375     private static Player findPlayer(
   376         Player previous, String line, int y, int spaceX, Player.Direction dir, int fences
   377     ) {
   378         int index = line.indexOf(dir.player);
   379         if (index == -1) {
   380             return previous;
   381         }
   382         int x = (index - 1) / (spaceX + 1) * 2;
   383         return new Player(x, y - 1, fences, dir);
   384     }
   385 
   386     private static Board readFromBetween(BufferedReader b, Matcher firstMatcher)
   387     throws IOException, IllegalPositionException {
   388         final int from = firstMatcher.start(1);
   389         final int to = firstMatcher.end(1);
   390         final int northFences = firstMatcher.end(2) - firstMatcher.start(2);
   391         final int spaceX = (to - from - 1) / 9 - 1;
   392         final int spaceY = 1;
   393 
   394         Player p = null;
   395         Player q = null;
   396         Set<Fence> fences = new HashSet<Fence>();
   397 
   398         StringBuffer sb = new StringBuffer();
   399         int row = 7;
   400         for (int y = (spaceY + 1) * 9 - 1; y > 0; y--) {
   401             String s = b.readLine();
   402             if (s == null) {
   403                 throw new EOFException();
   404             }
   405             sb.append(s);
   406             sb.append('\n');
   407             if (s.length() < to) {
   408                 throw new IOException("Too short line: " + s); // NOI18N
   409             }
   410             assertChar(s, from, '|');
   411             assertChar(s, to - 1, '|');
   412 
   413             if (y % (spaceY + 1) == 0) {
   414                 for (int x = 1; x < 9; x++) {
   415                     switch (assertChar(s, from + (spaceX + 1) * x, '+', '-', '|')) {
   416                         case 1:
   417                             fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.HORIZONTAL));
   418                             break;
   419                         case 2:
   420                             fences.add(new Fence(x * 2 - 1, row * 2 + 1, Fence.Orientation.VERTICAL));
   421                             break;
   422                         case 0:
   423                             break;
   424                         default:
   425                             assert false;
   426                     }
   427                 }
   428                 row--;
   429             } else {
   430                 String line = s.substring(from, to);
   431                 p = findPlayer(p, line, y, spaceX, Player.Direction.NORTH, -1);
   432                 q = findPlayer(q, line, y, spaceX, Player.Direction.SOUTH, northFences);
   433             }
   434         }
   435 
   436         String last = b.readLine();
   437         if (last == null) {
   438             throw new EOFException();
   439         }
   440         Matcher lastMatcher = northSouthPattern.matcher(last);
   441         if (!lastMatcher.find()) {
   442             throw new IOException("Unrecognized last line: " + last);
   443         }
   444 
   445         List<Player> arr = new ArrayList<Player>(2);
   446         assert p != null;
   447         int southFences = lastMatcher.end(2) - lastMatcher.start(2);
   448         arr.add(new Player(p.getXInternal(), p.getYInternal(), southFences, p.endDirection));
   449         arr.add(q);
   450         int turn = "*".equals(lastMatcher.group(3)) ? 0 : 1; // NOI18N
   451         return new Board(turn, arr, fences);
   452     }
   453 
   454 
   455     
   456     /** Writes the board to the provided writer. <b>P</b> denotes position
   457      * of the first player and <b>Q</b> of the second. Number of remaining
   458      * fences of each player are shown in left bottom and left top corner
   459      * as appropriate number of <b>|||</b> - one <b>|</b> per fence. The
   460      * player that is supposed to move in this turn has <b>*</b> right after
   461      * the set of its fences.
   462      *
   463      * <pre>
   464                          [N]
   465 
   466             A   B   C   D   E   F   G   H
   467             |   |   |   |   |   |   |   |
   468         +|||||------------------------------+
   469         |                 Q                 |
   470      8--|   +   +   +   +   +   +   +   +   |--8
   471         |       |                           |           
   472      7--|   +   |   +   +-------+-------+   |--7
   473         |       |       |                   |           
   474      6--|-------+-------|-------+-------+   |--6
   475         |               |                   |          
   476      5--|   +   +   +   +   +   +   +   +   |--5
   477 [W]     |               |                   |     [E]
   478      4--|   +   +   +   |   +   +   +-------|--4
   479         |               |                   |
   480      3--|   +   +   +   +-------+   +   +   |--3
   481         |                                   |
   482      2--|   +   +   +   +   +   +   +   +   |--2
   483         |                       |           |
   484      1--|   +   +   +   +   +   |   +   +   |--1
   485         |                 P     |           |
   486         +|||*-------------------------------+
   487             |   |   |   |   |   |   |   |
   488             A   B   C   D   E   F   G   H
   489 
   490                          [S]
   491      </pre>
   492      * @param w writer to write the board to
   493      * @exception IOException if communiction with writer fails
   494      */
   495     public void write (Writer w) throws IOException {
   496         write(w, 3, 1);
   497     }
   498 
   499     private void northSouthSign(int width, char sign, Writer w) throws IOException {
   500         int middle = width / 2;
   501         for (int x = 0; x < width; x++) {
   502             char ch = ' ';
   503             if (x == middle - 1) {
   504                 ch = '[';
   505             }
   506             if (x == middle) {
   507                 ch = sign;
   508             }
   509             if (x == middle + 1) {
   510                 ch = ']';
   511             }
   512             w.write(ch);
   513         }
   514         w.write(System.getProperty("line.separator")); // NOI18N
   515     }
   516 
   517     private void subColumnLine(int width, int spaceX, Writer w) throws IOException {
   518         for (int x = 0; x < width - 1; x++) {
   519             if (x % (spaceX + 1) == 0 && x > 0) {
   520                 w.write('|');
   521             } else {
   522                 w.write(' ');
   523             }
   524         }
   525     }
   526     
   527     /** This will print the board with provided spacing.
   528      * This is example of 3:1 spacing: 
   529      * <pre>
   530      *  +---+
   531      *  |sss|
   532      *  +---+
   533      * </pre>
   534      * and this 4:2 spacing:
   535      * <pre>
   536      *  +----+
   537      *  |ssss|
   538      *  |ssss|
   539      *  +----+
   540      * </pre>
   541      */
   542     private void write (Writer w, int spaceX, int spaceY) throws IOException {
   543         int width = spaceX * 9 + 10;
   544         int height = spaceY * 9 + 10;
   545         char[][] desk = new char[height][];
   546         for (int i = 0; i < height; i++) {
   547             desk[i] = new char[width];
   548             for (int j = 0; j < width; j++) {
   549                 if (i % (spaceY + 1) == 0 && j % (spaceX + 1) == 0) {
   550                     desk[i][j] = '+';
   551                 } else {
   552                     desk[i][j] = ' ';
   553                 }
   554             }
   555             desk[i][0] = '|';
   556             desk[i][width - 1] = '|';
   557         }
   558         for (int i = 1; i < width - 1; i++) {
   559             desk[0][i] = '-';
   560             desk[height -1][i] = '-';
   561         }
   562         desk[0][0] = '+';
   563         desk[0][width - 1] = '+';
   564         desk[height - 1][0] = '+';
   565         desk[height - 1][width - 1] = '+';
   566 
   567         {
   568             for (Player p : players) {
   569                 int px = p.getXInternal() / 2;
   570                 int py = p.getYInternal() / 2;
   571                 desk
   572                     [1 + py * (spaceY + 1) + spaceY / 2]
   573                     [1 + px * (spaceX + 1) + spaceX / 2] = p.endDirection.player;
   574                 paintLeftFences(desk, p.endDirection, p.getFences(), p.equals(getCurrentPlayer()));
   575             }
   576         }
   577         
   578         for (Fence f : fences) {
   579             int fx = (f.getX() / 2 + 1) * (spaceX + 1);
   580             int fy = (f.getY() / 2 + 1) * (spaceY + 1);
   581             switch (f.getOrientation()) {
   582                 case HORIZONTAL:
   583                     for (int i = -spaceX; i <= spaceX; i++) {
   584                         desk[fy][fx + i] = '-';
   585                     }
   586                     break;
   587                 case VERTICAL:
   588                     for (int i = -spaceY; i <= spaceY; i++) {
   589                         desk[fy + i][fx] = '|';
   590                     }
   591                     break;
   592                 default: 
   593                     throw new IllegalStateException ("Unknown orientation: " + f.getOrientation ()); // NOI18N
   594             }
   595         }
   596         w.write("        ");
   597         northSouthSign(width, 'N', w);
   598         w.write(System.getProperty("line.separator")); // NOI18N
   599         w.write("        ");
   600         columnLine(width, spaceX, w);
   601         w.write(System.getProperty("line.separator")); // NOI18N
   602         w.write("        ");
   603         subColumnLine(width, spaceX, w);
   604         w.write(System.getProperty("line.separator")); // NOI18N
   605         int cnt = 9;
   606         for (int y = height - 1; y >= 0; y--) {
   607             if (y == height / 2) {
   608                 w.write("[W]  ");
   609             } else {
   610                 w.write("     ");
   611             }
   612             boolean number = y % (spaceY + 1) == 0 && y > 0 && y < height - 1;
   613             if (number) {
   614                 cnt--;
   615                 w.write(Integer.toString(cnt));
   616                 w.write("--");
   617             } else {
   618                 w.write("   ");
   619             }
   620             for (int x = 0; x < width; x++) {
   621                 w.write(desk[y][x]);
   622             }
   623             if (number) {
   624                 w.write("--");
   625                 w.write(Integer.toString(cnt));
   626             } else {
   627                 w.write("   ");
   628             }
   629             if (y == height / 2) {
   630                 w.write("  [E]");
   631             }
   632             w.write(System.getProperty("line.separator")); // NOI18N
   633         }
   634         w.write("        ");
   635         subColumnLine(width, spaceX, w);
   636         w.write(System.getProperty("line.separator")); // NOI18N
   637         w.write("        ");
   638         columnLine(width, spaceX, w);
   639         w.write(System.getProperty("line.separator")); // NOI18N
   640         w.write(System.getProperty("line.separator")); // NOI18N
   641         w.write("        ");
   642         northSouthSign(width, 'S', w);
   643     }
   644 
   645 
   646     private void paintLeftFences(char[][] desk, Direction endDirection, int fences, boolean currentTurn) {
   647         assert fences >= 0 && fences <= 10 : "Players: " + players;
   648         switch (endDirection) {
   649             case SOUTH: {
   650                 for (int i = 0; i < fences; i++) {
   651                     desk[desk.length - 1][i + 1] = '|';
   652                 }
   653                 if (currentTurn) {
   654                     desk[desk.length - 1][fences + 1] = '*';
   655                 }
   656                 break;
   657             }
   658             case NORTH: {
   659                 for (int i = 0; i < fences; i++) {
   660                     desk[0][i + 1] = '|';
   661                 }
   662                 if (currentTurn) {
   663                     desk[0][fences + 1] = '*';
   664                 }
   665                 break;
   666             }
   667             default:
   668                 assert false;
   669         }
   670     }
   671 
   672 
   673     //
   674     // Standard Methods
   675     // 
   676 
   677     
   678     @Override
   679     public int hashCode () {
   680         return occupied.hashCode ();
   681     }
   682     
   683     @Override
   684     public boolean equals (Object o) {
   685         if (o instanceof Board) {
   686             Board b = (Board)o;
   687             return occupied.equals (b.occupied) && players.equals (b.players);
   688         }
   689         return false;
   690     }
   691 
   692     /** Converts the board into string representation. For more information
   693      * about the format see {@link #write(java.io.Writer)}. To read the
   694      * string back use {@link #valueOf(java.lang.String)}.
   695      *
   696      * @return string representing the board
   697      */
   698     @Override
   699     public String toString() {
   700         StringWriter w = new StringWriter();
   701         try {
   702             write(w);
   703         } catch (IOException ex) {
   704             return ex.toString();
   705         }
   706         return w.toString();
   707     }
   708 
   709     
   710     //
   711     // Validation methods
   712     //
   713 
   714     /** Computes new position of a player and checks whether there is no
   715      * fence between the old and new.
   716      */
   717     private Player newPosition (Player old, Player.Direction direction) throws IllegalPositionException {
   718         return newPosition (old, direction, occupied);
   719     }
   720     
   721     
   722     private static Player newPosition (Player old, Player.Direction direction, BitSet occupied) throws IllegalPositionException {
   723         int nx = old.x;
   724         int ny = old.y;
   725         int fx = old.x;
   726         int fy = old.y;
   727         
   728         switch (direction) {
   729             case NORTH: 
   730                 ny = old.y + 2;
   731                 fy = old.y + 1;
   732                 break;
   733             case SOUTH: 
   734                 ny = old.y - 2; 
   735                 fy = old.y - 1;
   736                 break;
   737             case EAST: 
   738                 nx = old.x + 2; 
   739                 fx = old.x + 1;
   740                 break;
   741             case WEST: 
   742                 nx = old.x - 2; 
   743                 fx = old.x - 1;
   744                 break;
   745             default: throw new IllegalStateException ("Unknown direction: " + direction); // NOI18N
   746         }
   747         
   748         if (nx < 0 || nx > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
   749         if (ny < 0 || ny > 16) throw new IllegalPositionException ("Wrong player position: " + nx + ":" + ny); // NOI18N
   750         
   751         int fenceIndex = toIndex (fx, fy);
   752         if (occupied.get (fenceIndex)) {
   753             throw new IllegalPositionException ("You cannot go over fences"); // NOI18N
   754         }
   755         
   756         return new Player (nx, ny, old.getFences (), old.endDirection);
   757     }
   758     
   759     /** @param position the current position of the player
   760      * @param endDir the side the player wants to reach
   761      * @param fences bits set to 1 when fences are placed
   762      * @param reached bits on squares that were already reached (modified during run)
   763      * @return true if the end line can be reached
   764      */
   765     private static boolean accessibleFinalLine (Player position, Player.Direction endDir, BitSet fences, BitSet reached) {
   766         int index = toIndex (position);
   767         if (reached.get (index)) {
   768             // already visited without success
   769             return false;
   770         }
   771 
   772         if (endDir.reached(position)) {
   773             return true;
   774         }
   775         
   776         reached.set (index);
   777         
   778         for (Player.Direction oneDirection : Player.Direction.values ()) {
   779             try {
   780                 if (accessibleFinalLine (newPosition (position, oneDirection, fences), endDir, fences, reached)) {
   781                     return true;
   782                 }
   783             } catch (IllegalPositionException ex) {
   784                 // ok, try once more
   785             }
   786         }
   787         
   788         return false;
   789     }
   790     
   791     /** Computes mask of the occupried bits.
   792      */
   793     private static BitSet computeOccupied (
   794         Collection<Player> players, Collection<Fence> fences
   795     ) throws IllegalPositionException {
   796         BitSet occupied = new BitSet (17 * 17);
   797         
   798         for (Player p : players) {
   799             if (p.getXInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
   800             if (p.getYInternal() % 2 == 1) throw new IllegalPositionException ("Wrong player position: " + p); // NOI18N
   801             
   802             int index = toIndex (p);
   803             if (occupied.get (index)) {
   804                 throw new IllegalPositionException ("There cannot be two players at " + p); // NOI18N
   805             }
   806             occupied.set (index);
   807         }
   808         
   809         for (Fence f : fences) {
   810             
   811             for (int i = -1; i <= 1; i++) {
   812                 int index = toIndex (f, i);
   813                 if (index < 0 || index > occupied.size ()) {
   814                     throw new IllegalPositionException ("Wrong fence position: " + f); // NOI18N
   815                 }
   816                 if (occupied.get (index)) {
   817                     throw new IllegalPositionException ("Fence collition: " + f); // NOI18N
   818                 }
   819                 
   820                 occupied.set (index);
   821             }
   822             
   823         }
   824         
   825         return occupied;
   826     }
   827 
   828     /** Converts twodimensional coordinates of player to one dimensional index.
   829      */
   830     private static int toIndex (Player p) {
   831         return toIndex (p.getXInternal(), p.getYInternal());
   832     }
   833     
   834     /** Converts twodimensional coordinates of fence to one dimensional index.
   835      * @param f the fence
   836      * @param whichPart (-1, 0, 1) 
   837      */
   838     private static int toIndex (Fence f, int whichPart) {
   839         int x = f.getX ();
   840         int y = f.getY ();
   841         
   842         switch (f.getOrientation ()) {
   843             case HORIZONTAL: x += whichPart; break;
   844             case VERTICAL: y += whichPart; break;
   845             default: throw new IllegalStateException ("Wrong orientation: " + f.getOrientation ()); // NOI18N
   846         }
   847         
   848         return toIndex (x, y);
   849     }
   850     
   851     /** Diagonal conversion of two positive integers to one integer.
   852      * <pre>
   853      * y3 9
   854      * y2 5  8
   855      * y1 2  4  7
   856      * y0 0  1  3  6
   857      *   x0 x1 x2 x3
   858      * </pre>
   859      */
   860     private static int toIndex (int x, int y) {
   861         assert x >= 0 && x < 17;
   862         assert y >= 0 && y < 17;
   863         return 17 * y + x;
   864     }
   865 
   866 }