This repository has been archived on 2022-12-21. You can view files and clone it, but cannot push or open issues or pull requests.
sdm03/src/main/java/com/github/dtschust/zork/repl/actions/TakeAction.java

46 lines
1.8 KiB
Java

package com.github.dtschust.zork.repl.actions;
import com.github.dtschust.zork.ZorkGame;
import com.github.dtschust.zork.objects.ZorkContainer;
import com.github.dtschust.zork.repl.Action;
import java.util.List;
public class TakeAction implements Action {
@Override
public boolean matchesInput(List<String> arguments) {
return arguments.get(0).equals("take");
}
@Override
public int getMinimumArgCount() {
return 2;
}
@Override
public boolean run(ZorkGame game, List<String> arguments) {
return game.getItem(arguments.get(1)).map(i -> {
if (game.getCurrentRoom().containsItem(i.getName())) {
game.inventory.add(i.getName());
game.getCurrentRoom().removeObject(i);
game.stream.println("Item " + i.getName() + " added to inventory.");
return true;
} else {
// Search all containers in the current room for the item!
for (final String key : game.getCurrentRoom().getContainer()) {
final ZorkContainer tempContainer = game.getContainer(key).orElseThrow(() ->
new IllegalStateException("container " + key + " in room " +
game.getCurrentRoom().getName() + " not found"));
if (tempContainer != null && tempContainer.isOpen() && tempContainer.containsItem(i.getName())) {
game.inventory.add(i.getName());
tempContainer.removeObject(i);
game.stream.println("Item " + i.getName() + " added to inventory.");
return true;
}
}
}
return false;
}).orElse(false);
}
}