summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java
diff options
context:
space:
mode:
authorbculkin2442 <bjculkin@mix.wvu.edu>2016-04-03 18:43:50 -0400
committerbculkin2442 <bjculkin@mix.wvu.edu>2016-04-03 18:43:50 -0400
commit9658afb5b07d2b5a965dea322b0ad8fa3c16ce2d (patch)
treef9e50750e1a0d04f0c84ef9177bb5f7ae9050dc8 /dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java
parentc8ae1ec096f5d1ac6db4f3a0035f7da106444e4e (diff)
More refactoring and maintenance
Diffstat (limited to 'dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java')
-rw-r--r--dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java90
1 files changed, 90 insertions, 0 deletions
diff --git a/dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java b/dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java
new file mode 100644
index 0000000..4ca2568
--- /dev/null
+++ b/dice-lang/src/main/java/bjc/dicelang/OperatorDiceExpression.java
@@ -0,0 +1,90 @@
+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 det;
+
+ /**
+ * The dice on the left side of the expression
+ */
+ private IDiceExpression left;
+
+ /**
+ * The dice on the right side of the expression
+ */
+ private IDiceExpression right;
+
+ /**
+ * 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 det
+ * The operator to use for combining the dices
+ */
+ public OperatorDiceExpression(IDiceExpression right,
+ IDiceExpression left, DiceExpressionType det) {
+ this.right = right;
+ this.left = left;
+ this.det = det;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see bjc.utils.dice.IDiceExpression#roll()
+ */
+ @Override
+ public int roll() {
+ /*
+ * Handle each operator
+ */
+ switch (det) {
+ case ADD:
+ return right.roll() + left.roll();
+ case SUBTRACT:
+ return right.roll() - left.roll();
+ case MULTIPLY:
+ return right.roll() * left.roll();
+ case DIVIDE:
+ /*
+ * Round to keep results as integers. We don't really have
+ * any need for floating-point dice
+ */
+ try {
+ return right.roll() / left.roll();
+ } catch (ArithmeticException aex) {
+ throw new UnsupportedOperationException(
+ "Attempted to divide by zero."
+ + " Problematic expression is "
+ + left);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Got passed a invalid ScalarExpressionType " + det
+ + ". WAT");
+
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "dice-exp[type=" + det + ", l=" + left.toString() + ", r="
+ + right.toString() + "]";
+ }
+}