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

    Deathmarine Retired Staff

    50 Line list and play Sound Effects plugin.
    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. }
     
  2. Offline

    YoFuzzy3

    Deathmarine
    You could save 4 lines by compacting the imports. :p
     
  3. Offline

    Deathmarine Retired Staff

  4. Offline

    YoFuzzy3

  5. Offline

    bobacadodl

    Could you please explain how this works?:
    Code:
    .replaceAll("(&([a-f0-9l-or]))", "\u00A7$2")
     
    XD 3VIL M0NKEY likes this.
  6. Offline

    md_5

    Replaces the & when its followed by a colour code with the section sign.
    You can also use chatcolor.translatealternatecolourcodes
     
  7. Offline

    bobacadodl

    Well yes, I figured that out. But where do I learn cool shortcuts like that? :O
    And what does the "a-f0-9L-or" mean?
     
  8. Offline

    YoFuzzy3

    It replaces all & characters with section signs only when followed by the characters specified. The specified characters are a, b, c, d, e, f (a-f), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 (0-9), l, m, n, o (l-o) and r.
     
    bobacadodl likes this.
  9. Offline

    md_5

    Not really a shortcut, chatcolor.translatealtcolourcodes would be faster and more understandable.
     
  10. Offline

    bobacadodl

    True. But this method of replacement is interesting :O Where do you learn tricks like this??
     
  11. Offline

    YoFuzzy3

    I didn't even know that method existed. xD

    This website. :p
     
    bobacadodl likes this.
  12. Offline

    AmoebaMan

    It's regex (regular expressions), and you'll see it pop up in all sorts of queer places. It's used to locate desired patterns in Strings. Here's a tutorial.
     
    bobacadodl likes this.
  13. Offline

    bobacadodl

    Thanks so much for this!
     
  14. Offline

    codename_B

    me <3 regex
     
    YoFuzzy3 likes this.
  15. Offline

    YoFuzzy3

    I knew what it was, just didnt say so (oops). :p
     
  16. Offline

    AmoebaMan

    I would like Regex a lot more if it was more widely used. As it is, the only things I've ever used it for is the String.replace method in Java and the optional Regex search in Sublime Text 2.
     
  17. Offline

    codename_B

    You can do some trippy shit with regex
     
  18. Offline

    YoFuzzy3

    I remade some of the plugin and made it a little better. Now it's 5 spouts of fireworks all in a line. The time allows decimals. And it won't throw an exception if the input is wrong. It's also 42 lines now. :D

    Code:
    Code:java
    1. package com.fuzzoland.FireworkShow;
    2. import java.util.*;
    3. import org.bukkit.*;
    4. import org.bukkit.FireworkEffect.Type;
    5. import org.bukkit.command.*;
    6. import org.bukkit.entity.*;
    7. import org.bukkit.inventory.meta.FireworkMeta;
    8. import org.bukkit.plugin.java.JavaPlugin;
    9. import org.bukkit.scheduler.BukkitRunnable;
    10. public class Main extends JavaPlugin{
    11. final HashMap<Long, Long> fireworkTimer = new HashMap<Long, Long>();
    12. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, final String[] args){
    13. if(sender.hasPermission("FireworkShow.use") && sender instanceof Player && (commandLabel.equalsIgnoreCase("FS") || commandLabel.equalsIgnoreCase("FireworkShow")) && args.length == 3){
    14. try{
    15. final Long hashMapID = (new Random()).nextLong();
    16. final Player player = (Player) sender;
    17. final Location location = player.getLocation();
    18. final List<Type> type = new ArrayList<Type>();
    19. final List<Color> colour = new ArrayList<Color>();
    20. Collections.addAll(type, Type.BALL, Type.BALL_LARGE, Type.BURST, Type.STAR, Type.CREEPER);
    21. Collections.addAll(colour, Color.AQUA, Color.BLACK, Color.BLUE, Color.FUCHSIA, Color.GRAY, Color.GREEN, Color.LIME, Color.MAROON, Color.NAVY, Color.OLIVE, Color.ORANGE, Color.PURPLE, Color.RED, Color.SILVER, Color.TEAL, Color.WHITE, Color.YELLOW);
    22. fireworkTimer.put(hashMapID, System.currentTimeMillis());
    23. new BukkitRunnable(){
    24. public void run(){
    25. for(int i = -2; i < 3; i++){
    26. Firework firework = player.getWorld().spawn(new Location(location.getWorld(), location.getX() + (i * 5), location.getY(), location.getZ()), Firework.class);
    27. FireworkMeta data = (FireworkMeta) firework.getFireworkMeta();
    28. data.addEffects(FireworkEffect.builder().withColor(colour.get((new Random()).nextInt(17))).withColor(colour.get((new Random()).nextInt(17))).withColor(colour.get((new Random()).nextInt(17))).with(type.get((new Random()).nextInt(5))).trail((new Random()).nextBoolean()).flicker((new Random()).nextBoolean()).build());
    29. data.setPower((new Random()).nextInt(2) + 2);
    30. firework.setFireworkMeta(data);
    31. }
    32. if((System.currentTimeMillis() - fireworkTimer.get(hashMapID) > (Double.parseDouble(args[0]) * 1000))){
    33. fireworkTimer.remove(hashMapID);
    34. this.cancel();
    35. }
    36. }
    37. }.runTaskTimer(this, 0, Integer.parseInt(args[1]) / 50);
    38. }catch(NumberFormatException e){ }
    39. }
    40. return false;
    41. }
    42. }


    Results:
    Here is one firework show with a frequency of 500 milliseconds and a distance of 5 metres.
    http://imgur.com/ZAcsk,3MwNm,mwn0c
     
    bossomeness likes this.
  19. Offline

    bossomeness

    I have made a simple trolling plugin. The whole plugin and the plugin.yml are under 50 lines :)
    Code:java
    1.  
    2. package me.bossomeness.troll;
    3. import java.util.logging.Logger;
    4. import org.bukkit.Bukkit;
    5. import org.bukkit.ChatColor;
    6. import org.bukkit.World;
    7. import org.bukkit.command.Command;
    8. import org.bukkit.command.CommandSender;
    9. import org.bukkit.entity.Player;
    10. import org.bukkit.plugin.PluginDescriptionFile;
    11. import org.bukkit.plugin.java.JavaPlugin;
    12. public class Troll extends JavaPlugin {
    13. public final Logger logger = Logger.getLogger("Minecraft");
    14. @Override
    15. public void onEnable() {
    16. PluginDescriptionFile pdffile = this.getDescription();
    17. this.logger.info(pdffile.getName() + " Version " + pdffile.getVersion()
    18. + " Has Been Enabled!");}
    19. @Override
    20. public void onDisable() {
    21. PluginDescriptionFile pdffile = this.getDescription();
    22. this.logger.info(pdffile.getName() + " Version " + pdffile.getVersion()
    23. + " Has Been Disabled!");}
    24. @Override
    25. public boolean onCommand(CommandSender sender, Command command,
    26. String commandLabel, String[] args) {
    27. if (commandLabel.equalsIgnoreCase("prize")) {
    28. if (args.length >= 1) {
    29. float explosionPower = 5.0F;
    30. Player target = Bukkit.getServer().getPlayer(args[0]);
    31. if (target != null) {
    32. World world = target.getWorld();
    33. target.getWorld().createExplosion(target.getLocation(),
    34. explosionPower);
    35. world.createExplosion(target.getLocation(), explosionPower);
    36. } else {
    37. sender.sendMessage(ChatColor.RED + "User is not online.");
    38. }
    39. } else {
    40. sender.sendMessage(ChatColor.RED + "Insufficient Parameters.");
    41. }}
    42. return false;}}
    43.  

    Here is the plugin.yml
    Code:
    main: me.bossomeness.troll
    name: Troll
    version: 1.0
    author: bossomeness
    description: Troll a player with the /prize command.
    commands:
        prize:
            description: Trolls the player.
     
    Fishrock123 likes this.
  20. Offline

    Digi

    bossomeness
    That could've been way under 50 lines if you got rid of the enable/disable messages which are sent by bukkit anyways, yours are extra.
    You also don't need to store World if you're going to use it once.
    And I recommend you use getPlayerExact() when you have the exact name because it's faster.
     
  21. Offline

    drtshock Retired Staff

    Someone requested an exp multiplier plugin so this is what I came up with in about 10 minutes. Exactly 50 lines. Debating whether or not I want another really simple project on bukkitdev :p

    Code:java
    1. package me.shock.expmultiplier;
    2.  
    3. import java.io.File;
    4.  
    5. import org.bukkit.ChatColor;
    6. import org.bukkit.command.Command;
    7. import org.bukkit.command.CommandSender;
    8. import org.bukkit.event.EventHandler;
    9. import org.bukkit.event.Listener;
    10. import org.bukkit.event.player.PlayerExpChangeEvent;
    11. import org.bukkit.plugin.java.JavaPlugin;
    12.  
    13. public class Main extends JavaPlugin implements Listener {
    14.  
    15. int multiplier;
    16. public void onEnable() {
    17. getServer().getPluginManager().registerEvents(this, this);
    18. if(!(new File(getDataFolder() + File.separator + "config.yml").exists())) saveDefaultConfig();
    19. this.multiplier = getConfig().getInt("multiplier");
    20. }
    21. public void onDisable() {
    22. if(!(this.multiplier == getConfig().getInt("multiplier"))) {
    23. getConfig().set("multiplier", this.multiplier);
    24. saveConfig();
    25. }
    26. }
    27. @EventHandler
    28. public void onExpChange(PlayerExpChangeEvent event) {
    29. if(this.multiplier == 1) return;
    30. if(event.getPlayer().hasPermission("expmultiplier.use")) {
    31. event.setAmount(event.getAmount() * this.multiplier);
    32. }
    33. }
    34. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    35. if(cmd.getName().equalsIgnoreCase("em")) {
    36. if(args.length == 0) {
    37. sender.sendMessage(ChatColor.GREEN + "Current multiplier: " + ChatColor.GRAY + this.multiplier); return true;
    38. }
    39. if(args.length == 1 && sender.hasPermission("expmultiplier.set")) {
    40. if(args[0].matches("^[0-9]{1,3}$")) {
    41. this.multiplier = Integer.parseInt(args[0]);
    42. sender.sendMessage(ChatColor.GREEN + "Set exp multiplier to " + ChatColor.GRAY + args[0]); return true;
    43. }
    44. } else {
    45. sender.sendMessage(ChatColor.RED + "Correct usage: /em <multiplier>");
    46. }
    47. }
    48. return true;
    49. }
    50. }
     
    afistofirony likes this.
  22. Offline

    Scizzr

    Very simple ping plugin. Written for CraftBukkit 1.5 Beta

    Commands:
    • Player or console
    ○ /ping <name> : Show the ping of a player
    • Player only
    ○ /ping : Show your own ping

    Permissions:
    • None!



    plugin.yml
    Code:
    main: com.example.ping.Ping
     
    name: Ping
    version: 1.5-Beta
    description: Simple ping command
    author: Scizzr
    authors: [cembry90]
     
    commands:
      ping:
        description: See a player's ping
        usage:
          - /ping          | See your own ping
          - /ping <name>    | See another player's ping
    
    Ping.class
    Code:
    package com.scizzr.ping;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.craftbukkit.v1_5_R1.entity.CraftPlayer;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Ping extends JavaPlugin {
        public void onEnable() {
            getCommand("ping").setExecutor(new CommandExecutor() {
                public boolean onCommand(CommandSender s, Command cmd, String lbl, String[] args) {
                    String name = null;
                    if (args.length == 0) {
                        if (!(s instanceof Player)) {
                            msg(s, "&cYou don't have a ping... You're console!");
                            return true;
                        } else {
                            name = ((Player)s).getName();
                        }
                    } else {
                        name = args[0];
                    }
                    Player p = Bukkit.getServer().getPlayer(name);
                    if (p == null) { msg(s, "Invalid player named ''"); return true; }
                    msg(s, String.format((args.length == 0 ? "&aYour" : String.format("&e%s&a's", p.getName())) + " ping is &e%d", ((CraftPlayer)p).getHandle().ping));
                    return true;
                }
            });
        }
     
        public void msg(CommandSender s, String msg) {
            s.sendMessage(ChatColor.translateAlternateColorCodes('&', "&6[&ePing&6] &r" + msg));
        }
    }
     
    
     
  23. Offline

    md_5

    Make it version independent :p
     
  24. Offline

    YoFuzzy3

    29 lines.
    Code:java
    1. package com.fuzzoland.Ping;
    2. import org.bukkit.command.*;
    3. import org.bukkit.entity.Player;
    4. import org.bukkit.plugin.java.JavaPlugin;;
    5. public class Main extends JavaPlugin{
    6. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    7. if(commandLabel.equalsIgnoreCase("ping")){
    8. if(sender instanceof Player){
    9. String name = getServer().getClass().getPackage().getName();
    10. String version = name.substring(name.lastIndexOf('.') + 1);
    11. Player player = (Player) sender;
    12. if(version.equals("craftbukkit")){
    13. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.entity.CraftPlayer) player).getHandle().ping + "ms.");
    14. }else if(version.equals("v1_4_5")){
    15. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer) player).getHandle().ping + "ms.");
    16. }else if(version.equals("v1_4_6")){
    17. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer) player).getHandle().ping + "ms.");
    18. }else if(version.equals("v1_4_R1")){
    19. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.v1_4_R1.entity.CraftPlayer) player).getHandle().ping + "ms.");
    20. }else if(version.equals("v1_5_R1")){
    21. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.v1_5_R1.entity.CraftPlayer) player).getHandle().ping + "ms.");
    22. }else if(version.equals("v1_5_R2")){
    23. player.sendMessage("Your ping is " + ((org.bukkit.craftbukkit.v1_5_R2.entity.CraftPlayer) player).getHandle().ping + "ms.");
    24. }
    25. }
    26. }
    27. return false;
    28. }
    29. }


    [​IMG]
     
    drtshock likes this.
  25. Offline

    md_5

    Still requires compile depends + updating for new jars. What about int ping = player.getClass().getDeclaredMethod("getHandle").invoke().getClass().getDeclaredField("ping");

    Or similar
     
    Cirno and jorisk322 like this.
  26. Offline

    chaseoes Retired Staff

    ChatPing: Plays a "ping!" sound when your name is said in the chat.
    26 lines!

    Code:java
    1. package me.chaseoes.chatping;
    2.  
    3. import org.bukkit.Sound;
    4. import org.bukkit.entity.Player;
    5. import org.bukkit.event.EventHandler;
    6. import org.bukkit.event.EventPriority;
    7. import org.bukkit.event.Listener;
    8. import org.bukkit.event.player.AsyncPlayerChatEvent;
    9. import org.bukkit.plugin.java.JavaPlugin;
    10.  
    11. public class ChatPing extends JavaPlugin implements Listener {
    12.  
    13. public void onEnable() {
    14. getServer().getPluginManager().registerEvents(this, this);
    15. }
    16.  
    17. @EventHandler(priority = EventPriority.MONITOR)
    18. public void onChat(AsyncPlayerChatEvent event) {
    19. for (Player player : event.getRecipients()) {
    20. if (event.getMessage().contains(player.getName())) {
    21. player.playSound(player.getLocation(), Sound.ORB_PICKUP, 60f, 0f);
    22. }
    23. }
    24. }
    25.  
    26. }


    Source on GitHub

    Edit: aww. Probably isn't thread safe. :(
     
    LaxWasHere, gomeow and afistofirony like this.
  27. Offline

    codename_B

    Did someone say version independant in 37 lines?

    Would be 35 without comments
    Code:
    package com.bpermissions.ping;
    import java.lang.reflect.*;
    import org.bukkit.Bukkit;
    import org.bukkit.command.*;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    public class Ping extends JavaPlugin {
        private Method player_getHandle = null;
        private Field player_ping = null;
        private static Method getMethod(Class<?> cl, String method) {
            for(Method m : cl.getMethods()) if(m.getName().equals(method)) return m; return null;
        }
        private static Field getField(Class<?> cl, String field) {
            for(Field f : cl.getFields()) if(f.getName().equals(field)) return f; return null;
        }
        public boolean onCommand(CommandSender s, Command cmd, String lbl, String[] args) {
            String[] vars = new String[] {null, "ERROR"};
            if (args.length == 0 && !(s instanceof Player)) {
                s.sendMessage("You don't have a ping... You're console!"); return true;
            } else if(args.length == 0) {
                vars[0] = ((Player)s).getName();
            } else {
                vars[0] = args[0];
            }
            Player p = Bukkit.getServer().getPlayer(vars[0]);
            if (p == null) { s.sendMessage("Invalid player named '"+vars[0]+"'"); return true; }
            // player_getHandle.invoke() == CraftPlayer.getHandle();
            if(player_getHandle == null) player_getHandle = getMethod(p.getClass(), "getHandle");
            Object nmsPlayer = null;
            try { nmsPlayer = player_getHandle.invoke(p, (Object[]) null); } catch (Exception e) {}
            // player_ping.get() == net.minecraft.server.EntityPlayer.ping
            if(player_ping == null) player_ping = getField(nmsPlayer.getClass(), "ping");
            try { vars[1] = String.valueOf(player_ping.get(nmsPlayer)); } catch (Exception e) {}
            s.sendMessage(String.format((args.length == 0 ? "Your" : String.format("&e%s&a's", p.getName())) + " ping is &e%d", vars[1]));
            return true;
        }
    }
    
     
    chasechocolate and YoFuzzy3 like this.
  28. Offline

    md_5

    private static Method getMethod(Class<?> cl, String method) {
    for(Method m : cl.getMethods()) if(m.getName().equals(method)) return m; return null;
    }
    private static Field getField(Class<?> cl, String field) {
    for(Field f : cl.getFields()) if(f.getName().equals(field)) return f; return null;
    }

    codename_B why do you waste 6 lines like that? getClass().getDeclared[field/method](name)
     
  29. Offline

    Scizzr

    Stop making CraftBukkit version dependent :p

    I see what you did there. :cool:

    md_5 : 27 lines, version independent :D
    Code:java
    1. package com.scizzr.ping;
    2.  
    3. import java.lang.reflect.*;
    4. import org.bukkit.*;
    5. import org.bukkit.command.*;
    6. import org.bukkit.entity.Player;
    7. import org.bukkit.plugin.java.JavaPlugin;
    8.  
    9. public class Ping extends JavaPlugin {
    10. public void onEnable() {
    11. getCommand("ping").setExecutor(new CommandExecutor() {
    12. public boolean onCommand(CommandSender s, Command cmd, String lbl, String[] args) {
    13. try {
    14. String name = args.length == 1 ? args[0] : (s instanceof Player ? ((Player)s).getName() : null);
    15. if (name == null) { s.sendMessage("§6[§ePing§6]§r §cConsole doesn't have a ping."); return true; }
    16. Player player = Bukkit.getServer().getPlayer(name);
    17. if (player == null) { s.sendMessage("§6[§ePing§6]§r " + String.format("§cInvalid player named '§e%s§c'", args[0])); return true; }
    18. Method player_getHandle = player.getClass().getMethod("getHandle");
    19. Object player_MC = player_getHandle.invoke(player, (Object[]) null);
    20. Field player_ping = player_MC.getClass().getField("ping");
    21. s.sendMessage("§6[§ePing§6]§r " + String.format((args.length == 0 ? "§aYour" : String.format("§e%s§a's", player.getName())) + " ping is §e%d", Integer.valueOf(String.valueOf(player_ping.get(player_MC)))));
    22. } catch (Exception ex) { ex.printStackTrace(); }
    23. return true;
    24. }
    25. });
    26. }
    27. }
     
  30. Offline

    codename_B

    Good question, I've always had bad luck with getDeclared[field/method] somehow not picking up the thing I want.
    Scizzr, nice!
     
    Scizzr likes this.
Thread Status:
Not open for further replies.

Share This Page