1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package de.kaiserpfalzedv.rpg.core.dice.mat;
19
20 import com.fasterxml.jackson.annotation.JsonInclude;
21 import de.kaiserpfalzedv.rpg.core.dice.Die;
22 import de.kaiserpfalzedv.rpg.core.dice.LookupTable;
23 import lombok.*;
24 import lombok.extern.jackson.Jacksonized;
25 import net.objecthunter.exp4j.Expression;
26 import net.objecthunter.exp4j.ExpressionBuilder;
27 import org.eclipse.microprofile.openapi.annotations.media.Schema;
28
29 import java.io.Serializable;
30 import java.util.Optional;
31 import java.util.StringJoiner;
32
33
34
35
36
37
38
39 @Jacksonized
40 @Builder(toBuilder = true)
41 @AllArgsConstructor
42 @RequiredArgsConstructor
43 @Getter
44 @ToString
45 @EqualsAndHashCode
46 @JsonInclude(JsonInclude.Include.NON_ABSENT)
47 @Schema(name = "ExpressionTotal", description = "A generic result of an expression.")
48 public class ExpressionTotal implements Serializable {
49 private DieResult[] rolls;
50 private String expression;
51
52
53
54
55
56
57
58 public String getDescription() {
59 StringJoiner rolls = new StringJoiner(", ", "{", "}");
60
61 for (DieResult r : getRolls()) {
62 rolls.add(r.getDisplay());
63 }
64
65 return new StringBuilder(getExpression().replace("x", getDieIdentifier()))
66 .append(": ")
67 .append(calculateExpression())
68 .append(rolls)
69 .toString();
70 }
71
72 public String getDieIdentifier() {
73 return getRolls()[0].getDie().getDieType();
74 }
75
76 public int getAmountOfDice() {
77 return getRolls().length;
78 }
79
80
81
82
83
84
85 public String calculateExpression() {
86 String result = "";
87 if (getRolls().length > 0 && getRolls()[0].getDie().isNumericDie()) {
88 Die die = getRolls()[0].getDie();
89
90 int roll = calcuateTotal(getRolls());
91
92 Expression math = new ExpressionBuilder(getExpression()).variable("x").build();
93
94 int total = roll;
95 Optional<LookupTable> table = die.getLookupTable();
96 if (table.isPresent()) {
97 total = table.get().lookup(roll);
98 }
99
100 total = (int) math.setVariable("x", total).evaluate();
101 result = Integer.toString(total, 10) + " | " + Integer.toString(roll, 10);
102 }
103
104 return result;
105 }
106
107 private int calcuateTotal(DieResult[] rolls) {
108 int total = 0;
109
110 if (rolls.length > 0 && rolls[0].getDie().isNumericDie()) {
111 for (DieResult r : rolls) {
112 total += Integer.parseInt(r.getTotal(), 10);
113 }
114 }
115
116 return total;
117 }
118 }