commit a95c2ac30b0215b021a705d60dc50fb3360cf910 Author: Mysaa Date: Mon May 24 01:04:34 2021 +0200 Premier commit - Inclusion dans le projet git diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1dcf8f1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +bin/ +.classpath +.settings +.project diff --git a/plugin.yml b/plugin.yml new file mode 100644 index 0000000..a50c670 --- /dev/null +++ b/plugin.yml @@ -0,0 +1,20 @@ +name: HgWorldPlugin +main: com.bernard.hgWorld.HgWorldPlugin +version: béta +description: Un simple plugin pour maps hunger games ... +author: mysaa +website: bernard.com +commands: + hgshow: + description: Indique clairement l'élement spécifié + usage: /hgshow [élement] + hghide: + description: Cache l'indiquation de l'élement spécifié + usage: /hghide [élement] + chest: + description: Enregistre un coffre + usage: /chest type [x y z] + unchest: + description: Supprime un coffre des registres + usage: /unchest [x y z] + \ No newline at end of file diff --git a/src/com/bernard/hgWorld/EventManager.java b/src/com/bernard/hgWorld/EventManager.java new file mode 100644 index 0000000..9dc09e3 --- /dev/null +++ b/src/com/bernard/hgWorld/EventManager.java @@ -0,0 +1,271 @@ +package com.bernard.hgWorld; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.logging.Level; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import com.bernard.hgWorld.data.HgConfig; +import com.bernard.hgWorld.data.HgConfig.ScenarEvent; +import com.bernard.hgWorld.data.HgConfig.ScenarEvent.Action; +import com.bernard.hgWorld.data.HgConfig.ScenarEvent.DelayedMessage; + +public class EventManager implements Listener{ + + Set worldsToReact; + + Map,Set> afterEvents; + Set persistentList; + Set conditionalEvents; + Map> loopEvents; + Map tasks; + BukkitTask conditionalTask; + int littleLoopPeriod = 3; + boolean started = false; + + HgWorldPlugin plugin; + + public EventManager(HgConfig config,HgWorldPlugin plugin) { + // TODO 'Ranger' la config + } + + /** + * Démarre tous les timers, les loops et les 'catching d'events' + */ + public void start() { + //loop-triggered events + for(Entry> event : loopEvents.entrySet()) { + LoopRunnable runnable = new LoopRunnable(event.getValue()); + BukkitTask task = runnable.runTaskTimer(plugin, event.getKey().delay, event.getKey().loop); + for (ScenarEvent scenarEvent : event.getValue()) + tasks.put(scenarEvent, task); + } + + //conditional events + conditionalTask = new ConditionLoop().runTaskTimer(plugin, 0, littleLoopPeriod); + + started = true; + } + + /** + * Arette tout ce qui est 'sheduled' et coupe le catching d'events + */ + public void stop() { + started = false; + conditionalTask.cancel(); + for (BukkitTask task : tasks.values()) + task.cancel(); + tasks.clear(); + } + + @EventHandler + public void onEvent(Event e) { + if(afterEvents.containsKey(e.getClass())) { + makeHappen(afterEvents.get(e.getClass()), e); + } + } + + public void makeHappen(Set list) { + try { + ScriptEngineManager factory = new ScriptEngineManager(); + ScriptEngine engine = factory.getEngineByName("JavaScript"); + for(String var : generalArgsEval()) + engine.eval(var); + for(InitializedEvent event : list) { + if((boolean) engine.eval(event.event.condition)) { + new BukkitRunnable() { + @Override + public void run() { + for (Action action : event.event.actions) + action.execute(event.initializer); + delayedMessager(event.event.warnHappen); + } + }.runTaskLater(plugin, event.event.delay); + delayedMessager(event.event.warnCondition); + if(persistentList.contains(event)) + persistentList.remove(event); + }else { + if(event.event.persistent) { + if(!persistentList.contains(event)) + persistentList.add(event); + }else { + delayedMessager(event.event.warnFailed); + } + } + } + + } catch (ScriptException e) { + Bukkit.getLogger().log(Level.WARNING, "Impossible de tester cet event conditionnel, script illégal", e); + } + } + + private void makeHappen(Set events, Event initializer) { + try { + ScriptEngineManager factory = new ScriptEngineManager(); + ScriptEngine engine = factory.getEngineByName("JavaScript"); + for(String var : generalArgsEval()) + engine.eval(var); + for(ScenarEvent event : events) { + if((boolean) engine.eval(event.condition)) { + new BukkitRunnable() { + @Override + public void run() { + for (Action action : event.actions) + action.execute(initializer); + delayedMessager(event.warnHappen); + } + }.runTaskLater(plugin, event.delay); + delayedMessager(event.warnCondition); + if(persistentList.contains(new InitializedEvent(event, initializer))) + persistentList.remove(new InitializedEvent(event, initializer)); + }else { + if(event.persistent) { + if(!persistentList.contains(new InitializedEvent(event, initializer))) + persistentList.add(new InitializedEvent(event, initializer)); + }else { + delayedMessager(event.warnFailed); + } + } + } + + } catch (ScriptException e) { + Bukkit.getLogger().log(Level.WARNING, "Impossible de tester cet event conditionnel, script illégal", e); + } + } + + + //////////////////////////////////////////////////////////////////// + ///////////////Infering event data ZONE ...///////////////////////// + //////////////////////////////////////////////////////////////////// + @EventHandler + public void onBlockPlacedEvent(BlockPlaceEvent e) { + if(!worldsToReact.contains(e.getPlayer().getWorld().getName())) + return; + //XXX + } + + + + + + + public String[] generalArgsEval() { + String[] data = new String[3]; + data[0] = "alivePlayers" + "=" + Integer.toString(/* TODO Get the value */0); + data[1] = "onlineMode" + "=" + plugin.getServer().getOnlineMode(); + data[2] = "" + "=" + ""; + //TODO other values + return data; + } + + public void delayedMessager(List messages) { + delayedMessager(messages, 0); + } + public void delayedMessager(List messages,final int delta) { + for (final DelayedMessage m : messages) { + new BukkitRunnable() { + + @Override + public void run() { + Bukkit.broadcastMessage(m.message); + } + }.runTaskLater(plugin, m.delay + delta); + } + } + + private class ConditionLoop extends BukkitRunnable{ + + @Override + public void run() { + //Condtionnal events + makeHappen(conditionalEvents, null); + + //Persistent events + makeHappen(persistentList); + } + } + + public static class InitializedEvent{ + + public InitializedEvent(ScenarEvent event, Event initializer) { + this.event = event; + this.initializer = initializer; + } + ScenarEvent event; + Event initializer; + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((event == null) ? 0 : event.hashCode()); + result = prime * result + ((initializer == null) ? 0 : initializer.hashCode()); + return result; + } + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + InitializedEvent other = (InitializedEvent) obj; + if (event == null) { + if (other.event != null) + return false; + } else if (!event.equals(other.event)) + return false; + if (initializer == null) { + if (other.initializer != null) + return false; + } else if (!initializer.equals(other.initializer)) + return false; + return true; + } + + + } + + private class LoopRunnable extends BukkitRunnable{ + + Set events; + + public LoopRunnable(Set events) { + this.events = events; + } + + + + @Override + public void run() { + makeHappen(events, null); + } + + } + + public static class DelayedLoop{ + int delay; + int loop; + } + + +} diff --git a/src/com/bernard/hgWorld/HgWorldPlugin.java b/src/com/bernard/hgWorld/HgWorldPlugin.java new file mode 100644 index 0000000..4e1e19c --- /dev/null +++ b/src/com/bernard/hgWorld/HgWorldPlugin.java @@ -0,0 +1,56 @@ +package com.bernard.hgWorld; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.World; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.Yaml; + +import com.bernard.hgWorld.commands.ChestPlacingCommands; +import com.bernard.hgWorld.commands.HgManagerCommand; +import com.bernard.hgWorld.commands.LocationsShowCommands; +import com.bernard.hgWorld.data.HgWorldConfig; +import com.bernard.hgWorld.objects.HgGame; + +public class HgWorldPlugin extends JavaPlugin { + + public static Map worldsConfig = new HashMap<>();// + + public static Map games = new HashMap<>();// + + public static Yaml yaml = new Yaml(); + + public EventManager eventManager; + + @Override + public void onEnable() { + super.onEnable(); + + eventManager = new EventManager(); + + this.getServer().getPluginManager().registerEvents(new ManagmentListener(), this); + this.getServer().getPluginManager().registerEvents(eventManager, this); + + this.getCommand("hgshow").setExecutor(new LocationsShowCommands()); + this.getCommand("hghide").setExecutor(new LocationsShowCommands()); + this.getCommand("chest").setExecutor(new ChestPlacingCommands()); + this.getCommand("unchest").setExecutor(new ChestPlacingCommands()); + this.getCommand("hg").setExecutor(new HgManagerCommand()); + + + } + + @Override + public void onDisable() { + // TODO Auto-generated method stub + super.onDisable(); + } + + public static HgWorldConfig getWorldConfig(World world){ + if(!HgWorldPlugin.worldsConfig.containsKey(world.getName()))HgWorldPlugin.worldsConfig.put(world.getName(), new HgWorldConfig()); + return HgWorldPlugin.worldsConfig.get(world.getName()); + + } + +} diff --git a/src/com/bernard/hgWorld/ManagmentListener.java b/src/com/bernard/hgWorld/ManagmentListener.java new file mode 100644 index 0000000..22f1be8 --- /dev/null +++ b/src/com/bernard/hgWorld/ManagmentListener.java @@ -0,0 +1,65 @@ +package com.bernard.hgWorld; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.yaml.snakeyaml.error.YAMLException; + +import com.bernard.hgWorld.data.HgWorldConfig; + +public class ManagmentListener implements Listener{ + + @EventHandler + public void onWorldLoad(WorldLoadEvent e) { + //Recupération du fichier de config (emplacement des coffres, points de spawn etc...) + File worldFolder = e.getWorld().getWorldFolder(); + File configFile = new File(worldFolder,"hgWorldConfig.yml"); + if(!configFile.exists()) { + Bukkit.getLogger().log(Level.WARNING, "Le fichier de configuration 'hgWorldConfig.yml' n'existe pas dans ce monde ("+e.getWorld().getName()+"). Sa configuration ne sera donc pas chargée et une partie de HungerGames ne pourra pas se dérouler dans ce monde .... à bon entendeur"); + return; + } + + try (FileInputStream fis = new FileInputStream(configFile)){ + HgWorldConfig config = (HgWorldConfig) HgWorldPlugin.yaml.load(fis); + HgWorldPlugin.worldsConfig.put(e.getWorld().getName(), config); + Bukkit.getLogger().log(Level.INFO, "Configuration chargée pour le monde "+e.getWorld().getName()); + } catch (FileNotFoundException e1) { + Bukkit.getLogger().log(Level.SEVERE, "ALERTE ROUGE .... cette erreur n'est pas cencée se déclencher, ou alors vous savez supprimer des fichiers très vite",e1); + } catch (IOException e1) { + Bukkit.getLogger().log(Level.SEVERE, "Je n'ai pas réussi à lire ce fichier .... vous avez surement touché aux droits, ou alors le fichier est corrompu",e1); + } catch (YAMLException | ClassCastException e1) { + Bukkit.getLogger().log(Level.SEVERE, "Impossible de lire le fichier, son contenu est corompu ... désolé",e1); + } + } + + @EventHandler + public void onWorldUnload(WorldUnloadEvent e) { + //Écriture du fichier de config (emplacement des coffres, points de spawn etc...) + File worldFolder = e.getWorld().getWorldFolder(); + File configFile = new File(worldFolder,"hgWorldConfig.yml"); + if(HgWorldPlugin.worldsConfig.containsKey(e.getWorld().getName())) { + Bukkit.getLogger().log(Level.WARNING, "Il n'existe pas de configuration a enregistrer pour le monde "+e.getWorld().getName()); + return; + } + + try (FileOutputStream fos = new FileOutputStream(configFile)){ + String data = HgWorldPlugin.yaml.dump(HgWorldPlugin.worldsConfig.get(e.getWorld().getName())); + fos.write(data.getBytes()); + Bukkit.getLogger().log(Level.INFO, "Configuration sauvegardée pour le monde "+e.getWorld().getName()); + } catch (IOException e1) { + Bukkit.getLogger().log(Level.SEVERE, "Je n'ai pas réussi à écrire ce fichier .... vous avez surement touché aux droits",e1); + } + } + + + +} diff --git a/src/com/bernard/hgWorld/commands/ChestPlacingCommands.java b/src/com/bernard/hgWorld/commands/ChestPlacingCommands.java new file mode 100644 index 0000000..9845b72 --- /dev/null +++ b/src/com/bernard/hgWorld/commands/ChestPlacingCommands.java @@ -0,0 +1,118 @@ +package com.bernard.hgWorld.commands; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.util.Vector; + +import com.bernard.hgWorld.HgWorldPlugin; + +public class ChestPlacingCommands implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command command, String cmd, String[] args) { + + Location chestPos; + World chestWorld; + if(sender instanceof Player) + chestWorld = ((Player)sender).getWorld(); + else if(sender instanceof BlockCommandSender) + chestWorld = ((BlockCommandSender)sender).getBlock().getWorld(); + else { + sender.sendMessage("Cette commande ne peut être lancée depuis la console, sinon, je ne sais dans quel monde placer les coffres"); + return true; + } + + switch(cmd) { + case "chest": + if(args.length != 1 && args.length != 4)return false; + String chestType = args[0]; + if(args.length == 4) { + chestPos = understandCoords(args[1], args[2], args[3], sender, chestWorld); + if(chestPos == null)return true; + if(!(chestWorld.getBlockAt(chestPos).getState() instanceof InventoryHolder)) { + sender.sendMessage("Le bloc à cette coordonée n'a pas d'inventaire, je ne l'enregistre donc pas"); + return true; + } + }else { + Location currentLocation; + if(sender instanceof Player) + currentLocation = ((Player)sender).getLocation(); + else + currentLocation = ((BlockCommandSender)sender).getBlock().getLocation(); + while(!(chestWorld.getBlockAt(currentLocation).getState() instanceof InventoryHolder) && currentLocation.getBlockY() >= 0) { + currentLocation = currentLocation.add(new Vector(0, -1, 0)); + } + if(currentLocation.getBlockY() < 0) { + sender.sendMessage("Je n'ai pas trouvé de container, veuillez vous assurer d'être AU DESSUS de votre cible (même x, même z, y plus grand"); + return true; + } + chestPos = currentLocation; + } + HgWorldPlugin.getWorldConfig(chestWorld).chests.put(chestPos, chestType); + sender.sendMessage("Ok, le "+chestWorld.getBlockAt(chestPos).getType().toString()+" aux coordonnées "+chestPos.toString()+" est enregistré comme un "+chestType); + return true; + case "unchest": + if(args.length != 0 && args.length != 3)return false; + + if(args.length == 4) { + chestPos = understandCoords(args[0], args[1], args[2], sender, chestWorld); + if(chestPos == null)return true; + }else { + Location currentLocation; + if(sender instanceof Player) + currentLocation = ((Player)sender).getLocation(); + else + currentLocation = ((BlockCommandSender)sender).getBlock().getLocation(); + while(!(chestWorld.getBlockAt(currentLocation).getState() instanceof InventoryHolder) && currentLocation.getBlockY() >= 0) { + currentLocation = currentLocation.add(new Vector(0, -1, 0)); + } + if(currentLocation.getBlockY() < 0) { + sender.sendMessage("Je n'ai pas trouvé de container, veuillez vous assurer d'être AU DESSUS de votre cible (même x, même z, y plus grand"); + return true; + } + chestPos = currentLocation; + } + + if(HgWorldPlugin.getWorldConfig(chestWorld).chests.remove(chestPos) == null) + sender.sendMessage("Je n'avais pas enregistré d'inventaire aux coordonnées "+chestPos.toString()); + else + sender.sendMessage("Ok, l'inventaire aux coordonnées "+chestPos.toString()+"a été désenregistré"); + + return true; + } + throw new IllegalArgumentException("La méthode ChestPlacingCOmmands.onCommand n'est pas censée gérer la commande "+cmd); + } + + public static Location understandCoords(String sx, String sy, String sz, CommandSender output, World world) { + int x,y,z; + try { + x = Integer.parseInt(sx); + }catch (NumberFormatException e) { + output.sendMessage(sx+" n'est pas une coordonée x valide"); + return null; + } + try { + y = Integer.parseInt(sy); + if(y < 0 || y > 255) + throw new NumberFormatException(); + }catch (NumberFormatException e) { + output.sendMessage(sy+" n'est pas une coordonée y valide"); + return null; + } + try { + z = Integer.parseInt(sz); + }catch (NumberFormatException e) { + output.sendMessage(sz+" n'est pas une coordonée z valide"); + return null; + } + return new Location(world, x,y,z); + + } + +} diff --git a/src/com/bernard/hgWorld/commands/HgManagerCommand.java b/src/com/bernard/hgWorld/commands/HgManagerCommand.java new file mode 100644 index 0000000..ea1276c --- /dev/null +++ b/src/com/bernard/hgWorld/commands/HgManagerCommand.java @@ -0,0 +1,58 @@ +package com.bernard.hgWorld.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.bernard.hgWorld.HgWorldPlugin; +import com.bernard.hgWorld.objects.HgGame; + +public class HgManagerCommand implements CommandExecutor{ + + @Override + public boolean onCommand(CommandSender sender, Command command, String cName, String[] args) { + if(args.length == 0)return false; + if(!(sender instanceof Player)) { + sender.sendMessage("Seul un joueur peut lancer cette commande"); + return true; + } + Player p = (Player)sender; + HgGame game; + switch(args[0]) { + case "init": + if(HgWorldPlugin.games.containsKey(p.getWorld().getName())) { + sender.sendMessage("Une partie a déjà été initialisée dans ce monde (voir démarée)");return true; + } + String[] commandArgs = new String[args.length-1]; + System.arraycopy(args, 0, commandArgs, 0, commandArgs.length); + game = HgGame.initGame(commandArgs,p.getWorld()); + HgWorldPlugin.games.put(p.getName(), game); + + + case "start": + game = HgWorldPlugin.games.get(p.getWorld().getName()); + if(game==null) { + sender.sendMessage("Aucune partie n'a été initiée dans ce monde (utilisez 'hg init')");return true; + } + if(game.isStarted()) { + sender.sendMessage("Une partie est déjà en cours dans ce monde");return true; + } + case "pause": + game = HgWorldPlugin.games.get(p.getWorld().getName()); + if(game==null) { + sender.sendMessage("Aucune partie n'a été initiée dans ce monde (utilisez 'hg init')");return true; + } + if(!game.isStarted()) { + sender.sendMessage("La partie n'a pas encore démarrée ...");return true; + } + if(game.isPause()) { + sender.sendMessage("La partie est déjà en pause ...");return true; + } + + //XXX + } + return false; + } + +} diff --git a/src/com/bernard/hgWorld/commands/LocationsShowCommands.java b/src/com/bernard/hgWorld/commands/LocationsShowCommands.java new file mode 100644 index 0000000..2a44a62 --- /dev/null +++ b/src/com/bernard/hgWorld/commands/LocationsShowCommands.java @@ -0,0 +1,19 @@ +package com.bernard.hgWorld.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +public class LocationsShowCommands implements CommandExecutor{ + + @Override + public boolean onCommand(CommandSender sender, Command command, String cmd, String[] args) { + if(cmd == "hgshow") { + + }else if(cmd == "hghide") { + + } + return false; + } + +} diff --git a/src/com/bernard/hgWorld/data/HgConfig.java b/src/com/bernard/hgWorld/data/HgConfig.java new file mode 100644 index 0000000..321f977 --- /dev/null +++ b/src/com/bernard/hgWorld/data/HgConfig.java @@ -0,0 +1,316 @@ +package com.bernard.hgWorld.data; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; + +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.event.Event; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import com.bernard.hgWorld.math.UndeterminedInt; +import com.bernard.hgWorld.math.UndeterminedString; +import com.bernard.inutil.ArrayInutil; + +public class HgConfig { + + //Scenarios + public Map events; + + public static class ScenarEvent{ + + public String condition; + public boolean persistent; + public int delay; + public int loop; + public List warnHappen; //Est affiché lorsque l'action est déclenchée + public List warnFailed; //Est affiché lorsque (loop ou after) s'est déclenché mais que la condition a empeche le déroulement + public List warnCondition; //Est affiché lorsque (loop ou after ou condition) est déclenché, ne reste que le délai + public double spawn; + public Action[] actions; + + + public class DelayedMessage{ + public String message; + public int delay; + } + + public static class Action{ + Event initializer; + String type; + Param[] params; + + public void execute(Event initializer) { + //TODO l'execution d'actions avec initialiseur + /// /!\ Effectue juste les tests ceux de l'event ! + } + + public static class Param{ + String name; + String value; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((initializer == null) ? 0 : initializer.hashCode()); + result = prime * result + Arrays.hashCode(params); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Action other = (Action) obj; + if (initializer == null) { + if (other.initializer != null) + return false; + } else if (!initializer.equals(other.initializer)) + return false; + if (!Arrays.equals(params, other.params)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(actions); + result = prime * result + ((condition == null) ? 0 : condition.hashCode()); + result = prime * result + delay; + result = prime * result + loop; + result = prime * result + (persistent ? 1231 : 1237); + long temp; + temp = Double.doubleToLongBits(spawn); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((warnCondition == null) ? 0 : warnCondition.hashCode()); + result = prime * result + ((warnFailed == null) ? 0 : warnFailed.hashCode()); + result = prime * result + ((warnHappen == null) ? 0 : warnHappen.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ScenarEvent other = (ScenarEvent) obj; + if (!Arrays.equals(actions, other.actions)) + return false; + if (condition == null) { + if (other.condition != null) + return false; + } else if (!condition.equals(other.condition)) + return false; + if (delay != other.delay) + return false; + if (loop != other.loop) + return false; + if (persistent != other.persistent) + return false; + if (Double.doubleToLongBits(spawn) != Double.doubleToLongBits(other.spawn)) + return false; + if (warnCondition == null) { + if (other.warnCondition != null) + return false; + } else if (!warnCondition.equals(other.warnCondition)) + return false; + if (warnFailed == null) { + if (other.warnFailed != null) + return false; + } else if (!warnFailed.equals(other.warnFailed)) + return false; + if (warnHappen == null) { + if (other.warnHappen != null) + return false; + } else if (!warnHappen.equals(other.warnHappen)) + return false; + return true; + } + + } + + //ChestTypes + public Map chestTypes = new HashMap<>(); + + + public static class ChestType{//TODO Optimize with a cool bernard API + Map groups; + Map items; //Item->Chances de spawn + + public Inventory fillInventory(Inventory inv) { + + inv.clear(); + Random rand = new Random(); + + List toSpawn = new ArrayList<>(); + for (Entry itemGroup : groups.entrySet()) + if(rand.nextDouble() <= itemGroup.getValue()) + toSpawn.addAll(itemGroup.getKey().getItems()); + for (Entry item : items.entrySet()) + if(rand.nextDouble() <= item.getValue()) + toSpawn.add(item.getKey()); + if(inv.getSize() < toSpawn.size()) { + Collections.shuffle(toSpawn); + for(int i = toSpawn.size()-1;i>inv.getSize()-1;i--) + toSpawn.remove(i); + } + ItemStack[] content = new ItemStack[inv.getSize()]; + + for (UndeterminedItem item : toSpawn) { + int slot = item.slot; + if(slot == -1) + slot = rand.nextInt(content.length); + else if(content[item.slot] != null){//Echanger les items (le nouveau prends la place de l'ancien, qui est replacé aléatoirement, car considéré comme un nouveau) + UndeterminedItem nouveau = item; + item = new UndeterminedItem(content[slot]); + content[slot] = nouveau.getItem(); + } + while(content[slot] != null) + slot = (slot+1)%content.length; + content[slot] = item.getItem(); + } + + inv.setContents(content); + + return inv; + } + + public static class ItemGroup{ + String name; + UndeterminedInt count; + Map items; //Item->spawnWeight + + public List getItems() { + + Random rand = new Random(); + + int count = this.count.generateInt(); + double[] spawnWeights = new double[items.size()]; + double totalWeigth = 0; + List it = new ArrayList<>(items.keySet()); + for (int i = 0;i enchantGroups = new HashMap<>(); + Map enchants = new HashMap<>(); //Item->Chances de spawn + + UndeterminedString name; + + public UndeterminedItem(ItemStack s) { + this.slot = -1; + this.stackSize = new UndeterminedInt(s.getAmount()); + this.type = s.getType(); + this.damage = new UndeterminedInt(s.getDurability()); + this.name = s.getItemMeta().hasDisplayName()?new UndeterminedString(s.getItemMeta().getDisplayName()):null; + } + + public ItemStack getItem(){ + ItemStack stack = new ItemStack(type, stackSize.generateInt(), (short) damage.generateInt()); + + + Random rand = new Random(); + + List toSpawn = new ArrayList<>(); + for (Entry itemGroup : enchantGroups.entrySet()) + if(rand.nextDouble() <= itemGroup.getValue()) + toSpawn.addAll(itemGroup.getKey().getEnchantements()); + for (Entry item : enchants.entrySet()) + if(rand.nextDouble() <= item.getValue()) + toSpawn.add(item.getKey()); + for (UndeterminedEnchantement undeterminedEnchantement : toSpawn) + stack.addUnsafeEnchantment(undeterminedEnchantement.ID, undeterminedEnchantement.level.generateInt()); + + if(name != null) + stack.getItemMeta().setDisplayName(name.generate());//TODO verifier le fonctionnement + + + return stack; + + } + + public static class EnchantementGroup{ + String name; + UndeterminedInt count; + Map items; //Enchant->spawnWeight + + public List getEnchantements() { + + Random rand = new Random(); + + int count = this.count.generateInt(); + double[] spawnWeights = new double[items.size()]; + double totalWeigth = 0; + List it = new ArrayList<>(items.keySet()); + for (int i = 0;i chests = new HashMap<>();//Position,type + + + //Starting plots location + public List startingPlots = new ArrayList<>(); + +} diff --git a/src/com/bernard/hgWorld/events/ChestRefillEvent.java b/src/com/bernard/hgWorld/events/ChestRefillEvent.java new file mode 100644 index 0000000..ae6e824 --- /dev/null +++ b/src/com/bernard/hgWorld/events/ChestRefillEvent.java @@ -0,0 +1,12 @@ +package com.bernard.hgWorld.events; + +public class ChestRefillEvent implements HgEvent { + + @Override + public void call() { + // TODO Auto-generated method stub + + } + + +} diff --git a/src/com/bernard/hgWorld/events/HgEvent.java b/src/com/bernard/hgWorld/events/HgEvent.java new file mode 100644 index 0000000..9abba7e --- /dev/null +++ b/src/com/bernard/hgWorld/events/HgEvent.java @@ -0,0 +1,7 @@ +package com.bernard.hgWorld.events; + +public interface HgEvent { + + public void call(); + +} diff --git a/src/com/bernard/hgWorld/math/UndeterminedInt.java b/src/com/bernard/hgWorld/math/UndeterminedInt.java new file mode 100644 index 0000000..6e58c46 --- /dev/null +++ b/src/com/bernard/hgWorld/math/UndeterminedInt.java @@ -0,0 +1,54 @@ +package com.bernard.hgWorld.math; + +import java.util.Random; + +public class UndeterminedInt { + + Random rand; + char method; + double[] params; + + public UndeterminedInt(int amount) { + method='v'; + params = new double[] {amount}; + } + + private UndeterminedInt(char method,double[] params) { + this.method=method; + this.params = params; + } + + //val;exp;uni;norm + public int generateInt() { + switch(method) { + case 'v': + return (int) params[0]; + + case 'e': + return (int) -(Math.log(rand.nextDouble()) / params[0]); + + case 'u': + return (int) (params[0] + rand.nextDouble()*(params[1] - params[0])); + + case 'n': + return (int) (rand.nextGaussian() * params[1] + params[0]); + + default: + throw new IllegalStateException("Incorrect mode aléatioire : '"+method+"'"); + } + } + + public static UndeterminedInt getExponentialNumber(double lambda) { + return new UndeterminedInt('e', new double[] {lambda}); + } + + public static UndeterminedInt getUniformNumber(int x0,int x1) { + return new UndeterminedInt('u', new double[] {x0,x1}); + } + + public static UndeterminedInt getNormalNumber(int mu,int sigma) { + return new UndeterminedInt('u', new double[] {mu,sigma}); + } + + +} diff --git a/src/com/bernard/hgWorld/math/UndeterminedString.java b/src/com/bernard/hgWorld/math/UndeterminedString.java new file mode 100644 index 0000000..ab5fe54 --- /dev/null +++ b/src/com/bernard/hgWorld/math/UndeterminedString.java @@ -0,0 +1,46 @@ +package com.bernard.hgWorld.math; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +public class UndeterminedString { + + Random rand; + + Map spawn = new HashMap<>(); + + public UndeterminedString(String value) { + spawn.put(value, 1.0); + } + + public UndeterminedString(Map items) { + spawn = items; + } + + public UndeterminedString(String[] items) { + for(String s : items) + spawn.put(s, 1.0); + } + + + + + public String generate() { + + Double overallSum = 0.0; + for (Double d : spawn.values()) + overallSum+=d; + + Double val = rand.nextDouble() * overallSum; + Double current = 0.0; + + for (Map.Entry e : spawn.entrySet()) { + current += e.getValue(); + if(current >= val) + return e.getKey(); + } + throw new IllegalArgumentException("Il y a un probleme dan l'algorithme"); + + } +} diff --git a/src/com/bernard/hgWorld/objects/HgGame.java b/src/com/bernard/hgWorld/objects/HgGame.java new file mode 100644 index 0000000..094c407 --- /dev/null +++ b/src/com/bernard/hgWorld/objects/HgGame.java @@ -0,0 +1,107 @@ +package com.bernard.hgWorld.objects; + +import java.util.List; +import java.util.Set; + +import org.bukkit.World; + +public class HgGame { + + World world; + boolean started = false,pause = false; + int time; + + //Teams info + List> teams; + + public static HgGame initGame(String[] args,World w) { + HgGame game = new HgGame(); + game.world = w; + game.time = Integer.MIN_VALUE; + return game;//XXX + } + + + + + + + + + + + + + /** + * @return the world + */ + public World getWorld() { + return world; + } + + /** + * @param world the world to set + */ + public void setWorld(World world) { + this.world = world; + } + + /** + * @return the started + */ + public boolean isStarted() { + return started; + } + + /** + * @param started the started to set + */ + public void setStarted(boolean started) { + this.started = started; + } + + /** + * @return the pause + */ + public boolean isPause() { + return pause; + } + + /** + * @param pause the pause to set + */ + public void setPause(boolean pause) { + this.pause = pause; + } + + /** + * @return the time + */ + public int getTime() { + return time; + } + + /** + * @param time the time to set + */ + public void setTime(int time) { + this.time = time; + } + + /** + * @return the teams + */ + public List> getTeams() { + return teams; + } + + /** + * @param teams the teams to set + */ + public void setTeams(List> teams) { + this.teams = teams; + } + + + +} diff --git a/src/com/bernard/hgWorld/objects/HgPlayer.java b/src/com/bernard/hgWorld/objects/HgPlayer.java new file mode 100644 index 0000000..16b6838 --- /dev/null +++ b/src/com/bernard/hgWorld/objects/HgPlayer.java @@ -0,0 +1,9 @@ +package com.bernard.hgWorld.objects; + +import org.bukkit.entity.Player; + +public class HgPlayer { + + Player p; + +} diff --git a/src/com/bernard/inutil/ArrayInutil.java b/src/com/bernard/inutil/ArrayInutil.java new file mode 100644 index 0000000..9fa718e --- /dev/null +++ b/src/com/bernard/inutil/ArrayInutil.java @@ -0,0 +1,169 @@ +package com.bernard.inutil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/** + * @author Mysaa + * @date on 22/07/17. + */ + +public class ArrayInutil { + + public static double sum(Collection items) { + double sum = 0; + for (Double x : items) + sum += x; + return sum; + } + + public static List asize(List items, int length, Double[] failSumsArray, double failSum, Random r){ + if(Arrays.class.equals(items.getClass().getEnclosingClass())) + items = new ArrayList<>(items); + return asizeP(items,length,failSumsArray,failSum,r); + } + + public static List asize(X[] items,int length,Double[] failSumsArray,double failSum,Random r){ + return asize(Arrays.asList(items),length,failSumsArray,failSum,r); + } + + private static List asizeP(List items,int length,Double[] failSumsArray,double failSum,Random r){ + ArrayList failSums = new ArrayList<>(Arrays.asList(failSumsArray)); + ArrayList finalItems = new ArrayList<>(); + if(items.size() <= 0)System.err.println("ArrayInutil: List empty !"+items.add(null)); + if(items.size() < length){ + int n = (int) Math.floor(length / items.size()); + for (int i = 0; i < n; i++) + finalItems.addAll(items); + } + double currentFailSum = failSum; + while(finalItems.size()= ran){ + currentFailSum -= failSums.get(i); + finalItems.add(items.get(i)); + failSums.remove(i); + items.remove(i); + break; + } + } + } + Collections.shuffle(finalItems,r); + return finalItems; + } + + public static Map count(List items){ + Map out = new HashMap<>(); + for (X x:items) { + X key = null; + for (X k:out.keySet()) + if(x.equals(k)) + key = k; + if (key == null) + out.put(x, 1); + else + out.put(key, out.get(x) + 1); + } + return out; + } + + public static Long[] toObjectArray(long[] array){ + Long[] out = new Long[array.length]; + for (int i = 0; i < out.length; i++) + out[i] = array[i]; + return out; + } + + public static Double[] toObjectArray(double[] array){ + Double[] out = new Double[array.length]; + for (int i = 0; i < out.length; i++) + out[i] = array[i]; + return out; + } + + public static Integer[] toObjectArray(int[] array){ + Integer[] out = new Integer[array.length]; + for (int i = 0; i < out.length; i++) + out[i] = array[i]; + return out; + } + + public static Long[][] toObjectArray(long[][] array){ + Long[][] out = new Long[array.length][]; + for (int i = 0; i < out.length; i++) + out[i] = toObjectArray(array[i]); + return out; + } + + public static Integer[][] toObjectArray(int[][] array){ + Integer[][] out = new Integer[array.length][]; + for (int i = 0; i < out.length; i++) + out[i] = toObjectArray(array[i]); + return out; + } + + public static long[] toPrimitiveArray(Long[] array){ + long[] out = new long[array.length]; + for (int i = 0; i < out.length; i++) + out[i] = array[i]; + return out; + } + + public static int[] toPrimitiveArray(Integer[] array){ + int[] out = new int[array.length]; + for (int i = 0; i < out.length; i++) + out[i] = array[i]; + return out; + } + + public static long[][] toPrimitiveArray(Long[][] array){ + long[][] out = new long[array.length][]; + for (int i = 0; i < out.length; i++) + out[i] = toPrimitiveArray(array[i]); + return out; + } + + public static int[][] toPrimitiveArray(Integer[][] array){ + int[][] out = new int[array.length][]; + for (int i = 0; i < out.length; i++) + out[i] = toPrimitiveArray(array[i]); + return out; + } + + public static boolean inArray (T needle, T[] haystack){ + for(T item : haystack) + if(item.equals(needle))return true; + return false; + } + + public static Integer[] range (int low, int high){ + Integer[] result = new Integer[high-low]; + for(int i = 0;i int indexOf(T[] haystack, T needle) { + for (int i = 0; i < haystack.length; i++) { + if(haystack[i] != null && haystack[i].equals(needle)) + return i; + } + return -1; + } + + public static void removeIndex(T[] array, int index) { + System.arraycopy(array,index+1,array,index, array.length-index); + } + + + +}