summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java
blob: f86773df46365478bcd1bb26bc1fc23b25c930ce (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
package bjc.dicelang;

/**
 * Implements a class for combining two dice with an operator
 * 
 * @author ben
 *
 */
public class OperatorDiceExpression implements IDiceExpression {
	/**
	 * The operator to use for combining the dice
	 */
	private DiceExpressionType	expressionType;

	/**
	 * The dice on the left side of the expression
	 */
	private IDiceExpression		leftExpression;

	/**
	 * The dice on the right side of the expression
	 */
	private IDiceExpression		rightExpression;

	/**
	 * Create a new compound expression using the specified parameters
	 * 
	 * @param right
	 *            The die on the right side of the expression
	 * @param left
	 *            The die on the left side of the expression
	 * @param type
	 *            The operator to use for combining the dices
	 */
	public OperatorDiceExpression(IDiceExpression right,
			IDiceExpression left, DiceExpressionType type) {
		this.rightExpression = right;
		this.leftExpression = left;
		this.expressionType = type;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see bjc.utils.dice.IDiceExpression#roll()
	 */
	@Override
	public int roll() {
		/*
		 * Handle each operator
		 */
		switch (expressionType) {
			case ADD:
				return rightExpression.roll() + leftExpression.roll();
			case SUBTRACT:
				return rightExpression.roll() - leftExpression.roll();
			case MULTIPLY:
				return rightExpression.roll() * leftExpression.roll();
			case DIVIDE:
				/*
				 * Round to keep results as integers. We don't really have
				 * any need for floating-point dice, and continuous
				 * probability is a pain
				 */
				try {
					return rightExpression.roll() / leftExpression.roll();
				} catch (ArithmeticException aex) {
					UnsupportedOperationException usex = new UnsupportedOperationException(
							"Attempted to divide by zero."
									+ " Problematic expression is "
									+ leftExpression);

					usex.initCause(aex);

					throw usex;
				}
			default:
				throw new IllegalArgumentException(
						"Got passed  a invalid ScalarExpressionType ("
								+ expressionType + "). WAT");

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "dice-exp[type=" + expressionType + ", l="
				+ leftExpression.toString() + ", r="
				+ rightExpression.toString() + "]";
	}
}