package com.github.dtschust.zork; import com.github.dtschust.zork.types.HasPrintsAndActions; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public class ZorkTrigger implements HasPrintsAndActions { private final List print; private final List action; /* By default, "single" */ private final ZorkTriggerType type; private final List conditions; private final List commands; public ZorkTrigger(final ZorkTriggerType type, final List conditions, final List commands, final List print, final List action) { this.conditions = conditions; this.commands = commands; this.print = print; this.action = action; this.type = type; } public static boolean evaluateTriggersFor(final Stream collection, final ZorkGame game, final String input) { // non short-circuited to execute all side effects of evaluateTriggers return collection .map(game::getObject) .filter(Optional::isPresent) .map(Optional::get) .map(a -> a.evaluateTriggers(game, input)) .reduce(false, (a, b) -> a || b); } public boolean hasCommand() { return !this.commands.isEmpty(); } 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 getPrints() { return Collections.unmodifiableList(print); } @Override public List getActions() { return Collections.unmodifiableList(action); } public ZorkTriggerType getType() { return type; } }