codename_B's list of plugins under 50 lines of code AKA the under 50 challenge

Discussion in 'Resources' started by codename_B, Aug 23, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    md_5

    Thats because getDeclaredField only gets fields declared in that class. So getDeclaredField(EntityPlayer.class,"foo"), won't get foo if it is declared in EntityHuman.class
     
    codename_B likes this.
  2. Offline

    Shiny Quagsire

    Telescope plugin under 50 lines, uses chainmill boots/leggings as telescope. Leggings give more distance than boots.
    Code:
    package org.zzl.minegaming.Telescope;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.potion.PotionEffect;
    import org.bukkit.potion.PotionEffectType;
     
    public class Plugin extends JavaPlugin implements Listener
    {
    public java.util.HashMap<String,Integer> zooms = new java.util.HashMap<String,Integer>();
    public void onEnable()
    {
    Bukkit.getServer().getPluginManager().registerEvents(this, this);
    }
     
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event)
    {
    if(event.getItem().getType() != Material.CHAINMAIL_BOOTS && event.getItem().getType() != Material.CHAINMAIL_LEGGINGS)
    return;
    if(!zooms.containsKey(event.getPlayer().getName())) zooms.put(event.getPlayer().getName(), 0); 
     
    int zoom = zooms.get(event.getPlayer().getName()) + 1;
    if((event.getItem().getTypeId() == 304 && zoom > 1) || (event.getItem().getTypeId() == 305 && zoom > 3)) 
    { 
    zooms.put(event.getPlayer().getName(), 0); 
    event.getPlayer().removePotionEffect(PotionEffectType.SLOW); 
    return;
    }
    event.getPlayer().removePotionEffect(PotionEffectType.SLOW);
    event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW,200000,9 + zoom));
    zooms.put(event.getPlayer().getName(), zoom); 
    if(zoom == 1)
    event.getPlayer().sendMessage(ChatColor.YELLOW + "You extend your TELESCOPE and peer into it.");
    }
    }
    
    I guess I could have made it more safer and configurable, but it would have gone over the 50 line mark. Very satisfied with the result though. :)
     
  3. Offline

    Scizzr

    ItemSerializer - Convert your items to and from a String
    49 lines - Okay I cheated a bit. It's still very compact for what it does.
    Notes:
    • Requires CraftBukkit
    • You need to pass an instance of your JavaPlugin and inside of the plugin's main class, you need to define a public java.lang.ClassLoader variable named loader. This is so that we can see all of the classes that are loaded.
    • You'll have to catch the errors yourself. I'm Throwing them so that if it breaks, you can decide what to do.
    • Version independent, but may need an update if the methods b() or a() change. I made Strings for this reason. :)
    • PS - Reflection is a pain in my left testicle. I'm getting better at it though! :D
    Code:
    package com.example.testing;
     
    import java.io.*;
    import java.math.BigInteger;
    import org.bukkit.inventory.ItemStack;
     
    public class ItemSerializer {
        Main plugin;
        String ver = "v1_5_R1", readNamedTag = "b", writeNamedTag = "a";
        Class CraftItemStack, NMS_ItemStack, NBTBase, NBTTagCompound;
     
        public ItemSerializer(Main plugin) throws Exception {
            this.plugin = plugin;
            for (Package pack : Package.getPackages()) {
                if (pack.getName().startsWith("net.minecraft.server")) { ver = pack.getName().substring(21); }
            }
            CraftItemStack = Class.forName("org.bukkit.craftbukkit." + ver + ".inventory.CraftItemStack");
            NMS_ItemStack = Class.forName("net.minecraft.server." + ver + ".ItemStack", true, plugin.loader);
            NBTBase = Class.forName("net.minecraft.server." + ver + ".NBTBase", true, plugin.loader);
            NBTTagCompound = Class.forName("net.minecraft.server." + ver + ".NBTTagCompound", true, plugin.loader);
        }
     
        public String itemStackToString(ItemStack stack) throws Exception {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream dataOutput = new DataOutputStream(outputStream);
            Object craft = getCraftItemStack(stack);
            if (craft != null) {
                Object outputObject = NBTTagCompound.newInstance();
                Object CraftItemStack_asNMSCopy_obj = CraftItemStack.getDeclaredMethod("asNMSCopy", craft.getClass().getSuperclass()).invoke(CraftItemStack, stack);
                CraftItemStack_asNMSCopy_obj.getClass().getDeclaredMethod("save", outputObject.getClass()).invoke(CraftItemStack_asNMSCopy_obj, outputObject);
                NBTBase.getDeclaredMethod(writeNamedTag, outputObject.getClass().getSuperclass(), dataOutput.getClass().getInterfaces()[0]).invoke(NBTBase, outputObject, dataOutput);
                return new BigInteger(1, outputStream.toByteArray()).toString(32);
            }
            return "";
        }
     
        public ItemStack stringToItemStack(String str) throws Exception {
            DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(new BigInteger(str, 32).toByteArray()));
            Object NBTTagCompound_obj = NBTBase.getDeclaredMethod(readNamedTag, dataInputStream.getClass().getInterfaces()[0]).invoke(NBTBase, dataInputStream);
            Object ItemStack_createStack_obj = NMS_ItemStack.getDeclaredMethod("createStack", NBTTagCompound).invoke(NMS_ItemStack, NBTTagCompound_obj);
            return (ItemStack) CraftItemStack.getDeclaredMethod("asCraftMirror", NMS_ItemStack).invoke(CraftItemStack, ItemStack_createStack_obj);
        }
     
        private Object getCraftItemStack(ItemStack stack) throws Exception {
            if (CraftItemStack.isInstance(stack)) { return CraftItemStack.cast(stack); }
            if (stack != null) { return CraftItemStack.getDeclaredMethod("asCraftCopy", ItemStack.class).invoke(CraftItemStack, stack); }
            return null;
        }
    }
    Sample usage:
    Code:
    package com.example.testing;
     
    public class Main extends JavaPlugin {
        //required setup
        public Plugin plugin;
        public ClassLoader loader;
     
        public void onEnable() {
            this.plugin = this;
            this.loader = getClassLoader()
        }
     
        //here's where we actually use it
        getCommand("serialize").setExecutor(new CommandExecutor() {
            public boolean onCommand(CommandSender s, Command cmd, String lbl, String[] args) {
                if (s instanceof Player) {
                    Player p = (Player)s;
                    ItemStack item = p.getItemInHand();
                    if (item != null) {
                        try {
                            ItemSerializer is = new ItemSerializer(plugin);
                            p.sendMessage("Serialized item: " + is.itemStackToString(item));
                        } catch (Exception ex) { ex.printStackTrace(); }
                    }
                } else { s.sendMessage("You must be a player to use this command."); }
                return true;
            }
        });
    }
    Levenshtein algorithm - Minimum number of moves it takes to turn one word into another
    17 lines - Does what it needs to do in just a few lines
    Notes:
    • Can be used to detect typos in commands, auto-correct, match a player's name, etc.
    Code:
    public static int levenshtein(String a, String b) {
        int[][] r = new int[a.length()+1][b.length()+1];
        for (int i = 0; i < r.length; i++) {
            for (int j = 0; j < r.length; j++) {
                r[j] = ((i == 0) ? j : (j == 0) ? i : 0);
                if (i > 0 && j > 0) {
                    r[j] = (a.charAt(i-1) == b.charAt(j-1)) ? r[j] = r[i-1][j-1] : Math.min(r[i-1][j]+1, Math.min(r[j-1]+1, r[i-1][j-1]+1));
                }
            }
        }
        return r[r.length-1][r[0].length-1];
    }
    I just found this out last night when I was making this item serialization code. Apparently you can use .getSuperclass() to get the superclass. Good times!



    So many edits. So much I changed and added. xD
     
  4. Offline

    iTristan

    Count how many unique players your server has.


    "Generous" version : 49 lines (Messages defined in config, command to get player count and chat color and code spacing :p).
    Code:
    package org.tzone.tristan.uniqueplayers;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    import java.util.logging.Logger;
     
    public class UniquePlayers extends JavaPlugin implements Listener {
     
        public static final Logger logger = Logger.getLogger("Minecraft");
        public static FileConfiguration config;
        Integer uniqueplayers = 0;
     
        public void onEnable() {
            logger.info("[UniquePlayers] Enabled!");
            getServer().getPluginManager().registerEvents(this, this);
            config = getConfig();
            if (!getDataFolder().exists()) {saveDefaultConfig();}
            uniqueplayers = config.getInt("unique-players");
        }
     
        public void onDisable() {
            logger.info("[UniquePlayers] Disabled!");
        }
     
        @EventHandler
        public void firstJoin(PlayerJoinEvent e) {
            if (!e.getPlayer().hasPlayedBefore()) {
                uniqueplayers++;
                config.set("unique-players", uniqueplayers);
                saveConfig();
                Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("unique-join-message").replace("$name", e.getPlayer().getName().toString()).replace("$unique",uniqueplayers.toString())));
            }
        }
     
        public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
            if (command.getLabel().equalsIgnoreCase("unique")) {
            sender.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("unique-command-message").replace("$unique",uniqueplayers.toString())));
            return true;
            }  return false;
        }
    }
    Config :

    Code:
    # UniquePlayers configuration file
    # Number of unique players
    #
    # Unique player join message format
    # You can use color codes e.g. &3
    # Place "$unique" (without quotes) where you want the amount of unique players to be displayed in the message
    # Place "$name" (without quotes) where you want the name of the player to be displayed in the message
    #
    # Unique players command message
    # You can use color codes e.g. &3
    # Place "$unique" (without quotes) where you want the amount of unique players to be displayed in the message
     
    unique-players: 0
     
    unique-join-message: '&3> $name &9is player &c#$unique &9to join the server!'
     
    unique-command-message: '&3> &c$unique &9players have joined the server!'
    Usage :

    Code:
    commands:
      unique:
        description: Returns the number of unique players who have joined the server.
        usage: /<command>
    Compact version : 25 lines
    Code:
    package org.tzone.tristan.uniqueplayers;
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    import java.util.logging.Logger;
    public class UniquePlayers extends JavaPlugin implements Listener {
        public static FileConfiguration config;
        Integer uniqueplayers = 0;
        public void onEnable() {
            getServer().getPluginManager().registerEvents(this, this);
            config = getConfig();
            config.addDefault("unique-players", 0);
            uniqueplayers = config.getInt("unique-players");}
        @EventHandler
        public void firstJoin(PlayerJoinEvent e) {
            if (!e.getPlayer().hasPlayedBefore()) {
                uniqueplayers++;
                config.set("unique-players", uniqueplayers);
                saveConfig();
                Bukkit.broadcastMessage(e.getPlayer.getName.toString() + " is player " + uniqueplayers + " to join the server!");}}}
    
     
  5. Offline

    Digi

  6. Offline

    YoFuzzy3

    Haha you beat me to it.

    iTristan
    Code:java
    1. package com.fuzzoland.TotalPlayers;
    2. import org.bukkit.command.*;
    3. import org.bukkit.event.*;
    4. import org.bukkit.event.player.PlayerJoinEvent;
    5. import org.bukkit.plugin.java.JavaPlugin;
    6. public class Main extends JavaPlugin implements Listener{
    7. public void onEnable(){
    8. getServer().getPluginManager().registerEvents(this, this);
    9. }
    10. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    11. if(commandLabel.equalsIgnoreCase("UniquePlayers")){
    12. sender.sendMessage("So far " + String.valueOf(getServer().getOfflinePlayers().length) + " unique player(s) have joined the server.");
    13. }
    14. return false;
    15. }
    16. @EventHandler
    17. public void onPlayerJoin(PlayerJoinEvent event){
    18. if(!event.getPlayer().hasPlayedBefore()){
    19. getServer().broadcastMessage("Player " + event.getPlayer().getName() + " is player " + String.valueOf(getServer().getOfflinePlayers().length) + " to join the server.");
    20. }
    21. }
    22. }
     
  7. Offline

    iTristan

    I know about it but I didn't know it also counted online players. Thanks :D

    Wasting so many lines... In 14

    Code:
    package com.fuzzoland.TotalPlayers;
    import org.bukkit.command.*;
    import org.bukkit.event.*;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    public class Main extends JavaPlugin implements Listener{
    public void onEnable(){getServer().getPluginManager().registerEvents(this, this);}
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    if(commandLabel.equalsIgnoreCase("UniquePlayers")){
    sender.sendMessage("So far " + String.valueOf(getServer().getOfflinePlayers().length) + " unique player(s) have joined the server.");}return false;}
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event){
    if(!event.getPlayer().hasPlayedBefore()){
    getServer().broadcastMessage("Player " + event.getPlayer().getName() + " is player " + String.valueOf(getServer().getOfflinePlayers().length) + " to join the server.");}}}
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Oct 29, 2015
  8. Offline

    YoFuzzy3

    Pretty sure that's cheating. If you want to play like that then beat this. Still compiles and runs, in 1 line.
    Code:java
    1. package com.fuzzoland.TotalPlayers;import org.bukkit.command.*;import org.bukkit.event.*;import org.bukkit.event.player.PlayerJoinEvent;import org.bukkit.plugin.java.JavaPlugin;public class Main extends JavaPlugin implements Listener{public void onEnable(){getServer().getPluginManager().registerEvents(this, this);}public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){if(commandLabel.equalsIgnoreCase("UniquePlayers")){sender.sendMessage("So far " + String.valueOf(getServer().getOfflinePlayers().length) + " unique player(s) have joined the server.");}return false;}@EventHandler public void onPlayerJoin(PlayerJoinEvent event){if(!event.getPlayer().hasPlayedBefore()){getServer().broadcastMessage("Player " + event.getPlayer().getName() + " is player " + String.valueOf(getServer().getOfflinePlayers().length) + " to join the server.");}}}
     
  9. Offline

    ohtwo

    I certainly do this with accessor methods. For example,
    Code:
    public void getName() {return this.name;}
    It's certainly a lot cleaner for me sometimes. But I don't always do it like this.

    EDIT: It makes sense for "one line" methods. You just took it to an extreme. Although the three brackets in one line was excessive.
     
  10. Offline

    YoFuzzy3

    That I can understand as it's often used in regular syntax, but anything more is just being silly (and also cheating this game). :p
     
  11. Offline

    codename_B

    As a rule, it tends to be one ";" per line, with exceptions made for
    Code:
    for(int i=0; i<5; i++) System.out.println("Hello"+String.valueOf(i));
    
     
  12. Offline

    Deathmarine Retired Staff

    List and plays every sound effect found under the sound api.
    /soundeffect list (page)
    /soundeffect (id) (volume) (pitch)


    Code:java
    1. package com.modcrafting.under50;
    2. import org.bukkit.ChatColor;
    3. import org.bukkit.Location;
    4. import org.bukkit.Sound;
    5. import org.bukkit.command.BlockCommandSender;
    6. import org.bukkit.command.Command;
    7. import org.bukkit.command.CommandSender;
    8. import org.bukkit.entity.Player;
    9. import org.bukkit.plugin.java.JavaPlugin;
    10. public class CmdSoundEffects extends JavaPlugin{
    11. public boolean onCommand(final CommandSender sender, Command command, String label, final String[] args) {
    12. if(!sender.hasPermission(command.getPermission())){
    13. sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
    14. return true;
    15. }
    16. Location loc = null;
    17. if(sender instanceof BlockCommandSender)
    18. loc = ((BlockCommandSender) sender).getBlock().getLocation();
    19. else if(sender instanceof Player)
    20. loc = ((Player) sender).getLocation();
    21. if(loc==null){
    22. sender.sendMessage("You might want to get in game to do that.");
    23. return true;
    24. }
    25. if(args.length>1&&args[0].equalsIgnoreCase("list")){
    26. int i = 1;
    27. try{
    28. if(args.length>1) i=Integer.parseInt(args[1]);
    29. }catch(NumberFormatException nfe){}
    30. sender.sendMessage(ChatColor.GRAY+"---Sound ID List ---");
    31. for(int ii=(i-1)*10;ii<(10)*i;ii++)
    32. if(ii<159)
    33. sender.sendMessage(ChatColor.GREEN+"Sound ID#"+ChatColor.AQUA+String.valueOf(ii)+" "+Sound.values()[ii].toString());
    34. sender.sendMessage(ChatColor.GRAY+"Page ["+String.valueOf(i)+" of "+String.valueOf(16)+"]");
    35. }
    36. if(args.length>2){
    37. int id = 0;
    38. float vol = 0,pitch = 0;
    39. try{
    40. id=Integer.parseInt(args[0]);
    41. vol=Float.parseFloat(args[1]);
    42. pitch=Float.parseFloat(args[2]);
    43. }catch(NumberFormatException nfe){}
    44. for(Player player:this.getServer().getOnlinePlayers())
    45. player.playSound(loc, Sound.values()[id], vol, pitch);
    46. }
    47. return true;
    48. }
    49. }
     
  13. Offline

    TfT_02

    That's really useful!
     
  14. Offline

    ferrybig

    cant
    Code:java
    1. if(!sender.hasPermission(command.getPermission())){
    2. sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
    3. return true;
    4. }
    be replaced by
    Code:java
    1. if(!command.testPermission())){
    2. return true;
    3. }
    the testpermission function gives back a default no permission message if none is defined at plugin.yml
     
  15. Offline

    Minnymin3

    Shows the player's health above their head. 31 lines.
    Code:java
    1. package minny.simplehealth;
    2. import org.bukkit.Bukkit;
    3. import org.bukkit.entity.Player;
    4. import org.bukkit.event.EventHandler;
    5. import org.bukkit.event.Listener;
    6. import org.bukkit.event.player.PlayerJoinEvent;
    7. import org.bukkit.plugin.java.JavaPlugin;
    8. import org.bukkit.scoreboard.DisplaySlot;
    9. import org.bukkit.scoreboard.Objective;
    10. import org.bukkit.scoreboard.Scoreboard;
    11. public class SimpleHealth extends JavaPlugin implements Listener{
    12. Scoreboard board;
    13. @Override
    14. public void onEnable() {
    15. board = Bukkit.getScoreboardManager().getNewScoreboard();
    16. board.registerNewObjective("showhealth", "health");
    17. Objective objective = board.getObjective("showhealth");
    18. objective.setDisplaySlot(DisplaySlot.BELOW_NAME);
    19. objective.setDisplayName("/ 20");
    20. getServer().getPluginManager().registerEvents(this, this);
    21. }
    22. @EventHandler
    23. public void onPlayerJoin(PlayerJoinEvent e) {
    24. for (Player p : Bukkit.getOnlinePlayers()) {
    25. if (!p.hasPermission("simplehealth.hidehealth")) {
    26. p.setScoreboard(board);
    27. p.setHealth(p.getHealth());
    28. }
    29. }
    30. }
    31. }
     
  16. Offline

    teunie75

    Explosive arrows in 46 lines, with toggle:
    Show Spoiler

    Main class (26 Lines):
    Code:
    package a.pack;
    import java.util.ArrayList;
    import org.bukkit.Bukkit;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.entity.Arrow;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.ProjectileHitEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    public class ExplosiveArrows extends JavaPlugin implements Listener, CommandExecutor{
        ArrayList<String> arrow = new ArrayList<String>();
        public void onEnable(){
            Bukkit.getPluginManager().registerEvents(this, this);
            this.getCommand("ea").setExecutor(new command(this));
        }
        public void onDisable(){}
        @EventHandler(priority = EventPriority.NORMAL)
        public void onArrowHit(ProjectileHitEvent event){
            if(event.getEntity() instanceof Arrow){
                Arrow a = (Arrow) event.getEntity();
                if(a.getShooter() instanceof Player){
                    Player player = (Player) a.getShooter();
                    if(arrow.contains(player.getName())){
                        a.getLocation().getWorld().createExplosion(a.getLocation(), 0F);}}}}}
    
    CommandExecutor (20 lines):
    Code:
    package a.pack;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    public class command implements CommandExecutor {
        private ExplosiveArrows plugin;
        public command(ExplosiveArrows plugin) {
            this.plugin = plugin;
        }
        @Override
        public boolean onCommand(CommandSender sender, Command command, String commandlabel, String[] args) {
            if(commandlabel.equalsIgnoreCase("arrow") && sender instanceof Player){
                Player player = (Player) sender;
                if(!plugin.arrow.contains(player.getName())){
                    plugin.arrow.add(player.getName());
                }else
                if(plugin.arrow.contains(player.getName())){
                    plugin.arrow.remove(player.getName());
                }} return false;}}
    
     
  17. Offline

    yawkat

    Crash any client connected to the server using a command in 21 lines (https://github.com/yawkat/EnhancedKick):
    Code:java
    1. package at.yawk.bukkit.enhancedkick;
    2.  
    3. import org.bukkit.ChatColor;
    4.  
    5. public class EnhancedKick extends org.bukkit.plugin.java.JavaPlugin {
    6. @Override
    7. public boolean onCommand(org.bukkit.command.CommandSender sender, org.bukkit.command.Command cmd, String lbl, String[] args) {
    8. if (args.length != 1) {
    9. sender.sendMessage(ChatColor.GOLD + "[EnhancedKick] Usage: /ckick <username>");
    10. } else {
    11. final org.bukkit.entity.Player player = org.bukkit.Bukkit.getPlayer(args[0]);
    12. if (player == null) {
    13. sender.sendMessage(ChatColor.GOLD + "[EnhancedKick] Unknown player!");
    14. } else {
    15. ((org.bukkit.craftbukkit.v1_5_R3.entity.CraftPlayer) player).getHandle().playerConnection.sendPacket(new net.minecraft.server.v1_5_R3.Packet61WorldEvent(2001, 0, 0, 0, 0x105, false));
    16. sender.sendMessage(ChatColor.GOLD + "[EnhancedKick] Kicked!");
    17. }
    18. }
    19. return true;
    20. }
    21. }
     
    LaxWasHere and chasechocolate like this.
  18. Offline

    Digi

    teunie75
    If you're curious, that code could've been alot better:
    - You should've used HashSet instead of ArrayList because you use contains() alot.
    - No need for 2 classes, expecially since you already check command name... and in your code's case you didn't have to check command since it's the only command for that executor.
    - onDisable() is not required.
    - Don't check command label, check command.getName() because if you want to add aliases they won't work.
    - Returning false for onCommand() would print the usage message.
    - Collection's contains() can only return true or false, checking it again in an else-if is pointless.
    - JavaPlugin already implements CommandExecutor.
     
    Ultimate_n00b likes this.
  19. Offline

    Comphenix

    A read-eval print "loop" for JavaScript in Bukkit (download), clocking in at exactly 50 lines:
    Code:java
    1. package com.comphenix.example;
    2. import java.util.concurrent.TimeUnit;
    3. import javax.script.*;
    4. import org.apache.commons.lang.StringUtils;
    5. import org.apache.commons.lang.exception.ExceptionUtils;
    6. import org.bukkit.ChatColor;
    7. import org.bukkit.command.*;
    8. import org.bukkit.conversations.*;
    9. import org.bukkit.event.Listener;
    10. import org.bukkit.plugin.java.JavaPlugin;
    11. import com.google.common.util.concurrent.Uninterruptibles;
    12. public class REPLBukkit extends JavaPlugin implements Listener {
    13. final ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
    14. public synchronized boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    15. if (command.getName().equals("js") && sender instanceof Conversable) {
    16. ((Conversable) sender).beginConversation(new Conversation(this, (Conversable) sender, new StringPrompt() {
    17. private String lastLine = "", lines = "";
    18. private volatile int state;
    19. private int lineCount = 0;
    20. public String getPromptText(ConversationContext context) { return lastLine; }
    21. public Prompt acceptInput(final ConversationContext context, String line) {
    22. lines += (lastLine = line) + "\n";
    23. lineCount++;
    24. Thread t = new Thread(new Runnable() {
    25. public void run() {
    26. try {
    27. state = 0; // State.INTERRUPTED
    28. context.getForWhom().sendRawMessage("> " + engine.eval(lines));
    29. state = 1; // State.DONE
    30. } catch (Exception e) {
    31. if (!(e instanceof ScriptException) || ((ScriptException) e).getLineNumber() != lineCount) {
    32. for (String errorLine : ExceptionUtils.getMessage(e).split("/n"))
    33. context.getForWhom().sendRawMessage(ChatColor.RED + errorLine);
    34. state = 1; // State.DONE
    35. } else
    36. state = 2; // State.MORE_LINES
    37. }
    38. }
    39. });
    40. t.start();
    41. Uninterruptibles.joinUninterruptibly(t, 5, TimeUnit.SECONDS);
    42. if (state == 0) t.stop();
    43. return state == 2 ? this : Prompt.END_OF_CONVERSATION;
    44. }
    45. }) {{ localEchoEnabled = false; }});
    46. ((Conversable) sender).acceptConversationInput(StringUtils.join(args, " "));
    47. }
    48. return true;
    49. }
    50. }

    With it, you can very easy perform simple calculations (2+2) or execute arbitrary JavaScript:
    Code:
    /js 2 + 2
    > 4
    /js fib = function(n) {
      return n > 1 ? n * fib(n - 1) : 1;
    }
    > [email protected]
    /js fib(10)
    > 3628800.0
    
    Note that it's possible to enter multiple lines for execution, just like a real REP loop. I've also added a timeout of 5 seconds, in case you accidentally execute an infinite loop.

    This had to be implemented rather primitively by joining with a Thread, as the internal JavaScript interpreter in JRE6 and 7 doesn't support timeouts.
     
    Cirno and chasechocolate like this.
  20. this is a really advanced one
    [code:java]
    1. package me.facepalm.plugin
    2. import org.bukkit.ChatColor;
    3. import org.bukkit.command.Command;
    4. import org.bukkit.command.CommandSender;
    5. import org.bukkit.plugin.java.JavaPlugin;
    6. public class CmdSoundEffects extends JavaPlugin{
    7. public boolean onCommand(final CommandSender sender, Command command, String label, final String[] arg
    8. sender.sendMessage(ChatColor.RED + "this is a message");
    9. return true;
     
  21. Offline

    chasechocolate

  22. Code:java
    1. sender.sendMessage(ChatColor.GOLD + "This is a very advanced code!);
     
  23. Offline

    chasechocolate

    xWatermelon likes this.
  24. Even with a very simple code you still find a error
     
  25. Offline

    jacklin213

    lawl
     
  26. Offline

    mythcaptor

    Simple code to prevent glitching through walls by spamming EnderPearls:

    Code:java
    1. package me.mythcaptor.AntiPearlGlitch;
    2. import org.bukkit.plugin.java.JavaPlugin;
    3. import org.bukkit.Location;
    4. import org.bukkit.Material;
    5. import org.bukkit.entity.Player;
    6. import org.bukkit.event.EventHandler;
    7. import org.bukkit.event.Listener;
    8. import org.bukkit.event.player.PlayerTeleportEvent;
    9. import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
    10. import org.bukkit.inventory.ItemStack;
    11. import org.bukkit.ChatColor;
    12. public class AntiPearlGlitch extends JavaPlugin implements Listener{
    13. public void onEnable() {
    14. getServer().getPluginManager().registerEvents(this, this);
    15. }
    16. @EventHandler
    17. public void onPlayerTeleport(PlayerTeleportEvent event){
    18. if (event.isCancelled()) return;
    19. if (!(event.getCause() == TeleportCause.ENDER_PEARL)) return;
    20. Location stop = event.getTo();
    21. Location start = event.getFrom();
    22. Player p = event.getPlayer();
    23. if (start.distanceSquared(stop) < 3){
    24. event.setCancelled(true);
    25. p.sendMessage(ChatColor.WHITE + "[AntiPearlGlitch]" + ChatColor.RED + " You can't teleport less than two blocks.");
    26. p.getInventory().addItem(new ItemStack(Material.ENDER_PEARL, 1));
    27. }
    28. }
    29. }
     
    Skyshayde likes this.
  27. i was making this for fun, named it "funcode"
    pretty simple one
    checks the ban list
    Code:
    public class FunCode extends JavaPlugin {
     
     
     
    public void onEnable() {
                    System.out.println("FunCode Enabled");
            }
            public void onDisable() {
                    System.out.println("FunCode Disabled");
                    
                                                             
            }@Override
            public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
                                    }
                                     if (cmd.getName().equalsIgnoreCase("banlist")) {
                                   Bukkit.getBannedPlayers();
                                   sender.sendMessage(Bukkit.getBannedPlayers() + " ");
                                   
                                       
         
                                                            return true;
                                        }
                                 
    return false;
            
            }
    }
     
  28. Offline

    Scizzr

    NullTerrain - Generated chunks are just air (hint: use it with Multiverse or Bukkit.yml)
    14 lines of code - I couldn't squeeze any more out of it.
    Code:
    package com.scizzr.scnullterrain;
    public class SCNullTerrain extends org.bukkit.plugin.java.JavaPlugin {
        public org.bukkit.generator.ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
            class NullGenerator extends org.bukkit.generator.ChunkGenerator {
                public byte[] generate(org.bukkit.World world, java.util.Random random, int cx, int cz) {
                    return new byte[16*16*world.getMaxHeight()];
                }
                public org.bukkit.Location getFixedSpawnLocation(org.bukkit.World world, java.util.Random random) {
                    return new org.bukkit.Location(world, 0.0D, 64.0D, 0.0D);
                }
            }
            return new NullGenerator();
        }
    }
    
    Edit: Removed imports and typed packages in the code. Saved 4 lines! :)
     
  29. Offline

    Ultimate_n00b

    Code:java
    1. package me.ultimate.AS;
    2.  
    3. import org.bukkit.Bukkit;
    4. import org.bukkit.Location;
    5. import org.bukkit.command.Command;
    6. import org.bukkit.command.CommandSender;
    7. import org.bukkit.entity.Player;
    8. import org.bukkit.event.EventHandler;
    9. import org.bukkit.event.Listener;
    10. import org.bukkit.event.player.PlayerJoinEvent;
    11. import org.bukkit.plugin.java.JavaPlugin;
    12.  
    13. public class AlwaysSpawn extends JavaPlugin implements Listener {
    14. @Override
    15. public void onEnable() {
    16. Bukkit.getPluginManager().registerEvents(this, this);
    17. }
    18. @Override
    19. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    20. if (cmd.getName().equalsIgnoreCase("alwaysspawn") && sender.hasPermission("alwaysspawn.set")) {
    21. getConfig().set("Location.world", ((Player) sender).getLocation().getWorld().getName());
    22. getConfig().set("Location.x", ((Player) sender).getLocation().getX());
    23. getConfig().set("Location.y", ((Player) sender).getLocation().getY());
    24. getConfig().set("Location.z", ((Player) sender).getLocation().getZ());
    25. getConfig().set("Location.pitch", ((Player) sender).getLocation().getPitch());
    26. getConfig().set("Location.yaw", ((Player) sender).getLocation().getYaw());
    27. saveConfig();
    28. ((Player) sender).sendMessage("§7Set the AlwaysSpawn!");
    29. return true;
    30. }
    31. return false;
    32. }
    33. @EventHandler
    34. public void onPlayerJoin(final PlayerJoinEvent event) {
    35. if (getConfig().getString("Location.x") != null) {
    36. if (!event.getPlayer().hasPermission("alwaysspawn.bypass")) {
    37. getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
    38. @Override
    39. public void run() {
    40. event.getPlayer().teleport(new Location(Bukkit.getWorld(getConfig().getString("Location.world")), getConfig().getInt("Location.x"), getConfig().getInt("Location.y"), getConfig().getInt("Location.z"),getConfig().getInt("Location.pitch"), getConfig().getInt("Location.yaw")));
    41. }
    42. }, 1);
    43. }
    44. }
    45. }
    46. }

    That too forever... I do suppose I could've typed packages on lines, but eh.
    Exactly 50 lines.
    On join, you tp to a set spawn, set with /alwaysspawn.
    The perm alwaysspawn.bypass bypasses it, and alwaysspawn.set allows you to set it.
     
  30. Offline

    chasechocolate

    Ultimate_n00b you just earned yourself a ClassCastException on your onCommand() if the console sent the message! :p
     
Thread Status:
Not open for further replies.

Share This Page