Compare commits

...

2 commits

Author SHA1 Message Date
0e8c48f570 . 2026-09-01 01:43:45 +02:00
a365f70873 ill try smth 2026-08-31 17:54:57 +02:00
50 changed files with 776 additions and 387 deletions

View file

@ -21,11 +21,11 @@ public final class PlayerManager {
this.minigame = minigame; this.minigame = minigame;
} }
public Stream<Player> getParticipants() { public Stream<Player> participants() {
return participants.stream().map(Bukkit::getPlayer); return participants.stream().map(Bukkit::getPlayer);
} }
public Stream<Player> getSpectators() { public Stream<Player> spectators() {
return spectators.stream().map(Bukkit::getPlayer); return spectators.stream().map(Bukkit::getPlayer);
} }
@ -61,7 +61,7 @@ public final class PlayerManager {
return spectators.remove(player.getUniqueId()); return spectators.remove(player.getUniqueId());
} }
public Stream<Player> getAllPlayers() { public Stream<Player> allPlayers() {
return Stream.concat(getParticipants(), getSpectators()); return Stream.concat(participants(), spectators());
} }
} }

View file

@ -33,7 +33,6 @@ public class LobbyPhase<T extends Minigame> extends CompositePhase<T> {
ctx.listeners().on(PlayerJoinEvent.class, EventPriority.LOWEST, this::onJoin); ctx.listeners().on(PlayerJoinEvent.class, EventPriority.LOWEST, this::onJoin);
ctx.listeners().on(PlayerQuitEvent.class, EventPriority.LOWEST, this::onQuit); ctx.listeners().on(PlayerQuitEvent.class, EventPriority.LOWEST, this::onQuit);
//noinspection unchecked
ctx.listeners().cancel( ctx.listeners().cancel(
HangingBreakByEntityEvent.class, HangingBreakByEntityEvent.class,
PlayerInteractAtEntityEvent.class, PlayerInteractAtEntityEvent.class,
@ -51,13 +50,13 @@ public class LobbyPhase<T extends Minigame> extends CompositePhase<T> {
private void onJoin(PlayerJoinEvent ev) { private void onJoin(PlayerJoinEvent ev) {
ctx.players().addParticipant(ev.getPlayer()); ctx.players().addParticipant(ev.getPlayer());
ctx.players().getAllPlayers().forEach(p -> ctx.players().allPlayers().forEach(p ->
p.sendMessage("§8[§a+§8] §7" + ev.getPlayer().getName())); p.sendMessage("§8[§a+§8] §7" + ev.getPlayer().getName()));
} }
private void onQuit(PlayerQuitEvent ev) { private void onQuit(PlayerQuitEvent ev) {
if (ctx.players().removeParticipant(ev.getPlayer())) if (ctx.players().removeParticipant(ev.getPlayer()))
ctx.players().getAllPlayers().forEach(p -> ctx.players().allPlayers().forEach(p ->
p.sendMessage("§8[§c-§8] §7" + ev.getPlayer().getName())); p.sendMessage("§8[§c-§8] §7" + ev.getPlayer().getName()));
} }

View file

@ -30,7 +30,7 @@ class WaitForMaximumPlayersPhase<T extends Minigame> extends Phase<T> {
@Override @Override
protected void onTick(int tick) { protected void onTick(int tick) {
if (tick % 20 == 0) { if (tick % 20 == 0) {
ctx.players().getAllPlayers().forEach(player -> ctx.players().allPlayers().forEach(player ->
player.sendTitle("Game starting in " + secsLeft + " seconds", "have fun", 5, 20, 10) player.sendTitle("Game starting in " + secsLeft + " seconds", "have fun", 5, 20, 10)
); );
secsLeft--; secsLeft--;

View file

@ -21,7 +21,8 @@ public record ScrowMessageStyle(
@Override @Override
public Component ok(Component msg) { public Component ok(Component msg) {
return ComponentUtils.resolveURLS(prefix.append(Component.text("").color(NamedTextColor.GRAY)) return ComponentUtils.resolveURLS(
prefix.append(Component.text("").color(NamedTextColor.GRAY))
.append(msg.colorIfAbsent(NamedTextColor.GRAY))); .append(msg.colorIfAbsent(NamedTextColor.GRAY)));
} }

View file

@ -5,10 +5,7 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.command.ConfiguratorCommand; import site.lab0x13.scrow.configurator.command.ConfiguratorCommand;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry; import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry;
import site.lab0x13.scrow.configurator.storable.impl.VectorStorable;
import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable;
import java.io.IOException; import java.io.IOException;
@ -18,19 +15,6 @@ public class ConfiguratorPlugin extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
ConfigFile hotPotatoConfig = ConfigFile.of(this.getDataPath().resolve("config.json"));
ConfigFileRegistry.get().register(hotPotatoConfig);
var someVector = new VectorStorable();
var someLocation = new LocationStorable();
hotPotatoConfig.registerStorable("someVector", someVector);
hotPotatoConfig.registerStorable("someLocation", someLocation);
try {
hotPotatoConfig.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
ScrowAPI.commands().register(ConfiguratorCommand.rootLiteral(ConfigFileRegistry.get())); ScrowAPI.commands().register(ConfiguratorCommand.rootLiteral(ConfigFileRegistry.get()));
} }

View file

@ -0,0 +1,40 @@
package site.lab0x13.scrow.configurator.action;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.List;
public abstract class SetAction<T> implements StorableAction<T, Storable<T>> {
private final Argument<ScrowBukkitCC, T> argument = argument();
protected abstract Argument<ScrowBukkitCC, T> argument();
protected abstract @Nullable Component valueToPrettyString(T value);
@Override
public String name() {
return "set";
}
@Override
public List<Argument<ScrowBukkitCC, ?>> arguments(Storable<T> __) {
return List.of(argument);
}
@Override
public boolean requiresValue() {
return false;
}
@Override
public void execute(Storable<T> storable, ScrowBukkitCC ctx) {
var parsedArg = ctx.getArgument(argument);
storable.value(parsedArg.value());
var prettyValue = valueToPrettyString(parsedArg.value());
var valueAsString = prettyValue != null ? prettyValue : Component.text(parsedArg.rawValue());
ctx.sender().sendMessage(ctx.style().ok("Set value to ").append(valueAsString));
}
}

View file

@ -11,9 +11,9 @@ import static java.util.Objects.*;
final class CheckLiteral { final class CheckLiteral {
private final Literal<ScrowBukkitCC> literal; private final Literal<ScrowBukkitCC> literal;
private final ConfigFile configFile; private final ConfigFile<?> configFile;
public CheckLiteral(ConfigFile configFile) { public CheckLiteral(ConfigFile<?> configFile) {
this.configFile = configFile; this.configFile = configFile;
this.literal = Literal.<ScrowBukkitCC>builder("check") this.literal = Literal.<ScrowBukkitCC>builder("check")
.withSyncExecutor(this::execute) .withSyncExecutor(this::execute)

View file

@ -8,7 +8,7 @@ public final class ConfigLiteral {
private ConfigLiteral() { private ConfigLiteral() {
} }
public static Literal<ScrowBukkitCC> literal(ConfigFile cfg) { public static Literal<ScrowBukkitCC> literal(ConfigFile<?> cfg) {
return Literal.<ScrowBukkitCC>builder(cfg.path().normalize().toString()) return Literal.<ScrowBukkitCC>builder(cfg.path().normalize().toString())
.withSubLiteral(new KeyLiteral(cfg).literal()) .withSubLiteral(new KeyLiteral(cfg).literal())
.withSubLiteral(new CheckLiteral(cfg).literal()) .withSubLiteral(new CheckLiteral(cfg).literal())

View file

@ -11,9 +11,9 @@ import site.lab0x13.scrow.configurator.action.StorableAction;
final class KeyLiteral { final class KeyLiteral {
private final Literal<ScrowBukkitCC> literal; private final Literal<ScrowBukkitCC> literal;
private final ConfigFile configFile; private final ConfigFile<?> configFile;
KeyLiteral(ConfigFile configFile) { KeyLiteral(ConfigFile<?> configFile) {
this.configFile = configFile; this.configFile = configFile;
literal = Literal.<ScrowBukkitCC>dynamic("key") literal = Literal.<ScrowBukkitCC>dynamic("key")
.withSubLiteralMetas(() -> configFile.allKeys().stream().map(LiteralMeta::of).toList()) .withSubLiteralMetas(() -> configFile.allKeys().stream().map(LiteralMeta::of).toList())

View file

@ -1,28 +1,59 @@
package site.lab0x13.scrow.configurator.configfile; package site.lab0x13.scrow.configurator.configfile;
import com.google.gson.JsonParser;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.Storable; import site.lab0x13.scrow.configurator.storable.Storable;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
public interface ConfigFile extends Storable<Map<String, Storable<?>>> { import static java.util.Objects.requireNonNull;
static ConfigFile of(Path path) { public abstract class ConfigFile<T> extends ComplexStorable<T> {
return new ConfigFileImpl(path.normalize());
private final Path path;
public ConfigFile(Path path) {
this.path = path;
} }
@Nullable Storable<?> getStorable(String key); public void load() throws IOException {
this.loadJson(JsonParser.parseString(Files.readString(path)));
}
void registerStorable(String key, Storable<?> storable); public void save() throws IOException {
Files.writeString(path, this.toJson().toString());
}
List<String> allKeys(); public Storable<?> getStorable(String key) {
Storable<?> cur = this;
for (var fieldName : key.split("\\.")) {
cur = cur.getSubField(fieldName);
if (cur == null) return null;
}
return cur;
}
void load() throws IOException; public List<String> allKeys() {
var res = new ArrayList<String>();
addKeysRecursively(res, null, this);
return res;
}
void save() throws IOException; private void addKeysRecursively(List<String> res, @Nullable String parentKey, Storable<?> storable) {
if (parentKey != null)
res.add(parentKey);
storable.subFieldNames().forEach(subFieldName -> {
var subKey = parentKey == null ? subFieldName : parentKey + "." + subFieldName;
addKeysRecursively(res, subKey, requireNonNull(storable.getSubField(subFieldName)));
});
}
Path path(); public Path path() {
return path;
}
} }

View file

@ -1,83 +0,0 @@
package site.lab0x13.scrow.configurator.configfile;
import com.google.gson.JsonParser;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.storable.MapStorable;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static java.util.Objects.requireNonNull;
class ConfigFileImpl extends MapStorable<Storable<?>> implements ConfigFile {
private static final Logger log = LoggerFactory.getLogger(ConfigFileImpl.class);
private final Path path;
ConfigFileImpl(Path path) {
this.path = path;
}
@Override
public @Nullable Storable<?> getStorable(String key) {
var index = key.indexOf(':');
if (index == -1)
return getSubField(key);
if (key.endsWith(":"))
return null;
var fieldName = key.substring(0, index);
Storable<?> storable = getSubField(fieldName);
if (storable == null)
return null;
for (String subFieldName : key.substring(index + 1).split(":")) {
if (subFieldName.isEmpty()) continue;
storable = storable.getSubField(subFieldName);
if (storable == null)
return null;
}
return storable;
}
@Override
public void registerStorable(String key, Storable<?> storable) {
registerEntry(key, (Storable<Object>) storable);
}
@Override
public List<String> allKeys() {
var res = new ArrayList<String>();
subFieldNames().forEach(key -> addKeysRecursively(res, key, requireNonNull(getSubField(key))));
return res;
}
private void addKeysRecursively(List<String> result, String key, Storable<?> storable) {
result.add(key);
storable.subFieldNames().forEach(subKey ->
addKeysRecursively(result, key + ":" + subKey, requireNonNull(storable.getSubField(subKey))));
}
@Override
public void load() throws IOException {
if (!Files.exists(this.path)) return;
var json = Files.readString(this.path());
this.loadJson(JsonParser.parseString(json));
}
@Override
public void save() throws IOException {
Files.createDirectories(this.path().getParent());
Files.writeString(this.path(), this.toJson().toString());
}
@Override
public Path path() {
return path;
}
}

View file

@ -1,34 +1,33 @@
package site.lab0x13.scrow.configurator.configfile; package site.lab0x13.scrow.configurator.configfile;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ConfigFileRegistry { public class ConfigFileRegistry {
private static final Logger log = LoggerFactory.getLogger(ConfigFileRegistry.class);
private static final ConfigFileRegistry instance = new ConfigFileRegistry(); private static final ConfigFileRegistry instance = new ConfigFileRegistry();
public static ConfigFileRegistry get() { public static ConfigFileRegistry get() {
return instance; return instance;
} }
private final Map<String, ConfigFile> configFiles = new HashMap<>(); private final Map<String, ConfigFile<?>> configFiles = new HashMap<>();
public void register(ConfigFile configFile) { private ConfigFileRegistry() {
var oldValue = configFiles.put(configFile.path().toString(), configFile);
if (oldValue != null)
log.warn("Overwriting old config with same path '{}'", configFile.path());
} }
public Map<String, ConfigFile> allConfigs() { public <S> void register(ConfigFile<S> configFile, S defaultValue) {
configFile.value(defaultValue);
configFiles.put(configFile.path().normalize().toString(), configFile);
}
public Map<String, ConfigFile<?>> allConfigs() {
return new HashMap<>(configFiles); return new HashMap<>(configFiles);
} }
public @Nullable ConfigFile getConfigFile(String path) { public @Nullable ConfigFile<?> getConfigFile(String path) {
return configFiles.get(path); return configFiles.get(path);
} }
} }

View file

@ -1,6 +1,9 @@
package site.lab0x13.scrow.configurator.storable; package site.lab0x13.scrow.configurator.storable;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -8,20 +11,36 @@ import java.util.function.Predicate;
public abstract class AbstractStorable<T> implements Storable<T> { public abstract class AbstractStorable<T> implements Storable<T> {
private final List<ValueChangeSubscriber> subscribers = new ArrayList<>(); private final List<ValueChangeSubscriber> subscribers = new ArrayList<>();
@Nullable private final List<StorableAction<?, ?>> actions = new ArrayList<>();
protected T value = null;
private final List<ValueRequirement<T>> requirements = new ArrayList<>(); private final List<ValueRequirement<T>> requirements = new ArrayList<>();
private @Nullable T value = null;
public AbstractStorable() {
actions.addAll(Storable.super.actions());
}
protected abstract JsonElement toJsonSafe();
protected abstract void loadJsonSafe(JsonElement json);
protected void requireValue(Predicate<T> predicate, String error) { protected void requireValue(Predicate<T> predicate, String error) {
requirements.add(new ValueRequirement<>(predicate, error)); requirements.add(new ValueRequirement<>(predicate, error));
} }
protected void addAction(StorableAction<?, ?> action) {
actions.add(action);
}
@Override @Override
public void subscribe(ValueChangeSubscriber subscriber) { public void subscribe(ValueChangeSubscriber subscriber) {
subscribers.add(subscriber); subscribers.add(subscriber);
} }
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
@Override @Override
public @Nullable T value() { public @Nullable T value() {
return value; return value;
@ -29,10 +48,15 @@ public abstract class AbstractStorable<T> implements Storable<T> {
@Override @Override
public void value(@Nullable T value) { public void value(@Nullable T value) {
this.value = value; setValueSilently(value);
subscribers.forEach(ValueChangeSubscriber::notifyValueChange); subscribers.forEach(ValueChangeSubscriber::notifyValueChange);
} }
@Override
public void setValueSilently(@Nullable T value) {
this.value = value;
}
@Override @Override
public @Nullable String checkValue() { public @Nullable String checkValue() {
for (var requirement : requirements) { for (var requirement : requirements) {
@ -41,4 +65,20 @@ public abstract class AbstractStorable<T> implements Storable<T> {
} }
return null; return null;
} }
@Override
public void loadJson(JsonElement json) {
if (json == null || json.isJsonNull()) {
value(null);
return;
}
loadJsonSafe(json);
}
@Override
public JsonElement toJson() {
if (value == null)
return JsonNull.INSTANCE;
return toJsonSafe();
}
} }

View file

@ -9,6 +9,10 @@ import java.util.Map;
public class MapStorable<V> extends ComplexStorable<Map<String, V>> { public class MapStorable<V> extends ComplexStorable<Map<String, V>> {
public MapStorable() {
value(new HashMap<>());
}
public <S> void registerEntry(String name, Storable<S> storable) { public <S> void registerEntry(String name, Storable<S> storable) {
fieldRegistry().registerField(name, storable, map -> (S) map.get(name)); fieldRegistry().registerField(name, storable, map -> (S) map.get(name));
} }

View file

@ -2,12 +2,13 @@ package site.lab0x13.scrow.configurator.storable;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.action.GlobalSetJsonAction; import site.lab0x13.scrow.configurator.action.GlobalSetJsonAction;
import site.lab0x13.scrow.configurator.action.GlobalShowAction; import site.lab0x13.scrow.configurator.action.GlobalShowAction;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Supplier;
public interface Storable<T> { public interface Storable<T> {
@ -15,6 +16,11 @@ public interface Storable<T> {
void value(@Nullable T value); void value(@Nullable T value);
/**
* Set value without notifying subscribers
*/
void setValueSilently(@Nullable T value);
JsonElement toJson(); JsonElement toJson();
void loadJson(JsonElement json); void loadJson(JsonElement json);

View file

@ -26,19 +26,24 @@ public abstract class WrappedStorable<R, T> extends AbstractStorable<T> {
@Override @Override
public void value(@Nullable T value) { public void value(@Nullable T value) {
if (skipUpdates)
return;
super.value(value); super.value(value);
skipUpdates(() -> realStorable.value(value == null ? null : unwrap(value))); if (skipUpdates) return;
try {
skipUpdates = true;
realStorable.value(value != null ? unwrap(value) : null);
} finally {
skipUpdates = false;
}
} }
@Override @Override
public JsonElement toJson() { public JsonElement toJsonSafe() {
return realStorable.toJson(); return realStorable.toJson();
} }
@Override @Override
public void loadJson(JsonElement json) { public void loadJsonSafe(JsonElement json) {
realStorable.loadJson(json); realStorable.loadJson(json);
} }
@ -51,16 +56,4 @@ public abstract class WrappedStorable<R, T> extends AbstractStorable<T> {
public @Nullable Storable<?> getSubField(String name) { public @Nullable Storable<?> getSubField(String name) {
return realStorable.getSubField(name); return realStorable.getSubField(name);
} }
/**
* Run action without updating the value
*/
private void skipUpdates(Action action) {
try {
skipUpdates = true;
action.apply();
} finally {
skipUpdates = false;
}
}
} }

View file

@ -2,18 +2,18 @@ package site.lab0x13.scrow.configurator.storable.complex;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.Storable; import site.lab0x13.scrow.configurator.storable.Storable;
public abstract class ComplexStorable<T> extends SubFieldedStorable<T> { public abstract class ComplexStorable<T> extends SubFieldedStorable<T> {
@Override public ComplexStorable() {
protected @Nullable T defaultValue() { this.registerFields(fieldRegistry());
return null;
} }
protected abstract void registerFields(FieldRegistry<T> registry);
@Override @Override
public JsonElement toJson() { public JsonElement toJsonSafe() {
var obj = new JsonObject(); var obj = new JsonObject();
fieldRegistry().subFields().forEach((subFieldName, subField) -> { fieldRegistry().subFields().forEach((subFieldName, subField) -> {
var v = (Storable<Object>) subField.storable(); var v = (Storable<Object>) subField.storable();
@ -23,10 +23,9 @@ public abstract class ComplexStorable<T> extends SubFieldedStorable<T> {
} }
@Override @Override
public void loadJson(JsonElement json) { public void loadJsonSafe(JsonElement json) {
var obj = json.getAsJsonObject(); var obj = json.getAsJsonObject();
skipUpdates(() -> fieldRegistry().subFields().forEach((subFieldName, subField) -> fieldRegistry().subFields().forEach((subFieldName, subField) ->
subField.storable().loadJson(obj.get(subFieldName)))); subField.storable().loadJson(obj.get(subFieldName)));
updateValue();
} }
} }

View file

@ -2,6 +2,7 @@ package site.lab0x13.scrow.configurator.storable.complex;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.Storable; import site.lab0x13.scrow.configurator.storable.Storable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -9,11 +10,19 @@ import java.util.function.Function;
public class FieldRegistry<T> { public class FieldRegistry<T> {
private final Storable<T> parent;
private final Map<String, Field<T, ?>> subFields = new HashMap<>(); private final Map<String, Field<T, ?>> subFields = new HashMap<>();
private final Runnable onFieldRegister;
public FieldRegistry(Storable<T> parent, Runnable onFieldRegister) {
this.parent = parent;
this.onFieldRegister = onFieldRegister;
}
// TODO move field stuff into own class where register field is one block and after that ready is called
public <S> void registerField(String name, Storable<S> storable, Function<T, S> getter) { public <S> void registerField(String name, Storable<S> storable, Function<T, S> getter) {
subFields.put(name, new Field<>(storable, getter)); subFields.put(name, new Field<>(storable, getter));
parent.subscribe(() -> storable.setValueSilently(getter.apply(parent.value())));
storable.subscribe(onFieldRegister::run);
} }
public Map<String, Field<T, ?>> subFields() { public Map<String, Field<T, ?>> subFields() {

View file

@ -2,59 +2,20 @@ package site.lab0x13.scrow.configurator.storable.complex;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.AbstractStorable; import site.lab0x13.scrow.configurator.storable.AbstractStorable;
import site.lab0x13.scrow.configurator.storable.Action;
import site.lab0x13.scrow.configurator.storable.Storable; import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Supplier;
public abstract class SubFieldedStorable<T> extends AbstractStorable<T> { public abstract class SubFieldedStorable<T> extends AbstractStorable<T> {
private final FieldRegistry<T> fieldRegistry = new FieldRegistry<>(); private final FieldRegistry<T> fieldRegistry = new FieldRegistry<>(this, this::onFieldRegister);
private boolean skipUpdates = false;
public SubFieldedStorable() {
this.registerFields(fieldRegistry);
fieldRegistry.subFields().values().forEach(f -> f.storable().subscribe(this::updateValue));
}
protected abstract void registerFields(FieldRegistry<T> registry);
protected abstract T construct(FieldReader<T> reader); protected abstract T construct(FieldReader<T> reader);
protected abstract @Nullable T defaultValue(); private void onFieldRegister() {
this.setValueSilently(construct(new FieldReader<>(fieldRegistry)));
/**
* Run action without updating the value
*/
protected void skipUpdates(Action action) {
try {
skipUpdates = true;
action.apply();
} finally {
skipUpdates = false;
}
}
protected void updateValue() {
if (skipUpdates)
return;
super.value(construct(new FieldReader<>(fieldRegistry)));
}
@Override
public void value(@Nullable T value) {
if (value == null) {
super.value(defaultValue());
return;
}
super.value(value);
// reflect value change no sub fields
skipUpdates(() -> fieldRegistry.subFields().values().forEach(_field -> {
var field = (Field<T, Object>) _field;
field.storable().value(field.getter().apply(value));
}));
} }
@Override @Override

View file

@ -0,0 +1,23 @@
package site.lab0x13.scrow.configurator.storable.impl;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.primitive.IntStorable;
import site.lab0x13.scrow.configurator.storable.primitive.LongStorable;
import java.time.Duration;
public final class DurationStorable extends ComplexStorable<Duration> {
@Override
protected void registerFields(FieldRegistry<Duration> registry) {
registry.registerField("seconds", new LongStorable(), Duration::getSeconds);
registry.registerField("nanos", new IntStorable(), Duration::getNano);
}
@Override
protected Duration construct(FieldReader<Duration> reader) {
return Duration.ofSeconds(reader.read("seconds"), reader.read("nanos"));
}
}

View file

@ -6,7 +6,7 @@ import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry; import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable; import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
public class VectorStorable extends ComplexStorable<Vector> { public final class VectorStorable extends ComplexStorable<Vector> {
@Override @Override
protected void registerFields(FieldRegistry<Vector> registry) { protected void registerFields(FieldRegistry<Vector> registry) {

View file

@ -0,0 +1,30 @@
package site.lab0x13.scrow.configurator.storable.impl.component;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.commands.model.argument.types.StringArgumentType;
import site.lab0x13.scrow.configurator.action.SetAction;
import site.lab0x13.scrow.configurator.storable.WrappedStorable;
import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
public final class ComponentStorable extends WrappedStorable<String, Component> {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
public ComponentStorable() {
super(new StringStorable());
addAction(new SetComponentAction());
}
@Override
protected Component wrap(String real) {
return miniMessage.deserialize(real);
}
@Override
protected String unwrap(Component value) {
return miniMessage.serialize(value);
}
}

View file

@ -0,0 +1,21 @@
package site.lab0x13.scrow.configurator.storable.impl.component;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.commands.model.argument.types.StringArgumentType;
import site.lab0x13.scrow.configurator.action.SetAction;
class SetComponentAction extends SetAction<String> {
@Override
protected Argument<ScrowBukkitCC, String> argument() {
return Argument.builder("miniMessage", new StringArgumentType<ScrowBukkitCC>())
.build();
}
@Override
protected Component valueToPrettyString(String value) {
return MiniMessage.miniMessage().deserialize(value);
}
}

View file

@ -1,82 +0,0 @@
package site.lab0x13.scrow.configurator.storable.impl.list;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.AbstractStorable;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import static java.util.Objects.requireNonNull;
public class ListStorable<S extends Storable<?>> extends AbstractStorable<List<S>> {
private final Supplier<S> newElementSupplier;
private final List<StorableAction<?, ?>> actions;
public ListStorable(Supplier<S> newElementSupplier) {
this.newElementSupplier = newElementSupplier;
actions = super.actions();
actions.add(new ListExpandAction<>());
}
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
@Override
public @NotNull List<S> value() {
var v = super.value();
if (v == null) {
v = new ArrayList<>();
value(v);
}
return v;
}
/**
* Expands the list with a default value storable
*/
public S expandList() {
var newElement = newElementSupplier.get();
requireNonNull(value()).add(newElement);
return newElement;
}
@Override
public JsonElement toJson() {
var out = new JsonArray();
requireNonNull(value()).forEach(storable -> out.add(storable.toJson()));
return out;
}
@Override
public void loadJson(JsonElement json) {
var in = json.getAsJsonArray();
in.forEach(jsonElement -> expandList().loadJson(jsonElement));
}
@Override
public List<String> subFieldNames() {
var v = value();
if (v == null) return Collections.emptyList();
return IntStream.range(0, v.size())
.mapToObj(Integer::toString)
.toList();
}
@Override
public @Nullable Storable<?> getSubField(String name) {
var v = value();
if (v == null) return null;
return v.get(Integer.parseInt(name));
}
}

View file

@ -1,26 +1,18 @@
package site.lab0x13.scrow.configurator.storable.impl.location; package site.lab0x13.scrow.configurator.storable.impl.location;
import org.bukkit.Location; import org.bukkit.Location;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable; import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
import site.lab0x13.scrow.configurator.storable.primitive.FloatStorable;
import site.lab0x13.scrow.configurator.storable.primitive.PrimitiveStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader; import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry; import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.world.WorldStorable; import site.lab0x13.scrow.configurator.storable.impl.world.WorldStorable;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
import site.lab0x13.scrow.configurator.storable.primitive.FloatStorable;
import java.util.ArrayList; public final class LocationStorable extends ComplexStorable<Location> {
import java.util.List;
public class LocationStorable extends ComplexStorable<Location> {
private final List<StorableAction<?, ?>> actions;
public LocationStorable() { public LocationStorable() {
actions = new ArrayList<>(super.actions()); addAction(new LocationPickCurrentAction());
actions.add(new LocationPickCurrentAction()); addAction(new LocationTeleportAction());
actions.add(new LocationTeleportAction());
} }
@Override @Override
@ -33,11 +25,6 @@ public class LocationStorable extends ComplexStorable<Location> {
registry.registerField("pitch", new FloatStorable(), Location::getPitch); registry.registerField("pitch", new FloatStorable(), Location::getPitch);
} }
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
@Override @Override
protected Location construct(FieldReader<Location> reader) { protected Location construct(FieldReader<Location> reader) {
return new Location( return new Location(

View file

@ -8,6 +8,9 @@ import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects;
import static java.util.Objects.*;
class LocationTeleportAction implements StorableAction<Location, Storable<Location>> { class LocationTeleportAction implements StorableAction<Location, Storable<Location>> {
@ -28,8 +31,7 @@ class LocationTeleportAction implements StorableAction<Location, Storable<Locati
@Override @Override
public void execute(Storable<Location> node, ScrowBukkitCC ctx) { public void execute(Storable<Location> node, ScrowBukkitCC ctx) {
assert node.value() != null; ctx.player().teleport(requireNonNull(node.value()));
ctx.player().teleport(node.value());
ctx.player().sendMessage(ctx.style().ok("You've been teleported.")); ctx.player().sendMessage(ctx.style().ok("You've been teleported."));
} }
} }

View file

@ -1,38 +1,21 @@
package site.lab0x13.scrow.configurator.storable.impl.world; package site.lab0x13.scrow.configurator.storable.impl.world;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC; import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import org.bukkit.World; import org.bukkit.World;
import site.lab0x13.scrow.commands.bukkit.type.WorldArgumentType; import site.lab0x13.scrow.commands.bukkit.type.WorldArgumentType;
import site.lab0x13.scrow.commands.model.argument.Argument; import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.configurator.action.StorableAction; import site.lab0x13.scrow.configurator.action.SetAction;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.List; class SetWorldAction extends SetAction<World> {
class SetWorldAction implements StorableAction<World, Storable<World>> {
private final Argument<ScrowBukkitCC, World> arg =
Argument.builder("world", new WorldArgumentType<ScrowBukkitCC>()).build();
@Override @Override
public String name() { protected Component valueToPrettyString(World value) {
return "set"; return Component.text(value.getName() + "(" + value.getUID() + ")");
} }
@Override @Override
public List<Argument<ScrowBukkitCC, ?>> arguments(Storable<World> __) { protected Argument<ScrowBukkitCC, World> argument() {
return List.of(arg); return Argument.builder("world", new WorldArgumentType<ScrowBukkitCC>()).build();
}
@Override
public boolean requiresValue() {
return false;
}
@Override
public void execute(Storable<World> node, ScrowBukkitCC ctx) {
World world = ctx.getArg(arg);
node.value(world);
ctx.sender().sendMessage(ctx.style().ok("Set world to " + world.getName() + "(" + world.getUID() + ")"));
} }
} }

View file

@ -9,7 +9,7 @@ import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class WorldStorable extends WrappedStorable<String, World> { public final class WorldStorable extends WrappedStorable<String, World> {
private final List<StorableAction<?, ?>> actions; private final List<StorableAction<?, ?>> actions;

View file

@ -1,4 +1,4 @@
package site.lab0x13.scrow.configurator.storable.impl.list; package site.lab0x13.scrow.configurator.storable.list;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC; import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import site.lab0x13.scrow.commands.model.argument.Argument; import site.lab0x13.scrow.commands.model.argument.Argument;

View file

@ -0,0 +1,95 @@
package site.lab0x13.scrow.configurator.storable.list;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.AbstractStorable;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class ListStorable<S> extends AbstractStorable<List<S>> {
private final Supplier<Storable<S>> newElementSupplier;
private final List<StorableAction<?, ?>> actions;
private final List<Storable<S>> _value;
public ListStorable(Supplier<Storable<S>> newElementSupplier) {
this.newElementSupplier = newElementSupplier;
_value = new ArrayList<>();
value(new ArrayList<>());
actions = super.actions();
actions.add(new ListExpandAction<>());
}
@Override
public void value(@Nullable List<S> value) {
super.value(value != null ? value : new ArrayList<>());
}
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
/**
* Expands the list with a default value storable
*/
public Storable<S> expandList() {
var newElement = newElementSupplier.get();
newElement.subscribe(this::updateValue);
_value.add(newElement);
updateValue();
return newElement;
}
public void deleteAt(int index) {
_value.remove(index);
updateValue();
}
@Override
public JsonElement toJsonSafe() {
var out = new JsonArray();
_value.forEach(storable -> out.add(storable.toJson()));
return out;
}
@Override
public void loadJsonSafe(JsonElement json) {
var in = json.getAsJsonArray();
_value.clear();
in.forEach(jsonElement -> {
var element = newElementSupplier.get();
element.loadJson(jsonElement);
_value.add(element);
});
updateValue();
}
@Override
public List<String> subFieldNames() {
return IntStream.range(0, _value.size())
.mapToObj(Integer::toString)
.toList();
}
@Override
public @Nullable Storable<?> getSubField(String name) {
int index;
try {
index = Integer.parseInt(name);
} catch (NumberFormatException _) {
return null;
}
return _value.get(index);
}
private void updateValue() {
setValueSilently(_value.stream().map(Storable::value).toList());
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
public class BooleanStorable extends PrimitiveStorable<Boolean>{ public final class BooleanStorable extends PrimitiveStorable<Boolean>{
public BooleanStorable(boolean defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsBoolean);
}
public BooleanStorable() { public BooleanStorable() {
super(false, JsonPrimitive::new, JsonPrimitive::getAsBoolean); this(false);
} }
} }

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
public class ByteStorable extends PrimitiveStorable<Byte>{ public final class ByteStorable extends PrimitiveStorable<Byte>{
public ByteStorable(byte defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsByte);
}
public ByteStorable() { public ByteStorable() {
super((byte)0, JsonPrimitive::new, JsonPrimitive::getAsByte); this((byte) 0);
} }
} }

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
public class DoubleStorable extends PrimitiveStorable<Double>{ public final class DoubleStorable extends PrimitiveStorable<Double>{
public DoubleStorable(double defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsDouble);
}
public DoubleStorable() { public DoubleStorable() {
super(0D, JsonPrimitive::new, JsonPrimitive::getAsDouble); this(0);
} }
} }

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
public class FloatStorable extends PrimitiveStorable<Float>{ public final class FloatStorable extends PrimitiveStorable<Float>{
public FloatStorable(float defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsFloat);
}
public FloatStorable() { public FloatStorable() {
super(0F, JsonPrimitive::new, JsonPrimitive::getAsFloat); this(0);
} }
} }

View file

@ -2,9 +2,12 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
public class IntStorable extends PrimitiveStorable<Integer>{ public final class IntStorable extends PrimitiveStorable<Integer>{
public IntStorable(int defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsInt);
}
public IntStorable() { public IntStorable() {
super(0, JsonPrimitive::new, JsonPrimitive::getAsInt); this(0);
} }
} }

View file

@ -0,0 +1,14 @@
package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public final class LongStorable extends PrimitiveStorable<Long> {
public LongStorable(long defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsLong);
}
public LongStorable() {
this(0);
}
}

View file

@ -13,9 +13,9 @@ import java.util.function.Function;
public class PrimitiveStorable<V> extends AbstractStorable<V> { public class PrimitiveStorable<V> extends AbstractStorable<V> {
private final V defaultValue;
private final Function<V, JsonPrimitive> serializer; private final Function<V, JsonPrimitive> serializer;
private final Function<JsonPrimitive, V> deserializer; private final Function<JsonPrimitive, V> deserializer;
private final V defaultValue;
public PrimitiveStorable(V defaultValue, Function<V, JsonPrimitive> serializer, Function<JsonPrimitive, V> deserializer) { public PrimitiveStorable(V defaultValue, Function<V, JsonPrimitive> serializer, Function<JsonPrimitive, V> deserializer) {
this.defaultValue = defaultValue; this.defaultValue = defaultValue;
@ -24,25 +24,15 @@ public class PrimitiveStorable<V> extends AbstractStorable<V> {
} }
@Override @Override
public JsonElement toJson() { public JsonElement toJsonSafe() {
if (value() == null)
return JsonNull.INSTANCE;
return serializer.apply(value()); return serializer.apply(value());
} }
@Override @Override
public void loadJson(JsonElement json) { public void loadJsonSafe(JsonElement json) {
if (json.isJsonNull())
value(defaultValue);
else
value(deserializer.apply(json.getAsJsonPrimitive())); value(deserializer.apply(json.getAsJsonPrimitive()));
} }
@Override
public void value(@Nullable V value) {
super.value(value == null ? defaultValue : value);
}
@Override @Override
public List<String> subFieldNames() { public List<String> subFieldNames() {
return Collections.emptyList(); return Collections.emptyList();

View file

@ -1,10 +1,22 @@
package site.lab0x13.scrow.configurator.storable.primitive; package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.List;
public final class StringStorable extends PrimitiveStorable<String>{
public StringStorable(String defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsString);
}
public class StringStorable extends PrimitiveStorable<String>{
public StringStorable() { public StringStorable() {
super("", JsonPrimitive::new, JsonPrimitive::getAsString); this("");
}
@Override
public List<StorableAction<?, ?>> actions() {
return super.actions();
} }
} }

View file

@ -5,15 +5,30 @@ import de.kentoj.scrow.bukkit.minigame.PlayerManager;
import de.kentoj.scrow.bukkit.minigame.phaseflow.LinearPhaseFlow; import de.kentoj.scrow.bukkit.minigame.phaseflow.LinearPhaseFlow;
import de.kentoj.scrowlib.convention.ScrowMessageStyle; import de.kentoj.scrowlib.convention.ScrowMessageStyle;
import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextColor;
import site.lab0x13.scrow.extraction.config.ArenaConfig;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
/*
While in the network lobby, players select a kit. then when enough players are found,
players are spread on a map and are tasked to extract some tokens.
extracting a token gives you points, items and a temporary health and speed-boost as well as temporary
wallhacks. extracting a token takes a while and other players want to stop you from doing so, so you'll
need to fight.
*/
public class ExtractionGame implements Minigame { public class ExtractionGame implements Minigame {
private final ScrowMessageStyle style = new ScrowMessageStyle("PotatoRun", TextColor.color(0x8D7726)); private final ScrowMessageStyle style = new ScrowMessageStyle("PotatoRun", TextColor.color(0x8D7726));
private final PlayerManager playerManager = new PlayerManager(this); private final PlayerManager playerManager = new PlayerManager(this);
private final LinearPhaseFlow phaseFlow = new LinearPhaseFlow("potatoRun.root"); private final LinearPhaseFlow phaseFlow = new LinearPhaseFlow("potatoRun.root");
private final ArenaConfig arenaConfig;
public ExtractionGame(ArenaConfig arenaConfig) {
this.arenaConfig = arenaConfig;
}
@Override @Override
public int minParticipants() { public int minParticipants() {
return 0; return 0;
@ -37,4 +52,8 @@ public class ExtractionGame implements Minigame {
public PlayerManager playerManager() { public PlayerManager playerManager() {
return playerManager; return playerManager;
} }
public ArenaConfig arenaConfig() {
return arenaConfig;
}
} }

View file

@ -1,29 +1,26 @@
package site.lab0x13.scrow.extraction; package site.lab0x13.scrow.extraction;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry; import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry;
import site.lab0x13.scrow.extraction.config.ExtractionConfig; import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import site.lab0x13.scrow.extraction.config.ExtractionConfigStorable;
import java.io.IOException;
public class ExtractionPlugin extends JavaPlugin { public class ExtractionPlugin extends JavaPlugin {
private final Logger log = LoggerFactory.getLogger(ExtractionPlugin.class); private static final Logger log = LoggerFactory.getLogger(ExtractionPlugin.class);
private static Plugin _plugin;
public static Plugin plugin() {
return _plugin;
}
@Override @Override
public void onEnable() { public void onEnable() {
log.info("loading"); _plugin = this;
var cfg = ConfigFile.of(this.getDataPath().resolve("config.json")); var config = new ExtractionConfigStorable(this.getDataPath().resolve("config.json"));
ConfigFileRegistry.get().register(cfg); ConfigFileRegistry.get().register(config, ExtractionConfig.defaultConfig());
cfg.registerStorable("arenas", ExtractionConfig.arenas);
try {
cfg.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("loaded");
} }
} }

View file

@ -0,0 +1,10 @@
package site.lab0x13.scrow.extraction.compass;
import org.bukkit.Location;
public interface CompassTarget {
String targetName();
Location location();
}

View file

@ -0,0 +1,48 @@
package site.lab0x13.scrow.extraction.compass;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkArgument;
public class CompassTargetRegistry {
private final Map<UUID, CompassTarget> targets = new HashMap<>();
public void targetNearest(Player player, List<? extends CompassTarget> targetList) {
var nearest = findNearest(player.getLocation(), targetList);
targets.put(player.getUniqueId(), nearest);
}
public void setCompassTarget(Player player, @Nullable CompassTarget compassTarget) {
if (compassTarget == null)
targets.remove(player.getUniqueId());
else
targets.put(player.getUniqueId(), compassTarget);
}
public @Nullable CompassTarget getCompassTarget(Player player) {
return targets.get(player.getUniqueId());
}
private static CompassTarget findNearest(Location location, List<? extends CompassTarget> targetList) {
checkArgument(!targetList.isEmpty(), "targetList is empty");
CompassTarget nearest = targetList.getFirst();
double nearestDistanceSquared = Double.MAX_VALUE;
for (var target : targetList) {
var targetDistanceSquared = target.location().distanceSquared(location);
if (targetDistanceSquared < nearestDistanceSquared) {
nearestDistanceSquared = targetDistanceSquared;
nearest = target;
}
}
return nearest;
}
}

View file

@ -1,11 +1,19 @@
package site.lab0x13.scrow.extraction.config; package site.lab0x13.scrow.extraction.config;
import net.kyori.adventure.text.Component;
import org.bukkit.Location; import org.bukkit.Location;
import site.lab0x13.scrow.configurator.storable.Storable; import site.lab0x13.scrow.extraction.extractionpoint.ExtractionPoint;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public record ArenaConfig( public record ArenaConfig(
List<Storable<Location>> spawnLocations String id,
Component name,
List<Location> spawnLocations,
List<ExtractionPoint> extractionPoints
) { ) {
public static ArenaConfig defaultConfig() {
return new ArenaConfig("", Component.empty(), new ArrayList<>(), new ArrayList<>());
}
} }

View file

@ -3,18 +3,31 @@ package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable; import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader; import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry; import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.list.ListStorable; import site.lab0x13.scrow.configurator.storable.impl.component.ComponentStorable;
import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable; import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
public class ArenaConfigStorable extends ComplexStorable<ArenaConfig> { public class ArenaConfigStorable extends ComplexStorable<ArenaConfig> {
@Override @Override
protected void registerFields(FieldRegistry<ArenaConfig> registry) { protected void registerFields(FieldRegistry<ArenaConfig> registry) {
registry.registerField("spawnLocations", new ListStorable<>(LocationStorable::new), ArenaConfig::spawnLocations); registry.registerField("id", new StringStorable(), ArenaConfig::id);
registry.registerField("name", new ComponentStorable(), ArenaConfig::name);
registry.registerField("spawnLocations",
new ListStorable<>(LocationStorable::new), ArenaConfig::spawnLocations);
registry.registerField("extractionPoints",
new ListStorable<>(ExtractionPointStorable::new),
ArenaConfig::extractionPoints);
} }
@Override @Override
protected ArenaConfig construct(FieldReader<ArenaConfig> reader) { protected ArenaConfig construct(FieldReader<ArenaConfig> reader) {
return new ArenaConfig(reader.read("spawnLocations")); return new ArenaConfig(
reader.read("id"),
reader.read("name"),
reader.read("spawnLocations"),
reader.read("extractionPoints")
);
} }
} }

View file

@ -1,10 +1,27 @@
package site.lab0x13.scrow.extraction.config; package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.storable.impl.list.ListStorable; import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
public final class ExtractionConfig { public record ExtractionConfig(
private ExtractionConfig() { List<ArenaConfig> arenas,
Duration extractionDuration
) {
private static ExtractionConfig instance;
public static ExtractionConfig defaultConfig() {
return new ExtractionConfig(
new ArrayList<>(),
Duration.ofMillis(100)
);
} }
public static final ListStorable<ArenaConfigStorable> arenas = new ListStorable<>(ArenaConfigStorable::new); public ExtractionConfig {
instance = this;
}
public static ExtractionConfig get() {
return instance;
}
} }

View file

@ -0,0 +1,29 @@
package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.DurationStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import java.nio.file.Path;
public class ExtractionConfigStorable extends ConfigFile<ExtractionConfig> {
public ExtractionConfigStorable(Path path) {
super(path);
}
@Override
protected void registerFields(FieldRegistry<ExtractionConfig> registry) {
registry.registerField("arenas", new ListStorable<>(ArenaConfigStorable::new), ExtractionConfig::arenas);
registry.registerField("extractionDuration", new DurationStorable(), ExtractionConfig::extractionDuration);
}
@Override
protected ExtractionConfig construct(FieldReader<ExtractionConfig> reader) {
return new ExtractionConfig(
reader.read("arenas"),
reader.read("extractionDuration")
);
}
}

View file

@ -0,0 +1,19 @@
package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable;
import site.lab0x13.scrow.extraction.extractionpoint.ExtractionPoint;
public class ExtractionPointStorable extends ComplexStorable<ExtractionPoint> {
@Override
protected void registerFields(FieldRegistry<ExtractionPoint> registry) {
registry.registerField("location", new LocationStorable(), ExtractionPoint::location);
}
@Override
protected ExtractionPoint construct(FieldReader<ExtractionPoint> reader) {
return new ExtractionPoint(reader.read("location"));
}
}

View file

@ -0,0 +1,33 @@
package site.lab0x13.scrow.extraction.extractionpoint;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import site.lab0x13.scrow.extraction.compass.CompassTarget;
import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public final class ExtractionPoint implements CompassTarget {
private final Location location;
private final Map<UUID, ExtractionProgress> extractionProgress = new HashMap<>();
public ExtractionPoint(Location location) {
this.location = location;
}
public ExtractionProgress getProgress(Player player) {
return extractionProgress.computeIfAbsent(player.getUniqueId(), _ -> new ExtractionProgress());
}
@Override
public String targetName() {
return "Extraction Point";
}
@Override
public Location location() {
return location;
}
}

View file

@ -0,0 +1,89 @@
package site.lab0x13.scrow.extraction.extractionpoint;
import org.bukkit.scheduler.BukkitRunnable;
import site.lab0x13.scrow.extraction.ExtractionPlugin;
import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static java.util.Objects.requireNonNull;
/**
* You extract by repeatedly calling {@link ExtractionProgress#advanceExtraction()}
* with little delay in between.
* If the delay is too long, progress is reset.
*/
public class ExtractionProgress {
/**
* ticks(= 50ms) after which progress will be reset if {@link ExtractionProgress#advanceExtraction()}
* isn't called.
*/
private static final int MAX_DELAY_TICKS = 2;
private final List<Consumer<Double>> changeSubscribers = new ArrayList<>();
private final long requiredMs;
/**
* System.currentTimeMillis() at first click (in this attempt to extract)
* or < 0 if extracting hasn't been attempted recently.
*/
private long clickingSince = -1;
/**
* System.currentTimeMillis() at last click
*/
private long lastClickMs = 0;
/**
* @param extractionTime duration for which progress must be called repeatedly
*/
public ExtractionProgress(Duration extractionTime) {
this.requiredMs = extractionTime.toMillis();
}
public ExtractionProgress() {
this(ExtractionConfig.get().extractionDuration());
}
public void advanceExtraction() {
if (clickingSince < 0)
clickingSince = System.currentTimeMillis();
lastClickMs = System.currentTimeMillis();
notifyChangeSubscribers();
/* reset if not called again for a while */
new BukkitRunnable() {
final long lastClickMsAtStart = lastClickMs;
@Override
public void run() {
if (lastClickMsAtStart == lastClickMs)
resetProgress();
}
}.runTaskLater(ExtractionPlugin.plugin(), MAX_DELAY_TICKS);
}
public double progress() {
if (lastClickMs == 0)
return 0;
var delta = System.currentTimeMillis() - requiredMs;
return Math.max(1.0, (double) delta / (double) requiredMs);
}
public void resetProgress() {
clickingSince = -1;
lastClickMs = 0;
notifyChangeSubscribers();
}
public void subscribeChange(Consumer<Double> onChange) {
changeSubscribers.add(onChange);
}
private void notifyChangeSubscribers() {
var progress = progress();
changeSubscribers.forEach(sub -> sub.accept(progress));
}
}

View file

@ -0,0 +1,30 @@
package site.lab0x13.scrow.extraction.phase;
import de.kentoj.scrow.bukkit.minigame.phase.Phase;
import de.kentoj.scrow.bukkit.minigame.phaseflow.PhaseContext;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import site.lab0x13.scrow.extraction.ExtractionGame;
import site.lab0x13.scrow.extraction.compass.CompassTargetRegistry;
public class MidgamePhase extends Phase<ExtractionGame> {
private final CompassTargetRegistry compassTargetRegistry;
protected MidgamePhase(PhaseContext<ExtractionGame> ctx, CompassTargetRegistry compassTargetRegistry) {
super(ctx);
this.compassTargetRegistry = compassTargetRegistry;
}
@Override
protected void onStart() {
ctx.players().participants().forEach(player -> {
compassTargetRegistry.targetNearest(player, ctx.game().arenaConfig().extractionPoints());
player.getInventory().addItem(ItemStack.of(Material.COMPASS));
});
}
@Override
protected void onCancel() {
}
}