001 package rules;
002
003 import java.util.*;
004
005 import core.*;
006
007
008 /**
009 * The board for a game represented as a map from postions to pieces.
010 *
011 * @specfield positions_to_pieces : map // map from postions to pieces.
012 */
013 public class Board
014 {
015 /**
016 * The initial board string for a game.
017 * <pre>
018 * "rnbqkbnr\npppppppp \n \n \n \nPPPPPPPP\nRNBQKBNR\n"
019 * </pre>
020 */
021 public final static String startingBoard =
022 "rnbqkbnr\n" +
023 "pppppppp\n" +
024 " \n" +
025 " \n" +
026 " \n" +
027 " \n" +
028 "PPPPPPPP\n" +
029 "RNBQKBNR\n";
030
031 Piece[][] board;
032
033 public Board(){
034 board = new Piece[8][8]; //XXX shouldn't allow nulls
035 }
036
037 public static final long serialVersionUID = 171717;
038
039 /**
040 * Creates a board from a string representation (see startingBoard for an
041 * example string)
042 *
043 * @param s
044 * String representation of the board.
045 *
046 * @returns board corresponding to the string
047 */
048 public static Board fromString(String s)
049 {
050 Board board = new Board();
051 String[] rows = s.split("\n");
052 for (int i = 0; i < 8; i++)
053 {
054 for (int x = 0; x < 8; x++)
055 {
056 Piece p = PieceFactory.pieceFromChar(rows[i].charAt(x));
057 board.put(Position.get(x, 7 - i), p);
058 }
059 }
060 return board;
061 }
062
063 /**
064 * Outputs a string representation of a board. (see startingBoard for an
065 * example string)
066 */
067 public String toString()
068 {
069 String out = "";
070 for (int y = 7; y >= 0; y--)
071 {
072 for (int x = 0; x < 8; x++)
073 {
074 Piece p = board[x][y];
075 out += p == null ? " " : p;
076 }
077 out += "\n";
078 }
079 return out;
080 }
081
082 public void put(Position pos, Piece piece){
083 board[pos.getX()][pos.getY()] = piece;
084 }
085
086 public void put(int x, int y, Piece piece){
087 board[x][y] = piece;
088 }
089
090 public Piece get(Position pos){
091 return board[pos.getX()][pos.getY()];
092 }
093 public Piece get(int x, int y){
094 return board[x][y];
095 }
096
097 public Collection<Piece> getPieces(){
098 Collection<Piece> ans = new ArrayList<Piece>();
099 for(int x = 0; x < 8; x++){
100 for(int y = 0; y < 8; y++){
101 Piece p = board[x][y];
102 if (p.getColor() != Color.NONE)
103 ans.add(p);
104 }
105 }
106 return ans;
107 }
108
109 public Position kingPosition(Color c){
110 for(int x = 0; x < 8; x++){
111 for(int y = 0; y < 8; y++){
112 Piece p = board[x][y];
113 if (p instanceof King && p.getColor() == c)
114 return Position.get(x, y);
115 }
116 }
117 return null;
118 }
119
120 public Board copy(){
121 Board b = new Board();
122 for(int x = 0; x < 8; x++){
123 for(int y = 0; y < 8; y++){
124 b.board[x][y] = board[x][y];
125 }
126 }
127 return b;
128 }
129 }