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

import bjc.utils.funcutils.StringUtils;

/**
 * An expression for something that can be rolled like a polyhedral die
 * 
 * @author ben
 *
 */
@FunctionalInterface
public interface IDiceExpression {
	/**
	 * Roll the dice once
	 * 
	 * @return The result of rowing the dice
	 */
	public int roll();

	/**
	 * Optimize this expression to a scalar value
	 * 
	 * @return This expression, optimized to a scalar value
	 * 
	 * @throws UnsupportedOperationException
	 *             if this type of expression can't be optimized
	 */
	public default int optimize() {
		throw new UnsupportedOperationException(
				"Can't optimize this type of expression");
	}

	/**
	 * Check if this expression can be optimized to a scalar value
	 * 
	 * @return Whether or not this expression can be optimized to a scalar
	 *         value
	 */
	public default boolean canOptimize() {
		return false;
	}

	/**
	 * Parse this node into an expression
	 * @param exp The string to convert to an expression
	 * 
	 * @return The node in expression form
	 */
	static IDiceExpression toExpression(String exp) {
		String literalData = exp;
	
		if (StringUtils.containsInfixOperator(literalData, "c")) {
			String[] strangs = literalData.split("c");
	
			return new CompoundDice(strangs);
		} else if (StringUtils.containsInfixOperator(literalData,
				"d")) {
			/*
			 * Handle dice groups
			 */
			return ComplexDice.fromString(literalData);
		} else {
			try {
				return new ScalarDie(Integer.parseInt(literalData));
			} catch (NumberFormatException nfex) {
				UnsupportedOperationException usex = new UnsupportedOperationException(
						"Found malformed leaf token " + exp);
	
				usex.initCause(nfex);
	
				throw usex;
			}
		}
	}
}