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/objects/ZorkContainer.java

73 lines
2.0 KiB
Java

package com.github.dtschust.zork.objects;
import com.github.dtschust.zork.ZorkTrigger;
import com.github.dtschust.zork.types.ObjectCollector;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/* Container*/
public class ZorkContainer extends ZorkObject implements ObjectCollector {
private final Set<String> items;
private boolean open;
public ZorkContainer(final String name,
final String description,
final String status,
final Collection<String> items,
final Collection<String> accepts,
final Collection<ZorkTrigger> triggers) {
super(name, description, status, triggers);
// If a container has an accepts attribute, then it is always open
this.open = !accepts.isEmpty();
this.items = new HashSet<>(items);
}
public String getContents() {
if (this.items.isEmpty()) {
return getName() + " is empty";
} else {
return getName() + " contains " + String.join(", ", items) + ".";
}
}
public void addItem(final String item) {
this.items.add(item);
}
public void removeItem(final String item) {
this.items.remove(item);
}
public boolean containsItem(final String item) {
return this.items.contains(item);
}
public boolean isOpen() {
return open;
}
public void open() {
open = true;
}
@Override
public void addObject(final ZorkObject object) {
if (!(object instanceof ZorkItem)) {
throw new UnsupportedOperationException(
"a container cannot store " + object.getClass().getSimpleName() + " objects");
}
addItem(object.getName());
}
@Override
public void removeObject(final ZorkObject object) {
if (!(object instanceof ZorkItem)) {
return;
}
removeItem(object.getName());
}
}