1 /**************************************************************************
2 Copyright 2005 Webstersmalley
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 *************************************************************************/
16
17
18
19 package com.webstersmalley.chessweb.view;
20
21 import com.webstersmalley.chessweb.model.Board;
22 import com.webstersmalley.chessweb.model.Piece;
23 import com.webstersmalley.chessweb.model.Position;
24
25 public class SimpleStringView {
26 private static final int MAX_CELL_SIZE = 6;
27 private static final String HORIZONTAL_WALL = "------";
28 private static final String JOIN = "+";
29 private static final String VERTICAL_WALL = "|";
30
31 private Board board;
32
33 public SimpleStringView(Board board) {
34 this.board = board;
35 }
36
37 private String drawHorizontalDivider() {
38 StringBuffer sb = new StringBuffer();
39 sb.append(JOIN);
40 for (int i = 0 ; i < board.getWidth(); i++) {
41 sb.append(HORIZONTAL_WALL);
42 sb.append(JOIN);
43 }
44 return sb.toString();
45 }
46
47 private final String padString(final String input, final String pad, final int targetSize) {
48 StringBuffer sb = new StringBuffer();
49 sb.append(input);
50 while (sb.length() < targetSize) {
51 sb.append(pad);
52 }
53 return sb.toString();
54 }
55
56 public String toString() {
57 StringBuffer sb = new StringBuffer();
58 sb.append(drawHorizontalDivider());
59 sb.append("\n");
60 for (int i = board.getHeight()- 1; i >= 0; i--) {
61 sb.append(VERTICAL_WALL);
62 for (int j = 0 ; j < board.getWidth(); j++) {
63 Piece piece = board.getAt(new Position(j,i));
64 if (piece == null) {
65 sb.append(" ");
66 } else {
67 sb.append(padString(piece.getName(), " ", MAX_CELL_SIZE));
68 }
69 sb.append(VERTICAL_WALL);
70 }
71 sb.append("\n");
72 sb.append(drawHorizontalDivider());
73 sb.append("\n");
74 }
75 return sb.toString();
76 }
77 }