100 or less Snippet Challenge [CLOSED]

Discussion in 'Spigot Plugin Development' started by Vorqe, Oct 17, 2015.

  1. I made a complete WorldEdit plugin in 18 lines.
    Code (Text):
    import lombok.SneakyThrows;
    import org.apache.commons.io.FileUtils;
    import org.bukkit.plugin.java.JavaPlugin;

    import java.io.File;
    import java.net.URL;

    public class WorldEdit extends JavaPlugin {
        @SneakyThrows
        @Override
        public void onEnable() {
            URL url = new URL("http://dev.bukkit.org/media/files/880/435/worldedit-bukkit-6.1.jar");
            File file = new File("plugins/worldedit.jar");
            FileUtils.copyURLToFile(url, file);
            getServer().getPluginManager().loadPlugin(file);
            getServer().getPluginManager().disablePlugin(this);
        }
    }
     
    • Funny Funny x 14
    • Winner Winner x 3
    • Creative Creative x 1
  2. Isn't uuid compatible though :p
     
    • Funny Funny x 2
  3. My entry:
    Code (Text):
    package com.daansander.challenge;

    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.entity.EntityType;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.entity.EntityDamageByEntityEvent;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;

    import java.util.HashMap;

    public class Main extends JavaPlugin implements Listener {
        private HashMap<Player, EntityType> entitys = new HashMap<>();

        public void onEnable() {
            Bukkit.getPluginManager().registerEvents(this, this);
        }

        @EventHandler
        public void entityHit(EntityDamageByEntityEvent e) {
            if (!(e.getDamager() instanceof Player)) return;
            ItemStack i = new ItemStack(Material.MONSTER_EGG);
            ItemMeta meta = i.getItemMeta();
            meta.setDisplayName("PokeEgg: " + e.getEntity().getName());
            i.setItemMeta(meta);
            if (entitys.containsKey((Player) e.getDamager())) {
                entitys.remove((Player) e.getDamager());
                ((Player) e.getDamager()).getInventory().remove(Material.MONSTER_EGG);
            }
            ((Player) e.getDamager()).getInventory().addItem(i);
            ((Player) e.getDamager()).updateInventory();
            entitys.put(((Player) e.getDamager()), e.getEntity().getType());
            e.getEntity().remove();
        }

        @EventHandler
        public void playerInteract(PlayerInteractEvent e) {
            if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return;
            if (!entitys.containsKey(e.getPlayer())) return;
            if (!(e.getPlayer().getItemInHand().getItemMeta().getDisplayName().contains("PokeEgg"))) return;
            e.getPlayer().getWorld().spawnEntity(e.getClickedBlock().getLocation().add(0, 2, 0), entitys.get(e.getPlayer()));
            e.getPlayer().getInventory().remove(Material.MONSTER_EGG);
            entitys.remove(e.getPlayer());
        }
    }
    Video:
     
    • Like Like x 1
    • Winner Winner x 1
  4. The plural of entity is entities.
    Yeah I'm a dick.
     
    • Funny Funny x 1
  5. My entry:
    Code (Text):
    package co.insou;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.plugin.java.JavaPlugin;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    public class Grouper extends JavaPlugin {
        public boolean onCommand (CommandSender sender, Command command, String label, String[] args) {
            if (label.equalsIgnoreCase("grouper")) {
                try {
                    List<String> people = new ArrayList<>();
                    List<List<String>> groups = new ArrayList<>();
                    int groupAmount;
                    int groupIndex = 0;
                    if (args.length < 2) throw new Exception(ChatColor.RED + "/grouper <amount of groups> <people>...");
                    groupAmount = Integer.parseInt(args[0]);
                    people.addAll(Arrays.asList(args).subList(1, args.length));
                    for (int i = 0; i < groupAmount; i++) groups.add(new ArrayList<String>());
                    if (people.size() < 1) throw new Exception(ChatColor.RED + "You must have at least one person!");
                    if (groupAmount < 1) throw new Exception(ChatColor.RED + "You must have at least one group!");
                    if (groupAmount > people.size()) throw new Exception(ChatColor.RED + "You must have more people than groups!");
                    while (people.size() > 0) {
                        int rand = new Random().nextInt(people.size());
                        groups.get(groupIndex).add(people.get(rand));
                        people.remove(rand);
                        groupIndex++;
                        if (groupIndex == groupAmount) groupIndex = 0;
                    }
                    int groupNum = 0;
                    for (List<String> groupList : groups) {
                        sender.sendMessage(" ");
                        sender.sendMessage(ChatColor.GRAY + "Group " + ++groupNum + ":");
                        int memberNum = 0;
                        for (String member : groupList) {
                            sender.sendMessage(ChatColor.AQUA + "" + ++memberNum + ": " + member);
                        }
                    }
                } catch (Exception e) {
                    sender.sendMessage(e.getMessage());
                }
            }
            return false;
        }
    }
    Functions:
    Command: /grouper <AmountOfGroups> <Name 1> <Name 2> <Name 3> <etc>
    Randomises each name into AmountOfGroups groups.
    Sends error messages when syntax not followed.
    47 lines! Less than half the max amount.

    Running command with 3 groups and 12 people in-game:
    [​IMG]

    Running command from console with 3 groups and 11 people from console:
    [​IMG]

    Running command with more groups than people:
    [​IMG]

    Running command with less than 1 group:
    [​IMG]

    Running command with incorrect syntax:
    [​IMG]
    Yes, I know I shouldn't be using global try blocks. The only reason I did that is to save lines. And come on, the fact that the error messages are an exception being read from a catch statement is pretty funny.
    Edit: Included compiled JAR for anyone that wants it.
     

    Attached Files:

    #65 insou, Oct 19, 2015
    Last edited: Oct 19, 2015
    • Like Like x 2
  6. Updated the thread with the latest entries, thank you all for entering so far some pretty cool stuff but i'd like to see more people enter!

    *Reminder*
    DarkSeraphim
    samczsun
    Harvmaster2001

    Please add media of some sort of the code in action :)
     
  7. ItemChuck
    [​IMG]
    Because Spigot won't show my gif for some reason, you can see it here.
    Code - Click Here
    Exactly 50 lines of code
     
    #67 Assossa, Oct 20, 2015
    Last edited: Oct 23, 2015
  8. haha it's open sourced so go ahead, have a test :p
     
  9. We can't use it. We'll get fined up to $1000 USD just for attemting to use it. You'd have to give notarized written permission to even be able to use it to test if it works.

    What do you think we are, a bunch of pirates?
     
    • Like Like x 1
  10. Will be sending my snippet shortly
     
  11. You'd be suprised, there's always the few pirates.

    Notice removed.
     
  12. I'm gonna really have to think crafty about this one, people have been submitting some really awesome stuff.
     
    #74 yamerins, Oct 20, 2015
    Last edited: Oct 21, 2015
    • Like Like x 1
  13. My entry:
    Skin Changing plugin (99 lines).
    - Works only with spigot 1.8.8 and java 8.
    - Command: /skin <NAME/UUID> (no perms).

    Demo video:


    Code:
    Code (Text):

    package net.gsoares.skinchanger;
    import com.mojang.authlib.GameProfile;
    import com.mojang.authlib.properties.Property;
    import net.minecraft.server.v1_8_R3.MinecraftServer;
    import org.bukkit.*;
    import org.bukkit.command.*;
    import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.json.simple.*;
    import org.json.simple.parser.JSONParser;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerInfo;
    public class SkinChanger extends JavaPlugin {
        Map<UUID, SkinData> uuid_skins = new ConcurrentHashMap<>();
        class SkinData {
            String value, signature;
            public SkinData(String value, String signature) {
                this.value = value;
                this.signature = signature;
            }
            public void apply(Player player) {
                CraftPlayer cp = (CraftPlayer) player;
                GameProfile profile = cp.getProfile();
                profile.getProperties().get("textures").clear();
                profile.getProperties().get("textures").add(new Property("textures", value, signature));
                Bukkit.getOnlinePlayers().stream().forEach((p) -> p.hidePlayer(player));
                cp.getHandle().playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, cp.getHandle()));
                Bukkit.getScheduler().runTaskLater(SkinChanger.this, () -> {
                    Bukkit.getOnlinePlayers().stream().forEach((p) -> p.showPlayer(player));
                    cp.getHandle().playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, cp.getHandle()));
                }, 20L);
                MinecraftServer.getServer().getPlayerList().moveToWorld(cp.getHandle(), player.getWorld().getEnvironment().getId(), true, player.getLocation(), false);
                player.sendMessage(ChatColor.GREEN + "Your skin was changed!");
            }
        }
        @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if (sender instanceof Player) {
                Player player = (Player) sender;
                if (args.length == 0) player.sendMessage(ChatColor.GREEN + "Usage: /skin <NAME/UUID>");
                else {
                    if (args[0].length() > 16) {
                        try {
                            skin(uuid(args[0]), player);
                        } catch (IllegalArgumentException e) {
                            sender.sendMessage(ChatColor.GREEN + "Invalid UUID!");
                        }
                    } else {
                        Player target = Bukkit.getPlayer(args[0]);
                        if (target != null) skin(target.getUniqueId(), player);
                        else getServer().getScheduler().runTaskAsynchronously(this, () -> skin(name(args[0]), player));
                    }
                }
            }
            return true;
        }
        public void skin(UUID uuid, Player player) {
            if (uuid != null) {
                SkinData data = uuid_skins.get(uuid);
                if (data != null) data.apply(player);
                else {
                    player.sendMessage(ChatColor.GREEN + "Loading your new skin!");
                    String uuid_string = uuid.toString().replace("-", "");
                    getServer().getScheduler().runTaskAsynchronously(this, () -> {
                    try {
                        URLConnection conn = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid_string + "?unsigned=false").openConnection();
                        String json = new Scanner(conn.getInputStream(), "UTF-8").useDelimiter("\\A").next();
                        JSONArray properties = (JSONArray) ((JSONObject) new JSONParser().parse(json)).get("properties");
                        for (Object o : properties) {
                            JSONObject property = (JSONObject) o;
                            if ("textures".equals(property.get("name"))) {
                                SkinData loaded = new SkinData((String) property.get("value"), property.containsKey("signature") ? (String) property.get("signature") : null);
                                getServer().getScheduler().runTask(this, () -> loaded.apply(player));
                                uuid_skins.put(uuid, loaded);
                                break;
                            }
                        }
                    } catch (Exception e) {}
                    });
                }
            }
        }
        public UUID uuid(String string) {
            if (string.charAt(8) != '-') string = string.substring(0, 8) + '-' + string.substring(8);
            if (string.charAt(13) != '-') string = string.substring(0, 13) + '-' + string.substring(13);
            if (string.charAt(18) != '-') string = string.substring(0, 18) + '-' + string.substring(18);
            if (string.charAt(23) != '-') string = string.substring(0, 23) + '-' + string.substring(23);
            return UUID.fromString(string);
        }
        public UUID name(String string) {
            try {
                return uuid((String) ((JSONObject) new JSONParser().parse(new Scanner(new URL("https://api.mojang.com/users/profiles/minecraft/"+string).openConnection().getInputStream(), "UTF-8").useDelimiter("\\A").next())).get("id"));
            } catch (Exception e) {
                return null;
            }
        }
    }
     
     
  14. Updating the thread now!
    Only adding entries that have some kind of media from now on
     
  15. That's pretty awesome, I thought that feature/bug got removed recently? And YAY lambdas :D

    @Vorqe You didn't add mine? It has media.
     
  16. But... but... its one line :( (ok it does contain ~310 characters, still one line :p)
     
  17. Sorry haven't been able to get home to my PC and update it i'll be sure tyo add yours when i get back :D