2022-11-16 15:18:00 +00:00
|
|
|
package com.github.dtschust.zork;
|
|
|
|
|
2022-11-22 14:12:55 +00:00
|
|
|
import com.github.dtschust.zork.types.HasPrintsAndActions;
|
|
|
|
|
|
|
|
import java.util.Collections;
|
2022-11-20 13:11:58 +00:00
|
|
|
import java.util.List;
|
2022-11-22 17:31:06 +00:00
|
|
|
import java.util.Optional;
|
|
|
|
import java.util.stream.Stream;
|
2022-11-16 15:18:00 +00:00
|
|
|
|
2022-11-22 14:12:55 +00:00
|
|
|
public class ZorkTrigger implements HasPrintsAndActions {
|
|
|
|
|
|
|
|
private final List<String> print;
|
|
|
|
private final List<String> action;
|
|
|
|
|
2022-11-21 21:29:36 +00:00
|
|
|
/* By default, "single" */
|
2022-11-22 14:12:55 +00:00
|
|
|
private final ZorkTriggerType type;
|
2022-11-22 09:12:04 +00:00
|
|
|
private final List<ZorkCondition> conditions;
|
|
|
|
private final List<ZorkCommand> commands;
|
2022-11-21 21:29:36 +00:00
|
|
|
|
2022-11-22 14:12:55 +00:00
|
|
|
public ZorkTrigger(final ZorkTriggerType type,
|
2022-11-21 21:29:36 +00:00
|
|
|
final List<ZorkCondition> conditions,
|
|
|
|
final List<ZorkCommand> commands,
|
|
|
|
final List<String> print,
|
|
|
|
final List<String> action) {
|
|
|
|
this.conditions = conditions;
|
|
|
|
this.commands = commands;
|
|
|
|
this.print = print;
|
|
|
|
this.action = action;
|
2022-11-20 13:11:58 +00:00
|
|
|
this.type = type;
|
|
|
|
}
|
|
|
|
|
2022-11-22 17:31:06 +00:00
|
|
|
public static boolean evaluateTriggersFor(final Stream<String> collection,
|
|
|
|
final ZorkGame game,
|
|
|
|
final String input) {
|
2022-11-22 14:20:35 +00:00
|
|
|
// non short-circuited to execute all side effects of evaluateTriggers
|
2022-11-22 17:31:06 +00:00
|
|
|
return collection
|
|
|
|
.map(game::getObject)
|
|
|
|
.filter(Optional::isPresent)
|
|
|
|
.map(Optional::get)
|
|
|
|
.map(a -> a.evaluateTriggers(game, input))
|
2022-11-22 14:20:35 +00:00
|
|
|
.reduce(false, (a, b) -> a || b);
|
|
|
|
}
|
|
|
|
|
2022-11-22 09:12:04 +00:00
|
|
|
public boolean hasCommand() {
|
|
|
|
return !this.commands.isEmpty();
|
|
|
|
}
|
|
|
|
|
2022-11-22 14:12:55 +00:00
|
|
|
public boolean isTriggered(final ZorkGame game, final String currentCommand) {
|
|
|
|
return commands.stream().allMatch(c -> c.matchesInput(currentCommand)) &&
|
|
|
|
conditions.stream().allMatch(c -> c.evaluate(game));
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public List<String> getPrints() {
|
|
|
|
return Collections.unmodifiableList(print);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public List<String> getActions() {
|
|
|
|
return Collections.unmodifiableList(action);
|
|
|
|
}
|
|
|
|
|
|
|
|
public ZorkTriggerType getType() {
|
|
|
|
return type;
|
2022-11-16 15:18:00 +00:00
|
|
|
}
|
|
|
|
}
|