Add /effect and /enchant
EffectCommands (give with seconds/infinite, amplifier, hideParticles; clear all or one) and EnchantCommand with vanilla's level, support and compatibility checks and response messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -104,6 +104,38 @@ pub fn build() -> Dispatcher {
|
||||
let t = d.argument(kill, "targets", ENTITIES);
|
||||
d.executes(t, "kill");
|
||||
|
||||
// effect clear [<targets> [<effect>]] | give <targets> <effect> [<seconds>|infinite [<amplifier> [<hideParticles>]]]
|
||||
let effect = d.literal(root, "effect");
|
||||
d.requires(effect, GAMEMASTERS);
|
||||
let clear = d.literal(effect, "clear");
|
||||
d.executes(clear, "effect.clear");
|
||||
let t = d.argument(clear, "targets", ENTITIES);
|
||||
d.executes(t, "effect.clear");
|
||||
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
|
||||
d.executes(e, "effect.clear");
|
||||
let give = d.literal(effect, "give");
|
||||
let t = d.argument(give, "targets", ENTITIES);
|
||||
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
|
||||
d.executes(e, "effect.give");
|
||||
let seconds = d.argument(e, "seconds", ArgType::Integer { min: 1, max: 1_000_000 });
|
||||
let infinite = d.literal(e, "infinite");
|
||||
for duration in [seconds, infinite] {
|
||||
d.executes(duration, "effect.give");
|
||||
let amp = d.argument(duration, "amplifier", ArgType::Integer { min: 0, max: 255 });
|
||||
d.executes(amp, "effect.give");
|
||||
let hide = d.argument(amp, "hideParticles", ArgType::Bool);
|
||||
d.executes(hide, "effect.give");
|
||||
}
|
||||
|
||||
// enchant <targets> <enchantment> [<level>]
|
||||
let enchant = d.literal(root, "enchant");
|
||||
d.requires(enchant, GAMEMASTERS);
|
||||
let t = d.argument(enchant, "targets", ENTITIES);
|
||||
let e = d.argument(t, "enchantment", ArgType::Resource(Resource::Enchantment));
|
||||
d.executes(e, "enchant");
|
||||
let level = d.argument(e, "level", integer(0));
|
||||
d.executes(level, "enchant");
|
||||
|
||||
// summon <entity> [<pos>] [<nbt>]
|
||||
let summon = d.literal(root, "summon");
|
||||
d.requires(summon, GAMEMASTERS);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Command execution (the `execute` side of each vanilla command class):
|
||||
//! entity selectors resolved against the game, vanilla feedback and errors.
|
||||
mod effects;
|
||||
|
||||
use super::{Dim, Game, Screen, chat::PLAYER_NAME};
|
||||
use horizon_client::{
|
||||
command::{
|
||||
@@ -281,6 +283,9 @@ impl Game<'_> {
|
||||
"weather" => self.cmd_weather(ctx),
|
||||
"kill" => self.cmd_kill(ctx),
|
||||
"summon" => self.cmd_summon(ctx),
|
||||
"effect.give" => self.cmd_effect_give(ctx),
|
||||
"effect.clear" => self.cmd_effect_clear(ctx),
|
||||
"enchant" => self.cmd_enchant(ctx),
|
||||
"setblock" => self.cmd_setblock(ctx),
|
||||
"fill" => self.cmd_fill(ctx),
|
||||
"clone" => self.cmd_clone(ctx),
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! `/effect` (EffectCommands) and `/enchant` (EnchantCommand).
|
||||
use super::{Arg, Context, Game, R, Target, err, texts};
|
||||
use horizon_client::{
|
||||
brewing,
|
||||
effects::EffectInstance,
|
||||
text::{self, Style, Text},
|
||||
};
|
||||
use std::{collections::HashMap, sync::OnceLock};
|
||||
|
||||
/// `CommandResponseTracker` over targets: elements with a non-zero result.
|
||||
#[derive(Default)]
|
||||
struct Tracker {
|
||||
total: i32,
|
||||
changed: Vec<Target>,
|
||||
}
|
||||
impl Tracker {
|
||||
fn track(&mut self, t: Target, changed: bool) {
|
||||
if changed {
|
||||
self.total += 1;
|
||||
self.changed.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Namespaced effect ids for mob effect storage.
|
||||
fn namespaced(id: &'static str) -> &'static str {
|
||||
static IDS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
|
||||
IDS.get_or_init(|| {
|
||||
brewing::EFFECTS.iter().map(|e| (e.id, &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()))).collect()
|
||||
})
|
||||
.get(id)
|
||||
.copied()
|
||||
.unwrap_or(id)
|
||||
}
|
||||
fn effect_name(id: &str) -> Text {
|
||||
Text::translate(&format!("effect.minecraft.{id}"), &[])
|
||||
}
|
||||
impl Game<'_> {
|
||||
fn effect_arg(ctx: &Context) -> R<&'static brewing::EffectDef> {
|
||||
let Some(Arg::Resource(id)) = ctx.get("effect") else { return Err(err("argument.resource.invalid_type", &[])) };
|
||||
brewing::effect(id).ok_or_else(|| err("argument.resource.not_found", &[id, &"minecraft:mob_effect"]))
|
||||
}
|
||||
/// The executing entity for argument-less forms (the player).
|
||||
fn living_targets(&mut self, ctx: &Context) -> R<Vec<Target>> {
|
||||
if ctx.get("targets").is_some() { self.entities(ctx, "targets", false) } else { Ok(vec![Target::Player]) }
|
||||
}
|
||||
/// `EffectCommands.giveEffect`.
|
||||
pub(super) fn cmd_effect_give(&mut self, ctx: &Context) -> R<i32> {
|
||||
let effect = Self::effect_arg(ctx)?;
|
||||
let seconds = if ctx.has("infinite") { Some(-1) } else { Self::int(ctx, "seconds") };
|
||||
let amplifier = Self::int(ctx, "amplifier").unwrap_or(0);
|
||||
let particles = !matches!(ctx.get("hideParticles"), Some(Arg::Bool(true)));
|
||||
// computeDurationInTicks
|
||||
let duration = match seconds {
|
||||
Some(s) if effect.instant => s,
|
||||
Some(-1) => -1,
|
||||
Some(s) => s * 20,
|
||||
None if effect.instant => 1,
|
||||
None => 600,
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
for t in self.living_targets(ctx)? {
|
||||
let changed = match t {
|
||||
Target::Player => {
|
||||
let mut instance = EffectInstance::new(effect.id, duration, amplifier);
|
||||
instance.visible = particles;
|
||||
self.potions.effects.add(instance)
|
||||
}
|
||||
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
Some(m) => {
|
||||
m.add_effect(namespaced(effect.id), duration, amplifier);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
tracker.track(t, changed);
|
||||
}
|
||||
let message = match tracker.changed.as_slice() {
|
||||
[] => return Err(err("commands.effect.give.failed", &[])),
|
||||
[one] => Text::translate(
|
||||
"commands.effect.give.success.single",
|
||||
&[effect_name(effect.id), self.target_name(*one), Text::literal((duration / 20).to_string())],
|
||||
),
|
||||
many => Text::translate(
|
||||
"commands.effect.give.success.multiple",
|
||||
&texts(&[effect_name(effect.id), Text::literal(many.len().to_string()), Text::literal((duration / 20).to_string())]),
|
||||
),
|
||||
};
|
||||
self.feedback(message);
|
||||
Ok(tracker.total)
|
||||
}
|
||||
/// `EffectCommands.clearEffects` / `clearEffect`.
|
||||
pub(super) fn cmd_effect_clear(&mut self, ctx: &Context) -> R<i32> {
|
||||
let effect = if ctx.get("effect").is_some() { Some(Self::effect_arg(ctx)?) } else { None };
|
||||
let mut tracker = Tracker::default();
|
||||
for t in self.living_targets(ctx)? {
|
||||
let changed = match (t, effect) {
|
||||
(Target::Player, None) => {
|
||||
let any = !self.potions.effects.list.is_empty();
|
||||
self.potions.effects.clear();
|
||||
any
|
||||
}
|
||||
(Target::Player, Some(e)) => {
|
||||
let before = self.potions.effects.list.len();
|
||||
self.potions.effects.list.retain(|x| x.id != e.id);
|
||||
self.potions.effects.list.len() != before
|
||||
}
|
||||
(Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
Some(m) => {
|
||||
let before = m.extra.effects.len();
|
||||
m.extra.effects.retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id)));
|
||||
m.extra.effects.len() != before
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
tracker.track(t, changed);
|
||||
}
|
||||
let message = match (tracker.changed.as_slice(), effect) {
|
||||
([], None) => return Err(err("commands.effect.clear.everything.failed", &[])),
|
||||
([], Some(_)) => return Err(err("commands.effect.clear.specific.failed", &[])),
|
||||
([one], None) => Text::translate("commands.effect.clear.everything.success.single", &[self.target_name(*one)]),
|
||||
(many, None) => Text::translate("commands.effect.clear.everything.success.multiple", &[Text::literal(many.len().to_string())]),
|
||||
([one], Some(e)) => Text::translate("commands.effect.clear.specific.success.single", &[effect_name(e.id), self.target_name(*one)]),
|
||||
(many, Some(e)) => Text::translate(
|
||||
"commands.effect.clear.specific.success.multiple",
|
||||
&texts(&[effect_name(e.id), Text::literal(many.len().to_string())]),
|
||||
),
|
||||
};
|
||||
self.feedback(message);
|
||||
Ok(tracker.total)
|
||||
}
|
||||
/// `EnchantCommand.enchant` (mobs hold bare item ids, so only the player's
|
||||
/// main hand item can carry the enchantment).
|
||||
pub(super) fn cmd_enchant(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(id)) = ctx.get("enchantment").cloned() else { return Ok(0) };
|
||||
let level = Self::int(ctx, "level").unwrap_or(1);
|
||||
let enchantments = &self.res.stations.enchantments;
|
||||
let Some(def) = enchantments.get(&id) else { return Err(err("argument.resource.not_found", &[&id, &"minecraft:enchantment"])) };
|
||||
let max = def.max_level as i32;
|
||||
if level > max {
|
||||
return Err(err("commands.enchant.failed.level", &[&level, &max]));
|
||||
}
|
||||
let targets = self.entities(ctx, "targets", false)?;
|
||||
let single = targets.len() == 1;
|
||||
let mut tracker = Tracker::default();
|
||||
for t in targets {
|
||||
match t {
|
||||
Target::Player => {
|
||||
let Some(stack) = self.inventory[self.selected].clone() else {
|
||||
if single {
|
||||
return Err(err("commands.enchant.failed.itemless", &[&self.target_name(t).plain()]));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let e = &self.res.stations.enchantments;
|
||||
let compatible = e.can_enchant(&self.res.items, &id, &stack.item)
|
||||
&& stack.crafting_enchantments().iter().all(|(other, _)| e.compatible(other, &id));
|
||||
if compatible {
|
||||
if let Some(s) = self.inventory[self.selected].as_mut() {
|
||||
s.enchant(&id, level.max(0) as u32);
|
||||
}
|
||||
tracker.track(t, true);
|
||||
} else if single {
|
||||
// getHoverName().getString(): the custom or item name, no brackets.
|
||||
return Err(err("commands.enchant.failed.incompatible", &[&stack.custom_name().map_or_else(|| self.res.names.item(&stack.item).to_string(), str::to_owned)]));
|
||||
}
|
||||
}
|
||||
Target::Mob(mob) => {
|
||||
let held = self.mobs.iter().find(|m| m.id == mob).and_then(|m| m.extra.main_hand.clone());
|
||||
if single {
|
||||
return Err(match held {
|
||||
None => err("commands.enchant.failed.itemless", &[&self.target_name(t).plain()]),
|
||||
Some(item) => err("commands.enchant.failed.incompatible", &[&self.res.names.item(&item)]),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ if single => return Err(err("commands.enchant.failed.entity", &[&self.target_name(t).plain()])),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (name, curse) = self.res.stations.enchantments.full_name(&id, level.max(0) as u32);
|
||||
let style = Style { color: Some(if curse { text::RED } else { text::GRAY }), ..Style::default() };
|
||||
let full = Text::styled(name, style);
|
||||
let message = match tracker.changed.as_slice() {
|
||||
[] => return Err(err("commands.enchant.failed", &[])),
|
||||
[one] => Text::translate("commands.enchant.success.single", &[full, self.target_name(*one)]),
|
||||
many => Text::translate("commands.enchant.success.multiple", &texts(&[full, Text::literal(many.len().to_string())])),
|
||||
};
|
||||
self.feedback(message);
|
||||
Ok(tracker.total)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user