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