summaryrefslogtreecommitdiff
path: root/dice/src/example/java/bjc/dicelang/neodice/commands/RollCommand.java
blob: 275c53eb9e5804a8fd04d57028b557329f861d60 (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
package bjc.dicelang.neodice.commands;

import static bjc.dicelang.neodice.statements.StatementValue.Type.*;

import java.util.*;

import bjc.dicelang.neodice.*;
import bjc.dicelang.neodice.statements.*;

/**
 * A command that rolls a die or die-pool.
 * 
 * @author Ben Culkin
 *
 */
public class RollCommand implements Command {
	@Override
	public StatementValue execute(Iterator<String> words, DieBoxCLI state) {
		if (!words.hasNext()) {
			throw new DieBoxException("Roll must be provided an argument to roll");
		}
		
		StatementValue toRoll = state.runStatement(words);
		
		if (toRoll.type == DIE) {
			DieStatementValue die = (DieStatementValue) toRoll;
			
			return die.value.roll(state.rng);
		} else if (toRoll.type == DIEPOOL) {
			DiePoolStatementValue pool = (DiePoolStatementValue) toRoll;
			
			StatementValue[] values = pool.value
					.roll(state.rng)
					.toArray((sz) -> new StatementValue[sz]);
			
			return new ArrayStatementValue<>(pool.elementType,
					values);
		} else {
			throw new DieBoxException("Roll was provided something that wasn't rollable (only DIE and DIEPOOL objects are rollable) (was %s, of type %s)",
					toRoll, toRoll.type);
		}
	}
	
	@Override
	public String shortHelp() {
		return "rolls a die-like object";
	}
	
	@Override
	public String longHelp() {
		return "Rolls a die-like object, and yields the result of rolling it."
				+ " What is returned can differ based on what is rolled";
	}
}