summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java
diff options
context:
space:
mode:
authorbjculkin <bjculkin@WIT-136XG42.wvu-ad.wvu.edu>2017-02-27 10:08:50 -0500
committerbjculkin <bjculkin@WIT-136XG42.wvu-ad.wvu.edu>2017-02-27 10:08:50 -0500
commit79ee129fc0d36ad10bceb942262f2842419c030c (patch)
treed1298fdb8b81726f4b9012d7a29c3029a55a3aa7 /dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java
parentc50a0744269ce22604c0604cc69e6d5e5ce8a3fc (diff)
Pacakge reorganization
Diffstat (limited to 'dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java')
-rw-r--r--dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java86
1 files changed, 86 insertions, 0 deletions
diff --git a/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java
new file mode 100644
index 0000000..ac630a8
--- /dev/null
+++ b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java
@@ -0,0 +1,86 @@
+package bjc.dicelang.v1;
+
+/**
+ * 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 type;
+
+ /*
+ * 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 rght
+ * The die on the right side of the expression
+ * @param lft
+ * The die on the left side of the expression
+ * @param type
+ * The operator to use for combining the dices
+ */
+ public OperatorDiceExpression(IDiceExpression rght,
+ IDiceExpression lft, DiceExpressionType type) {
+ this.right = rght;
+ this.left = lft;
+ this.type = type;
+ }
+
+ @Override
+ public int roll() {
+ /*
+ * Handle each operator
+ */
+ switch (type) {
+ 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, and continuous
+ * probability is a pain
+ */
+ try {
+ return right.roll() / left.roll();
+ } catch (ArithmeticException aex) {
+ UnsupportedOperationException usex = new UnsupportedOperationException(
+ "Attempted to divide by zero."
+ + " Problematic expression is "
+ + left);
+
+ usex.initCause(aex);
+
+ throw usex;
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Got passed a invalid ScalarExpressionType ("
+ + type + "). WAT");
+
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "dice-exp[type=" + type + ", l="
+ + left.toString() + ", r="
+ + right.toString() + "]";
+ }
+}