blob: 86bce4d5f66b6d59fc2b1f86c0cf540f8b84daef (
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
101
102
|
package bjc.dicelang.v2;
import java.util.Random;
public class DiceBox {
private static final Random rng = new Random();
public interface Die {
boolean canOptimize();
int optimize();
int roll();
}
private static class ScalarDie implements Die {
private int val;
public ScalarDie(int vl) {
val = vl;
}
public boolean canOptimize() {
return true;
}
public int optimize() {
return val;
}
public int roll() {
return val;
}
public String toString() {
return Integer.toString(val);
}
}
private static class SimpleDie implements Die {
private int numDice;
private int diceSize;
public SimpleDie(int nDice, int size) {
numDice = nDice;
diceSize = size;
}
public boolean canOptimize() {
if(diceSize == 1) return true;
else return false;
}
public int optimize() {
return numDice;
}
public int roll() {
int total = 0;
for(int i = 0; i < numDice; i++) {
total += rng.nextInt(i) + 1;
}
return total;
}
public String toString() {
return numDice + "d" + diceSize;
}
}
public static Die parseExpression(String exp) {
if(!isValidExpression(exp)) return null;
if(exp.matches(scalarDiePattern)) {
return new ScalarDie(Integer.parseInt(exp));
} else if(exp.matches(simpleDiePattern)) {
String[] dieParts = exp.split("d");
if(dieParts[0].equals("")) {
return new SimpleDie(1, Integer.parseInt(dieParts[1]));
} else {
return new SimpleDie(Integer.parseInt(dieParts[0]), Integer.parseInt(dieParts[1]));
}
}
return null;
}
private static final String scalarDiePattern = "[\\+\\-]?\\d+";
private static final String simpleDiePattern = "(?:\\d+)?d\\d+";
public static boolean isValidExpression(String exp) {
if(exp.matches(scalarDiePattern)) {
return true;
} else if(exp.matches(simpleDiePattern)) {
return true;
} else {
return false;
}
}
}
|