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