summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/CompoundDice.java
blob: 704e4cd08401203455ef59d89c128d9d2485b6d1 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package bjc.dicelang;

/**
 * Implements a "compound dice"
 * 
 * To explain, a compound dice is something like a d100 composed from two
 * d10s instead of a hundred sided die.
 * 
 * @author ben
 *
 */
public class CompoundDice implements IDiceExpression {
	/**
	 * The left die of the expression
	 */
	private IDiceExpression	leftDice;

	/**
	 * The right die of the expression
	 */
	private IDiceExpression	rightDice;

	/**
	 * Create a new compound dice using the specified dice
	 * 
	 * @param left
	 *            The die to use on the left
	 * @param right
	 *            The die to use on the right
	 */
	public CompoundDice(IDiceExpression left, IDiceExpression right) {
		this.leftDice = left;
		this.rightDice = right;
	}

	/**
	 * Create a new compound dice from two dice strings
	 * 
	 * @param leftExp
	 *            The left side dice as a string
	 * @param rightExp
	 *            The right side dice as a string
	 */
	public CompoundDice(String leftExp, String rightExp) {
		this(ComplexDice.fromString(leftExp),
				ComplexDice.fromString(rightExp));
	}

	/**
	 * Create a new compound dice from an array of dice strings
	 * 
	 * @param exps
	 *            An array of two dice strings
	 */
	public CompoundDice(String[] exps) {
		this(exps[0], exps[1]);
	}

	@Override
	public boolean canOptimize() {
		return leftDice.canOptimize() && rightDice.canOptimize();
	}

	@Override
	public int optimize() {
		if (!canOptimize()) {
			throw new UnsupportedOperationException(
					"Cannot optimize this compound dice. "
							+ "Both component dice must be optimizable"
							+ " to optimize a compound dice");
		}

		return Integer
				.parseInt(leftDice.optimize() + "" + rightDice.optimize());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see bjc.utils.dice.IDiceExpression#roll()
	 */
	@Override
	public int roll() {
		/*
		 * Make the combination of the two dice
		 */
		return Integer.parseInt(leftDice.roll() + "" + rightDice.roll());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "compound[l=" + leftDice.toString() + ", r="
				+ rightDice.toString() + "]";
	}
}