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/parser/ZorkParser.java

44 lines
1.7 KiB
Java

package com.github.dtschust.zork.parser;
import com.github.dtschust.zork.ZorkGame;
import com.github.dtschust.zork.objects.*;
import java.util.Map;
import static com.github.dtschust.zork.objects.ZorkObjectTypes.*;
public abstract class ZorkParser {
private final Map<ZorkObjectTypes, PropertyParseStrategy<? extends ZorkObject>> strategies;
public ZorkParser(final PropertyParseStrategy<ZorkCreature> creatureStrategy,
final PropertyParseStrategy<ZorkContainer> containerStrategy,
final PropertyParseStrategy<ZorkItem> itemStrategy,
final PropertyParseStrategy<ZorkRoom> roomStrategy) {
this.strategies = Map.ofEntries(
Map.entry(CREATURE, creatureStrategy),
Map.entry(CONTAINER, containerStrategy),
Map.entry(ITEM, itemStrategy),
Map.entry(ROOM, roomStrategy)
);
}
protected abstract Property getRootProperty(final String filename);
public ZorkGame parse(final String filename) {
ZorkGame data = new ZorkGame();
final Property rootElement = getRootProperty(filename);
// Every single first generation child is a room, container, creature, or item. So load them in
for (final Property element : rootElement.subProperties()) {
final String name = element.name();
final ZorkObjectTypes t = ZorkObjectTypes.fromPropertyName(name)
.orElseThrow(() -> new IllegalStateException("Unexpected value: " + name));
final ZorkObject built = strategies.get(t).parse(element);
data.addObjectThroughLookup(t, built);
}
return data;
}
}