summaryrefslogtreecommitdiff
path: root/dice/src/main/java/bjc/dicelang/neodice/die/RerollDie.java
blob: 3cd369fc4b451b5bf1c4d7d65cf518495bfe1feb (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
package bjc.dicelang.neodice.die;

import java.util.*;
import java.util.function.*;

import bjc.dicelang.neodice.*;
import bjc.esodata.*;

public class RerollDie implements Die {
	private final Die          contained;
	
	private final IntPredicate                           condition;
	private final Function<MinMaxList<Integer>, Integer> chooser;
	
	private int limit = Integer.MAX_VALUE;
	
	
	public RerollDie(Die contained, IntPredicate condition,
			Function<MinMaxList<Integer>, Integer> chooser) {
		this.contained = contained;
		
		this.condition = condition;
		this.chooser   = chooser;
	}
	
	public RerollDie(Die contained, IntPredicate condition,
			Function<MinMaxList<Integer>, Integer> chooser, int limit) {
		this.contained = contained;
		
		this.condition = condition;
		this.chooser   = chooser;
		
		this.limit = limit;
	}
	
	@Override
	public int roll(Random rng) {
		int roll = contained.roll(rng);
		
		MinMaxList<Integer> newRolls = new MinMaxList<Integer>(
				Comparator.naturalOrder(), roll);
		
		int rerollCount = 0;
		while (condition.test(roll) && rerollCount < limit) {
			roll = contained.roll(rng);
			newRolls.add(roll);
			
			rerollCount += 1;
		}
		
		return chooser.apply(newRolls);
	}

	// No toString, because IntPredicate can't be converted to a string
}