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