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