Add champion mobs

This commit is contained in:
tyuXX 2026-07-26 02:01:56 +03:00
parent 5135a0ec47
commit fb8a41fb81
49 changed files with 762 additions and 216 deletions

View file

@ -3,7 +3,7 @@ plugins {
} }
group = 'org.gsdistance' group = 'org.gsdistance'
version = '1.5.6' version = '1.5.7'
repositories { repositories {
mavenCentral() mavenCentral()
@ -50,7 +50,7 @@ processResources {
} }
// Custom task to clean only jar files before build // Custom task to clean only jar files before build
task cleanJars(type: Delete) { tasks.register('cleanJars', Delete) {
delete fileTree('build/libs') { delete fileTree('build/libs') {
include '*.jar' include '*.jar'
exclude "${project.name}-${version}.jar" exclude "${project.name}-${version}.jar"
@ -58,5 +58,19 @@ task cleanJars(type: Delete) {
} }
// Run cleanJars before every build // Run cleanJars before every build
build.dependsOn cleanJars build.dependsOn 'cleanJars'
// Custom task to increment build.v on every build
tasks.register('incrementBuildVersion') {
doLast {
def buildFile = file('src/main/resources/build.v')
def currentVersion = buildFile.text.trim().toInteger()
def newVersion = currentVersion + 1
buildFile.text = newVersion.toString()
println "Build version incremented to: ${newVersion}"
}
}
// Run incrementBuildVersion before every build
build.dependsOn 'incrementBuildVersion'

View file

@ -115,6 +115,12 @@ public class GUtilBaseCommand implements CommandExecutor {
} }
return false; return false;
} }
case "spawnchampion" -> {
if (sender instanceof Player player) {
return SpawnChampion.subCommand(player, args);
}
return false;
}
case "sudo" -> { case "sudo" -> {
return Sudo.subCommand(sender, args); return Sudo.subCommand(sender, args);
} }

View file

@ -23,7 +23,7 @@ import java.util.stream.Stream;
public class GUtilTabCompleter implements TabCompleter { public class GUtilTabCompleter implements TabCompleter {
public static final List<String> defSubCommands = List.of("version", "setting", "spawn"); public static final List<String> defSubCommands = List.of("version", "setting", "spawn");
public static final List<String> adminSubCommands = List.of("relic", "enchant", "givecustomitem", "capability", "broadcast", "inventoryrestore", "fly", "god", "heal", "speed", "enderchest", "invsee", "addtitle", "removetitle", "unlevelentity", "sudo", "levelentity"); public static final List<String> adminSubCommands = List.of("relic", "enchant", "givecustomitem", "capability", "broadcast", "inventoryrestore", "fly", "god", "heal", "speed", "enderchest", "invsee", "addtitle", "removetitle", "unlevelentity", "sudo", "levelentity", "spawnchampion");
private CommandMap cachedCommandMap; private CommandMap cachedCommandMap;
@ -93,7 +93,8 @@ public class GUtilTabCompleter implements TabCompleter {
case "setting" -> { case "setting" -> {
return PlayerMetadata.getPlayerMetadata(player).settings.stream().toList(); return PlayerMetadata.getPlayerMetadata(player).settings.stream().toList();
} }
case "inventoryrestore", "heal", "spawn", "enderchest", "invsee", "addtitle", "removetitle", "sudo", "fly", "god" -> { case "inventoryrestore", "heal", "spawn", "enderchest", "invsee", "addtitle", "removetitle", "sudo",
"fly", "god" -> {
return Bukkit.getOnlinePlayers().stream() return Bukkit.getOnlinePlayers().stream()
.map(Player::getName) .map(Player::getName)
.filter(name -> name.toLowerCase().startsWith(args[1].toLowerCase())) .filter(name -> name.toLowerCase().startsWith(args[1].toLowerCase()))
@ -110,6 +111,13 @@ public class GUtilTabCompleter implements TabCompleter {
.filter(uuid -> uuid.toLowerCase().startsWith(args[1].toLowerCase())) .filter(uuid -> uuid.toLowerCase().startsWith(args[1].toLowerCase()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
case "spawnchampion" -> {
return java.util.Arrays.stream(org.bukkit.entity.EntityType.values())
.filter(type -> type.isSpawnable() && type.isAlive())
.map(type -> type.name().toLowerCase())
.filter(name -> name.startsWith(args[1].toLowerCase()))
.collect(Collectors.toList());
}
default -> { default -> {
return List.of(); return List.of();
} }
@ -132,7 +140,7 @@ public class GUtilTabCompleter implements TabCompleter {
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "enchant" -> { case "enchant" -> {
if (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove") || if (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove") ||
args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("has")) { args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("has")) {
return java.util.Arrays.stream(CustomEnchantment.values()) return java.util.Arrays.stream(CustomEnchantment.values())
.map(enchant -> enchant.name().toLowerCase()) .map(enchant -> enchant.name().toLowerCase())
.filter(name -> name.startsWith(args[2].toLowerCase())) .filter(name -> name.startsWith(args[2].toLowerCase()))
@ -207,6 +215,15 @@ public class GUtilTabCompleter implements TabCompleter {
.filter(option -> option.startsWith(args[2].toLowerCase())) .filter(option -> option.startsWith(args[2].toLowerCase()))
.toList(); .toList();
} }
case "spawnchampion" -> {
List<String> tiers = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
tiers.add(String.valueOf(i));
}
return tiers.stream()
.filter(tier -> tier.startsWith(args[2]))
.toList();
}
default -> { default -> {
return List.of(); return List.of();
} }
@ -242,12 +259,30 @@ public class GUtilTabCompleter implements TabCompleter {
} }
return List.of(); return List.of();
} }
case "spawnchampion" -> {
List<String> levels = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
levels.add(String.valueOf(i));
}
return levels.stream()
.filter(level -> level.startsWith(args[3]))
.toList();
}
default -> { default -> {
return List.of(); return List.of();
} }
} }
} else if (args.length == 5) { } else if (args.length == 5) {
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "spawnchampion" -> {
List<String> prestiges = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
prestiges.add(String.valueOf(i));
}
return prestiges.stream()
.filter(prestige -> prestige.startsWith(args[4]))
.toList();
}
case "relic" -> { case "relic" -> {
if (args[1].equalsIgnoreCase("set")) { if (args[1].equalsIgnoreCase("set")) {
List<String> resistances = new ArrayList<>(); List<String> resistances = new ArrayList<>();

View file

@ -18,6 +18,27 @@ public class LevelEntity {
} }
if (sender instanceof Player player) { if (sender instanceof Player player) {
// Parse optional level and prestige parameters
Integer specifiedLevel = null;
Integer specifiedPrestige = null;
if (args.length >= 3) {
try {
specifiedLevel = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Invalid level: " + args[2]);
return false;
}
}
if (args.length >= 4) {
try {
specifiedPrestige = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Invalid prestige: " + args[3]);
return false;
}
}
if (args.length < 2) { if (args.length < 2) {
// Force leveling on entity player is looking at // Force leveling on entity player is looking at
RayTraceResult rayTrace = player.getWorld().rayTraceEntities(player.getEyeLocation(), player.getEyeLocation().getDirection(), 5); RayTraceResult rayTrace = player.getWorld().rayTraceEntities(player.getEyeLocation(), player.getEyeLocation().getDirection(), 5);
@ -26,7 +47,7 @@ public class LevelEntity {
sender.sendMessage(ChatColor.RED + "No entity found in range (5 blocks). Specify an entity UUID or look at an entity."); sender.sendMessage(ChatColor.RED + "No entity found in range (5 blocks). Specify an entity UUID or look at an entity.");
return false; return false;
} }
return applyLeveling(sender, targetEntity); return applyLeveling(sender, targetEntity, specifiedLevel, specifiedPrestige);
} else { } else {
// Force leveling by UUID // Force leveling by UUID
try { try {
@ -42,7 +63,7 @@ public class LevelEntity {
sender.sendMessage(ChatColor.RED + "Entity with UUID " + args[1] + " not found in current world."); sender.sendMessage(ChatColor.RED + "Entity with UUID " + args[1] + " not found in current world.");
return false; return false;
} }
return applyLeveling(sender, targetEntity); return applyLeveling(sender, targetEntity, specifiedLevel, specifiedPrestige);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Invalid UUID format: " + args[1]); sender.sendMessage(ChatColor.RED + "Invalid UUID format: " + args[1]);
return false; return false;
@ -54,24 +75,33 @@ public class LevelEntity {
} }
} }
private static boolean applyLeveling(CommandSender sender, Entity entity) { private static boolean applyLeveling(CommandSender sender, Entity entity, Integer specifiedLevel, Integer specifiedPrestige) {
// Register entity in the registry // Register entity in the registry
CustomEntityManager.registerEntity(entity); CustomEntityManager.registerEntity(entity);
// Get or create metadata and apply leveling // Get or create metadata and apply leveling
EntityMetadata metadata = EntityMetadata.getEntityMetadata(entity); EntityMetadata metadata = EntityMetadata.getEntityMetadata(entity);
// Override level/prestige if specified
if (specifiedLevel != null) {
metadata.level = specifiedLevel;
}
if (specifiedPrestige != null) {
metadata.prestige = specifiedPrestige;
}
if (entity instanceof LivingEntity livingEntity) { if (entity instanceof LivingEntity livingEntity) {
// Force re-apply leveling even if already leveled // Force re-apply leveling even if already leveled
if (metadata.level > 1 || metadata.prestige > 1) { try {
// Re-apply to refresh stats java.lang.reflect.Method applyLevelling = EntityMetadata.class.getDeclaredMethod("applyLevelling", LivingEntity.class, EntityMetadata.class);
try { applyLevelling.setAccessible(true);
java.lang.reflect.Method applyLevelling = EntityMetadata.class.getDeclaredMethod("applyLevelling", LivingEntity.class, EntityMetadata.class); applyLevelling.invoke(null, livingEntity, metadata);
applyLevelling.setAccessible(true); // Save attribute values after applying
applyLevelling.invoke(null, livingEntity, metadata); java.lang.reflect.Method saveAttributeValues = EntityMetadata.class.getDeclaredMethod("saveAttributeValues", LivingEntity.class, EntityMetadata.class);
} catch (Exception e) { saveAttributeValues.setAccessible(true);
sender.sendMessage(ChatColor.YELLOW + "Warning: Could not re-apply leveling via reflection."); saveAttributeValues.invoke(null, livingEntity, metadata);
} } catch (Exception e) {
sender.sendMessage(ChatColor.YELLOW + "Warning: Could not re-apply leveling via reflection.");
} }
sender.sendMessage(ChatColor.GREEN + "Forced leveling on entity: " + entity.getType().name() + " (Level: " + metadata.level + ", Prestige: " + metadata.prestige + ")"); sender.sendMessage(ChatColor.GREEN + "Forced leveling on entity: " + entity.getType().name() + " (Level: " + metadata.level + ", Prestige: " + metadata.prestige + ")");

View file

@ -0,0 +1,167 @@
package org.gsdistance.grimmsServer.Commands.GUtilCommand;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.gsdistance.grimmsServer.Constructable.Data;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityAbility;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityAffix;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityMetadata;
import org.gsdistance.grimmsServer.Manage.CustomEntityManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SpawnChampion {
public static boolean subCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission("grimmsserver.util.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return false;
}
if (sender instanceof Player player) {
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: /gutil spawnchampion <entity_type> [tier] [level] [prestige]");
sender.sendMessage(ChatColor.YELLOW + "Example: /gutil spawnchampion ZOMBIE 3 50 2");
return false;
}
// Parse entity type
EntityType entityType;
try {
entityType = EntityType.valueOf(args[1].toUpperCase());
} catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Invalid entity type: " + args[1]);
return false;
}
if (!entityType.isSpawnable() || !entityType.isAlive()) {
sender.sendMessage(ChatColor.RED + "Entity type must be a living spawnable entity.");
return false;
}
// Parse optional parameters
int tier = 1;
int level = 1;
int prestige = 1;
if (args.length >= 3) {
try {
tier = Integer.parseInt(args[2]);
if (tier < 1 || tier > 5) {
sender.sendMessage(ChatColor.RED + "Tier must be between 1 and 5.");
return false;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Invalid tier: " + args[2]);
return false;
}
}
if (args.length >= 4) {
try {
level = Integer.parseInt(args[3]);
if (level < 1) {
sender.sendMessage(ChatColor.RED + "Level must be at least 1.");
return false;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Invalid level: " + args[3]);
return false;
}
}
if (args.length >= 5) {
try {
prestige = Integer.parseInt(args[4]);
if (prestige < 1) {
sender.sendMessage(ChatColor.RED + "Prestige must be at least 1.");
return false;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Invalid prestige: " + args[4]);
return false;
}
}
// Spawn the entity
LivingEntity entity = (LivingEntity) player.getWorld().spawnEntity(player.getLocation(), entityType);
// Set a temporary tag to prevent EntitySpawnEvent from processing this entity
entity.setMetadata("champion_spawn", new org.bukkit.metadata.FixedMetadataValue(org.gsdistance.grimmsServer.GrimmsServer.instance, true));
// Register entity
CustomEntityManager.registerEntity(entity);
// Create metadata manually to bypass automatic leveling
EntityMetadata metadata = new EntityMetadata(entity);
// Clear any affixes/abilities that the constructor might have set
metadata.affixes.clear();
metadata.abilities.clear();
// Override champion tier, level, and prestige
metadata.championTier = tier;
metadata.level = level;
metadata.prestige = prestige;
// Store in session data to prevent recreation
org.gsdistance.grimmsServer.Data.PerSessionDataStorage.dataStore.put("entityMetadata-" + entity.getUniqueId(), Data.of(metadata, EntityMetadata.class));
// Select affixes based on tier
int numAffixes = Math.min(tier, org.gsdistance.grimmsServer.Constructable.Entity.EntityAffixes.affixes.size());
List<EntityAffix> availableAffixes = new ArrayList<>(org.gsdistance.grimmsServer.Constructable.Entity.EntityAffixes.affixes.keySet());
Collections.shuffle(availableAffixes);
for (int i = 0; i < numAffixes; i++) {
metadata.affixes.add(availableAffixes.get(i));
}
// Select abilities based on tier
metadata.abilities.clear();
int numAbilities = Math.max(0, tier - 1);
if (numAbilities > 0) {
List<EntityAbility> availableAbilities = new ArrayList<>(org.gsdistance.grimmsServer.Constructable.Entity.EntityAbilities.abilities.keySet());
Collections.shuffle(availableAbilities);
for (int i = 0; i < Math.min(numAbilities, availableAbilities.size()); i++) {
metadata.abilities.add(availableAbilities.get(i));
}
}
// Apply leveling and champion effects
try {
// Use applyAttributeModifiers directly to avoid recalculation of level/prestige
java.lang.reflect.Method applyAttributeModifiers = EntityMetadata.class.getDeclaredMethod("applyAttributeModifiers", LivingEntity.class, EntityMetadata.class);
applyAttributeModifiers.setAccessible(true);
applyAttributeModifiers.invoke(null, entity, metadata);
java.lang.reflect.Method saveAttributeValues = EntityMetadata.class.getDeclaredMethod("saveAttributeValues", LivingEntity.class, EntityMetadata.class);
saveAttributeValues.setAccessible(true);
saveAttributeValues.invoke(null, entity, metadata);
java.lang.reflect.Method applyChampionAffixes = EntityMetadata.class.getDeclaredMethod("applyChampionAffixes", LivingEntity.class, EntityMetadata.class);
applyChampionAffixes.setAccessible(true);
applyChampionAffixes.invoke(null, entity, metadata);
} catch (Exception e) {
sender.sendMessage(ChatColor.YELLOW + "Warning: Could not apply effects via reflection.");
e.printStackTrace();
}
// Save metadata
metadata.saveToFile();
sender.sendMessage(ChatColor.GREEN + "Spawned champion " + entityType.name() + " (Tier: " + tier + ", Level: " + level + ", Prestige: " + prestige + ")");
sender.sendMessage(ChatColor.YELLOW + "Affixes: " + metadata.affixes.size() + ", Abilities: " + metadata.abilities.size());
return true;
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to use this command.");
return false;
}
}
}

View file

@ -62,8 +62,8 @@ public class UnlevelEntity {
// Remove metadata file // Remove metadata file
try { try {
java.io.File metadataFile = new java.io.File( java.io.File metadataFile = new java.io.File(
org.gsdistance.grimmsServer.GrimmsServer.instance.getDataFolder(), org.gsdistance.grimmsServer.GrimmsServer.instance.getDataFolder(),
"entityMetadata/" + entity.getUniqueId() + ".json" "entityMetadata/" + entity.getUniqueId() + ".json"
); );
if (metadataFile.exists()) { if (metadataFile.exists()) {
metadataFile.delete(); metadataFile.delete();

View file

@ -3,11 +3,30 @@ package org.gsdistance.grimmsServer.Commands.GUtilCommand;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.gsdistance.grimmsServer.GrimmsServer; import org.gsdistance.grimmsServer.GrimmsServer;
import java.io.InputStream;
public class Version { public class Version {
private static String cachedBuildVersion = null;
private static String getBuildVersion() {
if (cachedBuildVersion == null) {
try (InputStream is = GrimmsServer.instance.getResource("build.v")) {
if (is != null) {
cachedBuildVersion = new String(is.readAllBytes()).trim();
} else {
cachedBuildVersion = "unknown";
}
} catch (Exception e) {
cachedBuildVersion = "error";
}
}
return cachedBuildVersion;
}
public static boolean subCommand(CommandSender sender, String[] args) { public static boolean subCommand(CommandSender sender, String[] args) {
String name = GrimmsServer.instance.getDescription().getPrefix(); String name = GrimmsServer.instance.getDescription().getPrefix();
sender.sendMessage(name + " v" + GrimmsServer.instance.getDescription().getVersion()); sender.sendMessage(name + " v" + GrimmsServer.instance.getDescription().getVersion() + " (build " + getBuildVersion() + ")");
return true; return true;
} }
} }

View file

@ -43,7 +43,10 @@ public enum ConfigKey {
LEVELLED_MOBS_SEARCH_RADIUS("levelled_mobs_search_radius", 50), LEVELLED_MOBS_SEARCH_RADIUS("levelled_mobs_search_radius", 50),
LEVELLED_MOBS_HEALTH_DIVISOR("levelled_mobs_health_divisor", 25.0), LEVELLED_MOBS_HEALTH_DIVISOR("levelled_mobs_health_divisor", 25.0),
LEVELLED_MOBS_ARMOR_DIVISOR("levelled_mobs_armor_divisor", 2.0), LEVELLED_MOBS_ARMOR_DIVISOR("levelled_mobs_armor_divisor", 2.0),
LEVELLED_MOBS_BLACKLIST("levelled_mobs_blacklist", new ArrayList<String>()); LEVELLED_MOBS_BLACKLIST("levelled_mobs_blacklist", new ArrayList<String>()),
CHAMPION_MOBS_ENABLED("champion_mobs_enabled", true),
CHAMPION_MOBS_CHANCE("champion_mobs_chance", 0.01),
CHAMPION_MOBS_BOSSBAR_RADIUS("champion_mobs_bossbar_radius", 50);
private final String key; private final String key;
private final Object defaultValue; private final Object defaultValue;

View file

@ -1,12 +1,70 @@
package org.gsdistance.grimmsServer.Constructable.Entity; package org.gsdistance.grimmsServer.Constructable.Entity;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Map; import java.util.Map;
public class EntityAbilities { public class EntityAbilities {
// Key - Ability // Key - Ability
// Value - Tier // Value - Tier (higher tier = stronger effect)
public static final Map<EntityAbility, Integer> abilities = Map.ofEntries( public static final Map<EntityAbility, Integer> abilities = Map.ofEntries(
Map.entry(new EntityAbility("test", Integer.MAX_VALUE, (entity) -> null), 99) // Heal self - heals 20% of max health every 10 seconds
Map.entry(new EntityAbility("heal_self", 200, (entity) -> {
double maxHealth = entity.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH).getValue();
double healAmount = maxHealth * 0.2;
entity.setHealth(Math.min(maxHealth, entity.getHealth() + healAmount));
return null;
}), 1),
// Reflect damage - reflects 50% of damage taken (handled in damage event)
Map.entry(new EntityAbility("reflect_damage", 0, (entity) -> {
// This is a passive ability handled in damage events
return null;
}), 1),
// Summon reinforcements - summons 2 mobs of same type every 30 seconds
Map.entry(new EntityAbility("summon_reinforcements", 600, (entity) -> {
Location loc = entity.getLocation();
for (int i = 0; i < 2; i++) {
LivingEntity reinforcement = (LivingEntity) loc.getWorld().spawnEntity(loc, entity.getType());
reinforcement.setCustomName("Reinforcement");
}
return null;
}), 1),
// Teleport - teleports to random nearby location every 15 seconds
Map.entry(new EntityAbility("teleport", 900, (entity) -> {
Location loc = entity.getLocation();
Location newLoc = new Location(
loc.getWorld(),
loc.getX() + (Math.random() - 0.5) * 10,
loc.getY(),
loc.getZ() + (Math.random() - 0.5) * 10
);
entity.teleport(newLoc);
return null;
}), 1),
// Rage - increases attack speed and damage when low health
Map.entry(new EntityAbility("rage", 100, (entity) -> {
if (entity.getHealth() < entity.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH).getValue() * 0.3) {
entity.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, 100, 1));
entity.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 100, 2));
}
return null;
}), 1),
// Fire burst - ignites nearby enemies every 20 seconds
Map.entry(new EntityAbility("fire_burst", 400, (entity) -> {
entity.getNearbyEntities(5, 5, 5).forEach(nearby -> {
if (nearby instanceof LivingEntity && nearby != entity) {
nearby.setFireTicks(60);
}
});
return null;
}), 1)
); );
// Could add abilities such as heal self, reflect damage, summon reinforcements etc.
} }

View file

@ -1,13 +1,62 @@
package org.gsdistance.grimmsServer.Constructable.Entity; package org.gsdistance.grimmsServer.Constructable.Entity;
import org.bukkit.attribute.Attribute;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Map; import java.util.Map;
public class EntityAffixes { public class EntityAffixes {
// Key - Affix // Key - Affix
// Value - Tier // Value - Tier (higher tier = stronger effect)
public static final Map<EntityAffix, Integer> affixes = Map.ofEntries( public static final Map<EntityAffix, Integer> affixes = Map.ofEntries(
Map.entry(new EntityAffix("test", (entity) -> null), 99) // Health bonus - increases max health by tier * 50%
); Map.entry(new EntityAffix("healthy", (entity) -> {
if (entity.getAttribute(Attribute.MAX_HEALTH) != null) {
double base = entity.getAttribute(Attribute.MAX_HEALTH).getBaseValue();
entity.getAttribute(Attribute.MAX_HEALTH).setBaseValue(base * 1.5);
entity.setHealth(entity.getAttribute(Attribute.MAX_HEALTH).getValue());
}
return null;
}), 1),
// Could add affixes such as health bonus, armor bonus and damage bonus // Armor bonus - increases armor by tier * 5
Map.entry(new EntityAffix("armored", (entity) -> {
if (entity.getAttribute(Attribute.ARMOR) != null) {
double base = entity.getAttribute(Attribute.ARMOR).getBaseValue();
entity.getAttribute(Attribute.ARMOR).setBaseValue(base + 5);
}
return null;
}), 1),
// Damage bonus - increases attack damage by tier * 20%
Map.entry(new EntityAffix("strong", (entity) -> {
if (entity.getAttribute(Attribute.ATTACK_DAMAGE) != null) {
double base = entity.getAttribute(Attribute.ATTACK_DAMAGE).getBaseValue();
entity.getAttribute(Attribute.ATTACK_DAMAGE).setBaseValue(base * 1.2);
}
return null;
}), 1),
// Speed bonus - gives speed effect
Map.entry(new EntityAffix("swift", (entity) -> {
entity.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1));
return null;
}), 1),
// Fire resistance
Map.entry(new EntityAffix("fiery", (entity) -> {
entity.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0));
return null;
}), 1),
// Knockback resistance
Map.entry(new EntityAffix("heavy", (entity) -> {
entity.addPotionEffect(new PotionEffect(PotionEffectType.SLOWNESS, Integer.MAX_VALUE, 0));
if (entity.getAttribute(Attribute.KNOCKBACK_RESISTANCE) != null) {
entity.getAttribute(Attribute.KNOCKBACK_RESISTANCE).setBaseValue(0.5);
}
return null;
}), 1)
);
} }

View file

@ -28,24 +28,53 @@ public class EntityMetadata {
public int prestige = 1; public int prestige = 1;
public String originalName; public String originalName;
public List<EntityAffix> affixes = new ArrayList<>(); public List<EntityAffix> affixes = new ArrayList<>();
public List<EntityAbility> abilities = new ArrayList<>();
public int championTier = 0; public int championTier = 0;
// Store base values after first leveling to prevent snowballing on chunk reload // Store base values after first leveling to prevent snowballing on chunk reload
public double maxHealth = 0; public double maxHealth = 0;
public double armor = 0; public double armor = 0;
public double armorToughness = 0; public double armorToughness = 0;
public double attackDamage = 0; public double attackDamage = 0;
// Bossbar for champion mobs
public transient org.bukkit.boss.BossBar bossBar;
// Ability cooldown tracking (ability UUID -> last execution time in ticks)
public transient java.util.Map<UUID, Long> abilityCooldowns = new java.util.HashMap<>();
public EntityMetadata(Entity entity) { public EntityMetadata(Entity entity) {
this.uuid = entity.getUniqueId(); this.uuid = entity.getUniqueId();
this.timestamp = LocalDateTime.now().toString(); this.timestamp = LocalDateTime.now().toString();
this.originalName = entity.getName(); this.originalName = entity.getName();
while(Math.random() < 0.01){
this.championTier++;
}
if(championTier > 0){
while(Math.random() < 0.5){
// TODO - Add a random affix with tier equal to or less than the champion tier
// Determine if this entity becomes a champion
Boolean championEnabled = ActiveConfig.getConfigValue(ConfigKey.CHAMPION_MOBS_ENABLED, Boolean.class);
Double championChance = ActiveConfig.getConfigValue(ConfigKey.CHAMPION_MOBS_CHANCE, Double.class);
if (championEnabled != null && championEnabled && championChance != null && Math.random() < championChance) {
// Roll for champion tier (1-5)
while (Math.random() < 0.5 && this.championTier < 5) {
this.championTier++;
}
// Select random affixes based on champion tier
if (this.championTier > 0) {
int numAffixes = Math.min(this.championTier, EntityAffixes.affixes.size());
List<EntityAffix> availableAffixes = new ArrayList<>(EntityAffixes.affixes.keySet());
java.util.Collections.shuffle(availableAffixes);
for (int i = 0; i < numAffixes; i++) {
this.affixes.add(availableAffixes.get(i));
}
// Select random abilities based on champion tier (higher tiers get more abilities)
int numAbilities = Math.max(0, this.championTier - 1);
if (numAbilities > 0) {
List<EntityAbility> availableAbilities = new ArrayList<>(EntityAbilities.abilities.keySet());
java.util.Collections.shuffle(availableAbilities);
for (int i = 0; i < Math.min(numAbilities, availableAbilities.size()); i++) {
this.abilities.add(availableAbilities.get(i));
}
}
} }
} }
} }
@ -69,6 +98,11 @@ public class EntityMetadata {
} }
public void deleteFromFile() { public void deleteFromFile() {
// Remove bossbar if present
if (this.bossBar != null) {
this.bossBar.removeAll();
this.bossBar = null;
}
GrimmsServer.pds.deleteData(this.uuid.toString() + ".json", "entityMetadata"); GrimmsServer.pds.deleteData(this.uuid.toString() + ".json", "entityMetadata");
PerSessionDataStorage.dataStore.remove("entityMetadata-" + this.uuid); PerSessionDataStorage.dataStore.remove("entityMetadata-" + this.uuid);
} }
@ -87,6 +121,7 @@ public class EntityMetadata {
// Apply levelling when metadata is first created // Apply levelling when metadata is first created
if (entity instanceof LivingEntity && entity.getType() != EntityType.PLAYER) { if (entity instanceof LivingEntity && entity.getType() != EntityType.PLAYER) {
applyLevelling((LivingEntity) entity, metadata); applyLevelling((LivingEntity) entity, metadata);
applyChampionAffixes((LivingEntity) entity, metadata);
} }
metadata.saveToFile(); metadata.saveToFile();
} else { } else {
@ -97,6 +132,7 @@ public class EntityMetadata {
// Re-apply levelling based on saved level/prestige when loading from disk (chunk reload) // Re-apply levelling based on saved level/prestige when loading from disk (chunk reload)
if (entity instanceof LivingEntity && entity.getType() != EntityType.PLAYER) { if (entity instanceof LivingEntity && entity.getType() != EntityType.PLAYER) {
applyAttributeModifiers((LivingEntity) entity, metadata); applyAttributeModifiers((LivingEntity) entity, metadata);
applyChampionAffixes((LivingEntity) entity, metadata);
} }
} }
@ -178,6 +214,60 @@ public class EntityMetadata {
} }
} }
private static void applyChampionAffixes(LivingEntity livingEntity, EntityMetadata metadata) {
// Apply all champion affixes to the entity
for (EntityAffix affix : metadata.affixes) {
affix.effect().apply(livingEntity);
}
// Create bossbar for champion mobs
if (metadata.championTier > 0) {
createBossBar(livingEntity, metadata);
}
}
private static void createBossBar(LivingEntity livingEntity, EntityMetadata metadata) {
// Remove existing bossbar if present
if (metadata.bossBar != null) {
metadata.bossBar.removeAll();
}
// Create new bossbar
String title = ChatColor.GOLD + "★ Champion " + metadata.championTier + " ★ " + ChatColor.WHITE + livingEntity.getName();
metadata.bossBar = org.bukkit.Bukkit.createBossBar(title, org.bukkit.boss.BarColor.RED, org.bukkit.boss.BarStyle.SEGMENTED_10);
updateBossBarHealth(livingEntity, metadata);
// Add nearby players to bossbar
Integer radius = ActiveConfig.getConfigValue(ConfigKey.CHAMPION_MOBS_BOSSBAR_RADIUS, Integer.class);
if (radius == null) radius = 50;
for (org.bukkit.entity.Player player : livingEntity.getWorld().getPlayers()) {
if (player.getLocation().distance(livingEntity.getLocation()) <= radius) {
metadata.bossBar.addPlayer(player);
}
}
}
public static void updateBossBarHealth(LivingEntity livingEntity, EntityMetadata metadata) {
if (metadata.bossBar != null && livingEntity.getAttribute(Attribute.MAX_HEALTH) != null) {
double maxHealth = livingEntity.getAttribute(Attribute.MAX_HEALTH).getValue();
double currentHealth = livingEntity.getHealth();
metadata.bossBar.setProgress(Math.max(0, Math.min(1, currentHealth / maxHealth)));
}
}
public void executeAbilities(LivingEntity livingEntity, EntityMetadata metadata, long currentTick) {
for (EntityAbility ability : metadata.abilities) {
UUID abilityId = java.util.UUID.nameUUIDFromBytes(ability.id().getBytes());
Long lastExecution = metadata.abilityCooldowns.get(abilityId);
if (lastExecution == null || currentTick - lastExecution >= ability.cooldownTicks()) {
ability.effect().apply(livingEntity);
metadata.abilityCooldowns.put(abilityId, currentTick);
}
}
}
private static void applyAttributeModifiers(LivingEntity livingEntity, EntityMetadata metadata) { private static void applyAttributeModifiers(LivingEntity livingEntity, EntityMetadata metadata) {
Boolean enabled = ActiveConfig.getConfigValue(ConfigKey.LEVELLED_MOBS_ENABLED, Boolean.class); Boolean enabled = ActiveConfig.getConfigValue(ConfigKey.LEVELLED_MOBS_ENABLED, Boolean.class);
if (enabled == null || !enabled) { if (enabled == null || !enabled) {
@ -263,7 +353,11 @@ public class EntityMetadata {
} }
} }
// Set custom name with level and health bar // Set custom name with level and health bar (skip for champion mobs)
if (metadata.championTier > 0) {
return;
}
ChatColor levelColor = getLevelColor(finalLevel); ChatColor levelColor = getLevelColor(finalLevel);
double maxHealth = livingEntity.getAttribute(Attribute.MAX_HEALTH).getValue(); double maxHealth = livingEntity.getAttribute(Attribute.MAX_HEALTH).getValue();

View file

@ -23,8 +23,9 @@ public class CustomEnchantmentHandler {
/** /**
* Add a custom enchantment to the item * Add a custom enchantment to the item
*
* @param enchantment The enchantment to add * @param enchantment The enchantment to add
* @param level The level of the enchantment * @param level The level of the enchantment
* @return true if successful, false if level exceeds max or enchantment already exists * @return true if successful, false if level exceeds max or enchantment already exists
*/ */
public boolean addEnchantment(CustomEnchantment enchantment, int level) { public boolean addEnchantment(CustomEnchantment enchantment, int level) {
@ -43,6 +44,7 @@ public class CustomEnchantmentHandler {
/** /**
* Remove a custom enchantment from the item * Remove a custom enchantment from the item
*
* @param enchantment The enchantment to remove * @param enchantment The enchantment to remove
* @return true if the enchantment was removed, false if it didn't exist * @return true if the enchantment was removed, false if it didn't exist
*/ */
@ -61,6 +63,7 @@ public class CustomEnchantmentHandler {
/** /**
* Check if the item has a specific custom enchantment * Check if the item has a specific custom enchantment
*
* @param enchantment The enchantment to check for * @param enchantment The enchantment to check for
* @return true if the item has the enchantment with level > 0 * @return true if the item has the enchantment with level > 0
*/ */
@ -70,6 +73,7 @@ public class CustomEnchantmentHandler {
/** /**
* Get the level of a custom enchantment on the item * Get the level of a custom enchantment on the item
*
* @param enchantment The enchantment to check * @param enchantment The enchantment to check
* @return The level of the enchantment, or 0 if not present * @return The level of the enchantment, or 0 if not present
*/ */
@ -81,6 +85,7 @@ public class CustomEnchantmentHandler {
/** /**
* Get all custom enchantments on the item * Get all custom enchantments on the item
*
* @return A map of enchantments to their levels * @return A map of enchantments to their levels
*/ */
public Map<CustomEnchantment, Integer> getAllEnchantments() { public Map<CustomEnchantment, Integer> getAllEnchantments() {
@ -98,8 +103,9 @@ public class CustomEnchantmentHandler {
/** /**
* Set the level of an enchantment (overwrites existing) * Set the level of an enchantment (overwrites existing)
*
* @param enchantment The enchantment to set * @param enchantment The enchantment to set
* @param level The level to set * @param level The level to set
* @return true if successful, false if level is invalid * @return true if successful, false if level is invalid
*/ */
public boolean setEnchantmentLevel(CustomEnchantment enchantment, int level) { public boolean setEnchantmentLevel(CustomEnchantment enchantment, int level) {
@ -123,6 +129,7 @@ public class CustomEnchantmentHandler {
/** /**
* Check if the item has any custom enchantments * Check if the item has any custom enchantments
*
* @return true if the item has at least one custom enchantment * @return true if the item has at least one custom enchantment
*/ */
public boolean hasAnyEnchantments() { public boolean hasAnyEnchantments() {

View file

@ -61,29 +61,29 @@ public class CustomItemRegistry {
public static void registerGunTypes() { public static void registerGunTypes() {
// Register pistol // Register pistol
registerCustomItem("gun_pistol", (itemStack) -> registerCustomItem("gun_pistol", (itemStack) ->
new GunItem("gun_pistol", itemStack, "Pistol", 5.0, 2.0, 12, Material.IRON_NUGGET)); new GunItem("gun_pistol", itemStack, "Pistol", 5.0, 2.0, 12, Material.IRON_NUGGET));
// Register rifle // Register rifle
registerCustomItem("gun_rifle", (itemStack) -> registerCustomItem("gun_rifle", (itemStack) ->
new GunItem("gun_rifle", itemStack, "Rifle", 8.0, 4.0, 30, Material.GOLD_NUGGET)); new GunItem("gun_rifle", itemStack, "Rifle", 8.0, 4.0, 30, Material.GOLD_NUGGET));
// Register shotgun // Register shotgun
registerCustomItem("gun_shotgun", (itemStack) -> registerCustomItem("gun_shotgun", (itemStack) ->
new GunItem("gun_shotgun", itemStack, "Shotgun", 15.0, 1.0, 8, Material.IRON_INGOT)); new GunItem("gun_shotgun", itemStack, "Shotgun", 15.0, 1.0, 8, Material.IRON_INGOT));
} }
public static void registerAmmoTypes() { public static void registerAmmoTypes() {
// Register pistol ammo // Register pistol ammo
registerCustomItem("ammo_pistol", (itemStack) -> registerCustomItem("ammo_pistol", (itemStack) ->
new AmmoItem("ammo_pistol", itemStack, "Pistol", 30, Material.IRON_NUGGET)); new AmmoItem("ammo_pistol", itemStack, "Pistol", 30, Material.IRON_NUGGET));
// Register rifle ammo // Register rifle ammo
registerCustomItem("ammo_rifle", (itemStack) -> registerCustomItem("ammo_rifle", (itemStack) ->
new AmmoItem("ammo_rifle", itemStack, "Rifle", 60, Material.GOLD_NUGGET)); new AmmoItem("ammo_rifle", itemStack, "Rifle", 60, Material.GOLD_NUGGET));
// Register shotgun ammo // Register shotgun ammo
registerCustomItem("ammo_shotgun", (itemStack) -> registerCustomItem("ammo_shotgun", (itemStack) ->
new AmmoItem("ammo_shotgun", itemStack, "Shotgun", 16, Material.IRON_INGOT)); new AmmoItem("ammo_shotgun", itemStack, "Shotgun", 16, Material.IRON_INGOT));
} }
public static Set<String> getRegisteredItemIds() { public static Set<String> getRegisteredItemIds() {

View file

@ -45,8 +45,8 @@ public class GunItem extends CustomItem {
@Override @Override
public String getDescription() { public String getDescription() {
return ChatColor.GRAY + "Damage: " + ChatColor.RED + this.damage + return ChatColor.GRAY + "Damage: " + ChatColor.RED + this.damage +
ChatColor.GRAY + " | Fire Rate: " + ChatColor.YELLOW + this.fireRate + "/s" + ChatColor.GRAY + " | Fire Rate: " + ChatColor.YELLOW + this.fireRate + "/s" +
ChatColor.GRAY + " | Ammo: " + ChatColor.AQUA + this.maxAmmo; ChatColor.GRAY + " | Ammo: " + ChatColor.AQUA + this.maxAmmo;
} }
// Getters for gun properties // Getters for gun properties

View file

@ -36,7 +36,7 @@ public class CustomRelicItem extends CustomItem {
}; };
String displayName = tierColor + (relicType.isEmpty() ? "" : relicType.substring(0, 1).toUpperCase() + relicType.substring(1)) + String displayName = tierColor + (relicType.isEmpty() ? "" : relicType.substring(0, 1).toUpperCase() + relicType.substring(1)) +
" Relic " + ChatColor.GRAY + "[" + tierColor + "Tier " + tier + ChatColor.GRAY + "]"; " Relic " + ChatColor.GRAY + "[" + tierColor + "Tier " + tier + ChatColor.GRAY + "]";
meta.setDisplayName(displayName); meta.setDisplayName(displayName);
setItemMeta(meta); setItemMeta(meta);
} }

View file

@ -26,27 +26,27 @@ public class PluginDataStorage {
private Gson createGson() { private Gson createGson() {
return new GsonBuilder() return new GsonBuilder()
.disableInnerClassSerialization() .disableInnerClassSerialization()
.excludeFieldsWithModifiers(java.lang.reflect.Modifier.STATIC, java.lang.reflect.Modifier.TRANSIENT) .excludeFieldsWithModifiers(java.lang.reflect.Modifier.STATIC, java.lang.reflect.Modifier.TRANSIENT)
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
@Override @Override
public boolean shouldSkipField(FieldAttributes f) { public boolean shouldSkipField(FieldAttributes f) {
// Skip fields that contain Optional or other problematic types // Skip fields that contain Optional or other problematic types
String typeName = f.getDeclaredType().getTypeName(); String typeName = f.getDeclaredType().getTypeName();
return typeName.contains("java.util.Optional") || return typeName.contains("java.util.Optional") ||
typeName.contains("java.lang.reflect") || typeName.contains("java.lang.reflect") ||
typeName.contains("java.security") || typeName.contains("java.security") ||
typeName.contains("java.util.concurrent") || typeName.contains("java.util.concurrent") ||
typeName.contains("org.bukkit"); typeName.contains("org.bukkit");
} }
@Override @Override
public boolean shouldSkipClass(Class<?> clazz) { public boolean shouldSkipClass(Class<?> clazz) {
// Skip all Bukkit classes from reflection // Skip all Bukkit classes from reflection
return clazz.getName().startsWith("org.bukkit"); return clazz.getName().startsWith("org.bukkit");
} }
}) })
.create(); .create();
} }
public boolean exists(String fileName, String addedPath) { public boolean exists(String fileName, String addedPath) {

View file

@ -0,0 +1,26 @@
package org.gsdistance.grimmsServer.Events.Listeners;
import org.bukkit.entity.LivingEntity;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityMetadata;
import org.gsdistance.grimmsServer.GrimmsServer;
import org.gsdistance.grimmsServer.Manage.CustomEntityManager;
public class ChampionTickEvent {
public ChampionTickEvent() {
}
public static void Event() {
// Only process entities in loaded chunks to avoid unnecessary processing
for (java.util.UUID entityUuid : CustomEntityManager.currentRegistry) {
org.bukkit.entity.Entity entity = GrimmsServer.instance.getServer().getEntity(entityUuid);
if (entity instanceof LivingEntity && entity.isValid()) {
EntityMetadata metadata = EntityMetadata.getEntityMetadata(entity);
if (metadata != null && metadata.championTier > 0 && !metadata.abilities.isEmpty()) {
metadata.executeAbilities((LivingEntity) entity, metadata, ServerTickEvent.ticks);
// Update bossbar health
EntityMetadata.updateBossBarHealth((LivingEntity) entity, metadata);
}
}
}
}
}

View file

@ -2,6 +2,8 @@ package org.gsdistance.grimmsServer.Events.Listeners;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityAbility;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityMetadata;
import org.gsdistance.grimmsServer.Constructable.Item.ItemLevelHandler; import org.gsdistance.grimmsServer.Constructable.Item.ItemLevelHandler;
import org.gsdistance.grimmsServer.Data.StaticLists; import org.gsdistance.grimmsServer.Data.StaticLists;
import org.gsdistance.grimmsServer.Events.Registers.CustomEntityDamageByEntityRegister; import org.gsdistance.grimmsServer.Events.Registers.CustomEntityDamageByEntityRegister;
@ -14,6 +16,23 @@ public class CustomEntityDamageByEntityEvent {
// This event is only called for non-player entities being damaged // This event is only called for non-player entities being damaged
org.bukkit.event.entity.EntityDamageByEntityEvent originalEvent = event.getOriginalEvent(); org.bukkit.event.entity.EntityDamageByEntityEvent originalEvent = event.getOriginalEvent();
// Handle champion abilities
EntityMetadata metadata = EntityMetadata.getEntityMetadata(originalEvent.getEntity());
if (metadata != null && metadata.championTier > 0) {
// Check for reflect_damage ability
for (EntityAbility ability : metadata.abilities) {
if (ability.id().equals("reflect_damage") && originalEvent.getDamager() instanceof org.bukkit.entity.LivingEntity) {
// Reflect 50% of damage back to the damager
double reflectedDamage = originalEvent.getDamage() * 0.5;
((org.bukkit.entity.LivingEntity) originalEvent.getDamager()).damage(reflectedDamage, originalEvent.getEntity());
}
}
// Update bossbar health when entity takes damage
if (originalEvent.getEntity() instanceof org.bukkit.entity.LivingEntity) {
EntityMetadata.updateBossBarHealth((org.bukkit.entity.LivingEntity) originalEvent.getEntity(), metadata);
}
}
// Item XP logic for damaging non-player entities // Item XP logic for damaging non-player entities
if (originalEvent.getDamager().getType() == EntityType.PLAYER && !StaticLists.xpBlacklist.contains(originalEvent.getEntityType()) && ItemLevelHandler.isItemLevelable(((Player) originalEvent.getDamager()).getInventory().getItemInMainHand())) { if (originalEvent.getDamager().getType() == EntityType.PLAYER && !StaticLists.xpBlacklist.contains(originalEvent.getEntityType()) && ItemLevelHandler.isItemLevelable(((Player) originalEvent.getDamager()).getInventory().getItemInMainHand())) {
ItemLevelHandler.getLevelHandler((Player) originalEvent.getDamager()).addXp(originalEvent.getDamage()); ItemLevelHandler.getLevelHandler((Player) originalEvent.getDamager()).addXp(originalEvent.getDamage());

View file

@ -16,7 +16,6 @@ public class EntityDamageByEntityEvent {
if (!GAuthBaseCommand.isLoggedIn(player)) { if (!GAuthBaseCommand.isLoggedIn(player)) {
player.sendMessage(ChatColor.RED + "You must login with /gAuth login <password> to perform this action."); player.sendMessage(ChatColor.RED + "You must login with /gAuth login <password> to perform this action.");
event.setCancelled(true); event.setCancelled(true);
return;
} }
} }
} }

View file

@ -29,6 +29,10 @@ public class EntityDamageEvent {
if (var2 instanceof LivingEntity livingEntity) { if (var2 instanceof LivingEntity livingEntity) {
EntityMetadata metadata = EntityMetadata.getEntityMetadata(livingEntity); EntityMetadata metadata = EntityMetadata.getEntityMetadata(livingEntity);
// Don't set custom name for champion mobs (they have bossbar instead)
if (metadata.championTier > 0) {
return;
}
if (metadata.level > 1 || metadata.prestige > 1) { if (metadata.level > 1 || metadata.prestige > 1) {
ChatColor levelColor = EntityMetadata.getLevelColor(metadata.level); ChatColor levelColor = EntityMetadata.getLevelColor(metadata.level);

View file

@ -1,7 +1,6 @@
package org.gsdistance.grimmsServer.Events.Listeners; package org.gsdistance.grimmsServer.Events.Listeners;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.gsdistance.grimmsServer.Constructable.Entity.EntityMetadata;
import org.gsdistance.grimmsServer.Manage.CustomEntityManager; import org.gsdistance.grimmsServer.Manage.CustomEntityManager;
public class EntityRemoveEvent { public class EntityRemoveEvent {

View file

@ -10,6 +10,12 @@ public class EntitySpawnEvent {
public static void Event(org.bukkit.event.entity.EntitySpawnEvent event) { public static void Event(org.bukkit.event.entity.EntitySpawnEvent event) {
if (event.getEntity().getType() != EntityType.PLAYER) { if (event.getEntity().getType() != EntityType.PLAYER) {
// Skip if this is a champion spawn (handled by SpawnChampion command)
if (event.getEntity().hasMetadata("champion_spawn")) {
event.getEntity().removeMetadata("champion_spawn", org.gsdistance.grimmsServer.GrimmsServer.instance);
return;
}
CustomEntityManager.registerEntity(event.getEntity()); CustomEntityManager.registerEntity(event.getEntity());
// getEntityMetadata handles both new entities (creates & levels) and chunk reloads (loads from disk without releveling) // getEntityMetadata handles both new entities (creates & levels) and chunk reloads (loads from disk without releveling)
EntityMetadata.getEntityMetadata(event.getEntity()); EntityMetadata.getEntityMetadata(event.getEntity());

View file

@ -20,7 +20,7 @@ public class GunFireEvent {
Player player = event.getPlayer(); Player player = event.getPlayer();
ItemStack item = player.getInventory().getItemInMainHand(); ItemStack item = player.getInventory().getItemInMainHand();
if (item == null || !CustomItemHandler.isCustomItem(item)) { if (!CustomItemHandler.isCustomItem(item)) {
return; return;
} }
@ -69,7 +69,7 @@ public class GunFireEvent {
// Find gun in player's inventory // Find gun in player's inventory
ItemStack gunItem = null; ItemStack gunItem = null;
for (ItemStack item : player.getInventory().getContents()) { for (ItemStack item : player.getInventory().getContents()) {
if (item != null && CustomItemHandler.isCustomItem(item)) { if (CustomItemHandler.isCustomItem(item)) {
CustomItemHandler gunHandler = CustomItemHandler.getHandler(item); CustomItemHandler gunHandler = CustomItemHandler.getHandler(item);
String gunItemId = gunHandler.getCustomItemId(); String gunItemId = gunHandler.getCustomItemId();
if (gunItemId.startsWith("gun_")) { if (gunItemId.startsWith("gun_")) {

View file

@ -35,8 +35,8 @@ public class PlayerRespawnEvent {
// Check if there are soulbound items to restore // Check if there are soulbound items to restore
if ((inventoryData.soulboundInventoryContents != null && !inventoryData.soulboundInventoryContents.isEmpty()) || if ((inventoryData.soulboundInventoryContents != null && !inventoryData.soulboundInventoryContents.isEmpty()) ||
hasNonNullItems(inventoryData.soulboundArmorContents) || hasNonNullItems(inventoryData.soulboundArmorContents) ||
hasNonNullItems(inventoryData.soulboundExtraContents)) { hasNonNullItems(inventoryData.soulboundExtraContents)) {
// Restore soulbound inventory items // Restore soulbound inventory items
Map<Integer, ItemStack> soulboundInventory = inventoryData.getSoulboundInventoryAsItemStacks(); Map<Integer, ItemStack> soulboundInventory = inventoryData.getSoulboundInventoryAsItemStacks();

View file

@ -16,6 +16,12 @@ public class ServerTickEvent {
} }
PlayerTickEvent.processMagnets(); PlayerTickEvent.processMagnets();
// Execute champion mob abilities every 20 ticks (1 second) to reduce load
if (ticks % 20L == 0L) {
ChampionTickEvent.Event();
}
++ticks; ++ticks;
if (ticks % 1000L == 0L) { if (ticks % 1000L == 0L) {
Market market = Market.getMarket(); Market market = Market.getMarket();

View file

@ -69,7 +69,7 @@ public final class GrimmsServer extends JavaPlugin {
return rt; return rt;
} }
public void registerCustomItems(){ public void registerCustomItems() {
CustomItemRegistry.registerGunTypes(); CustomItemRegistry.registerGunTypes();
CustomItemRegistry.registerAmmoTypes(); CustomItemRegistry.registerAmmoTypes();
} }

View file

@ -1,8 +1,10 @@
package org.gsdistance.grimmsServer.Manage; package org.gsdistance.grimmsServer.Manage;
import com.google.gson.reflect.TypeToken;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.gsdistance.grimmsServer.GrimmsServer; import org.gsdistance.grimmsServer.GrimmsServer;
import java.lang.reflect.Type;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
@ -26,7 +28,9 @@ public class CustomEntityManager {
} }
public static void loadFromFile() { public static void loadFromFile() {
List<UUID> loaded = GrimmsServer.pds.retrieveData("entityRegistry.json", "customEntities", List.class); Type listType = new TypeToken<List<UUID>>() {
}.getType();
List<UUID> loaded = GrimmsServer.pds.retrieveData("entityRegistry.json", "customEntities", listType);
if (loaded != null) { if (loaded != null) {
currentRegistry.clear(); currentRegistry.clear();
currentRegistry.addAll(loaded); currentRegistry.addAll(loaded);

View file

@ -12,18 +12,18 @@ import java.util.UUID;
public class PlayerTitles { public class PlayerTitles {
// Static titles (manually awarded or event-based) // Static titles (manually awarded or event-based)
private static final Map<String, String> staticTitles = Map.ofEntries( private static final Map<String, String> staticTitles = Map.ofEntries(
Map.entry("Dictator", "The title of a dictator, not to be messed with."), Map.entry("Dictator", "The title of a dictator, not to be messed with."),
Map.entry("Executioner", "The title and power of execution."), Map.entry("Executioner", "The title and power of execution."),
Map.entry("Murderer", "Someone whose crimes follow him till death."), Map.entry("Murderer", "Someone whose crimes follow him till death."),
Map.entry("Victim", "Got murdered, unfortunate."), Map.entry("Victim", "Got murdered, unfortunate."),
Map.entry("DragonSlayer", "The fabled warrior to defeat the fabled dragon or something like that."), Map.entry("DragonSlayer", "The fabled warrior to defeat the fabled dragon or something like that."),
Map.entry("Newbie", "Wowie! Joining the game gives a title!"), Map.entry("Newbie", "Wowie! Joining the game gives a title!"),
Map.entry("Titlemaxxer", "Get more than 5 titles"), Map.entry("Titlemaxxer", "Get more than 5 titles"),
Map.entry("Leader", "You got on the leaderboard."), Map.entry("Leader", "You got on the leaderboard."),
Map.entry("Null", "Not a title bro."), Map.entry("Null", "Not a title bro."),
Map.entry("BugSlayer", "Reported a bug."), Map.entry("BugSlayer", "Reported a bug."),
Map.entry("ExploitDestroyer", "Reported an exploit."), Map.entry("ExploitDestroyer", "Reported an exploit."),
Map.entry("Disgrace.", "Abused an exploit.") Map.entry("Disgrace.", "Abused an exploit.")
); );
// Dynamic titles (based on stats) - populated on-demand // Dynamic titles (based on stats) - populated on-demand

View file

@ -8,19 +8,19 @@ public enum TitleCriteria {
NEWBIE("Newbie", "Wowie! Joining the game gives a title!", player -> true), NEWBIE("Newbie", "Wowie! Joining the game gives a title!", player -> true),
MURDERER("Murderer", "Someone whose crimes follow him till death.", player -> MURDERER("Murderer", "Someone whose crimes follow him till death.", player ->
PlayerStats.getPlayerStats(player).getStat("total_kill_count", Integer.class) > 0), PlayerStats.getPlayerStats(player).getStat("total_kill_count", Integer.class) > 0),
VICTIM("Victim", "Got murdered, unfortunate.", player -> VICTIM("Victim", "Got murdered, unfortunate.", player ->
PlayerStats.getPlayerStats(player).getStat("death_count", Integer.class) > 0), PlayerStats.getPlayerStats(player).getStat("death_count", Integer.class) > 0),
DRAGON_SLAYER("DragonSlayer", "The fabled warrior to defeat the fabled dragon or something like that.", player -> DRAGON_SLAYER("DragonSlayer", "The fabled warrior to defeat the fabled dragon or something like that.", player ->
false), // Dragon kills not tracked in persistent stats false), // Dragon kills not tracked in persistent stats
LEADER("Leader", "You got on the leaderboard.", player -> LEADER("Leader", "You got on the leaderboard.", player ->
false), // Leaderboard status not tracked in persistent stats false), // Leaderboard status not tracked in persistent stats
TITLEMAXXER("Titlemaxxer", "Get more than 5 titles", player -> TITLEMAXXER("Titlemaxxer", "Get more than 5 titles", player ->
PlayerTitles.getPlayerTitles(player).getTitles().size() > 5); PlayerTitles.getPlayerTitles(player).getTitles().size() > 5);
private final String titleId; private final String titleId;
private final String description; private final String description;
@ -46,6 +46,6 @@ public enum TitleCriteria {
// Special titles that are manually awarded (not auto-checked) // Special titles that are manually awarded (not auto-checked)
public static final String[] MANUAL_TITLES = { public static final String[] MANUAL_TITLES = {
"Dictator", "Executioner", "BugSlayer", "ExploitDestroyer", "Disgrace." "Dictator", "Executioner", "BugSlayer", "ExploitDestroyer", "Disgrace."
}; };
} }

View file

@ -0,0 +1 @@
7