-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTower.java
54 lines (46 loc) · 1.26 KB
/
Tower.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Tower {
private Piece[] pieces;
private int height;
public Tower(int maxHeight) {
pieces = new Piece[maxHeight];
height = 0;
}
public int getMaxHeight() {
return pieces.length;
}
Piece pieceAt(int height) {
if (height < this.height) {
return pieces[height];
} else {
return new NullPiece();
}
}
public boolean /* successful? */ add(Piece newPiece) {
if (newPiece instanceof NullPiece) {
return false;
} else if (towerIsFull()) {
return false;
} else if (thereIsNoPieceYet() || newPieceIsSmallerThanTopPiece(newPiece)) {
this.pieces[height++] = newPiece;
return true;
} else {
return false;
}
}
public Piece pop() {
if (thereIsNoPieceYet()) {
return new NullPiece();
} else {
return pieces[--height];
}
}
private boolean towerIsFull() {
return height == getMaxHeight();
}
private boolean thereIsNoPieceYet() {
return height == 0;
}
private boolean newPieceIsSmallerThanTopPiece(Piece newPiece) {
return pieces[height-1].getSize() > newPiece.getSize();
}
}