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

    AmoebaMan

    Uhhh....

    codename_B I'm a bit disappointed...what the heck is this?

    Code:
    event.setCancelled((event.getEntity() instanceof Player) ? true : false);
    D:
     
  2. Offline

    TheE

    This is a short form for:
    Code:java
    1. if (event.getEntity() instanceof Player) {
    2. //Cancel the event
    3. event.setCancelled(true);
    4. } else {
    5. //Don't cancel the event
    6. event.setCancelled(false);
    7. }

    See here if you are interested in some more details.
     
  3. Offline

    desht

    Yeah, but it's a long form for:
    Code:
    event.setCancelled(event.getEntity() instanceof Player);
    
    :)
     
    Cirno, chasechocolate and md_5 like this.
  4. Offline

    TheE

    True. I think you might say that there is always a better alternative, if at least on of the return values is true or false. But it becomes handy if you have something like this:
    Code:java
    1. executor.sendMessage((player != null ? player.getName() : args[1]) + "has been...");
     
  5. Offline

    AmoebaMan

    I know what ternary operators are and how they're used.

    What I got irritated about and what desht picked up on was the HORRIBLE redundancy of using a ternary operator with the second and third arguments being boolean values. You're making the computer perform several extra operations for absolutely no reason.
     
    desht likes this.
  6. Offline

    YoFuzzy3

    Code:java
    1. package com.fuzzoland.EndOfTheWorld;
    2.  
    3. import org.bukkit.event.EventHandler;
    4. import org.bukkit.event.EventPriority;
    5. import org.bukkit.event.Listener;
    6. import org.bukkit.event.world.EndOfTheWorldEvent;
    7. import org.bukkit.plugin.java.JavaPlugin;
    8.  
    9. public class Main extends JavaPlugin implements Listener{
    10.  
    11. public void onEnable(){
    12. getServer().getPluginManager().registerEvents(this, this);
    13. }
    14.  
    15. @EventHandler(priority=EventPriority.HIGH)
    16. private void onEndOfTheWorld(EndOfTheWorldEvent event){
    17. if(event.getAsteroidImpact() == true){
    18. event.commence();
    19. }else{
    20. event.setCancelled(true);
    21. }
    22. }
    23. }
     
  7. Offline

    md_5

    == true. Wat, just use if (event.getAsteroidImpact())
     
    Cirno and chasechocolate like this.
  8. Offline

    YoFuzzy3

    How about if(event.getAsteroid().isApproaching()) ? :p

    Players will drop their heads when they get killed in PvP, using the new API in 31 lines; with the permission PlayerHeads.use. :D

    Code:java
    1. package com.fuzzoland.PlayerHeads;
    2. import org.bukkit.Location;
    3. import org.bukkit.Material;
    4. import org.bukkit.entity.Player;
    5. import org.bukkit.event.*;
    6. import org.bukkit.event.entity.PlayerDeathEvent;
    7. import org.bukkit.inventory.ItemStack;
    8. import org.bukkit.inventory.meta.SkullMeta;
    9. import org.bukkit.plugin.java.JavaPlugin;
    10. public class Main extends JavaPlugin implements Listener{
    11. public void onEnable(){
    12. getServer().getPluginManager().registerEvents(this, this);
    13. }
    14. @EventHandler
    15. public void onPlayerDeath(PlayerDeathEvent event){
    16. if(event.getEntity() instanceof Player){
    17. Player killed = (Player) event.getEntity();
    18. if(event.getEntity().getKiller() instanceof Player){
    19. Player killer = (Player) event.getEntity().getKiller();
    20. if(killer.hasPermission("PlayerHeads.use")){
    21. Location location = killed.getLocation();
    22. ItemStack skullItem = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
    23. SkullMeta metaData = (SkullMeta) skullItem.getItemMeta();
    24. metaData.setOwner(killed.getName());
    25. skullItem.setItemMeta(metaData);
    26. location.getWorld().dropItemNaturally(location, skullItem);
    27. }
    28. }
    29. }
    30. }
    31. }


    Get a welcome book when first joining the server with a custom title, author name and content all set in a configuration file, using the new API in 33 lines. You can also use colours in the books' content.

    Class:
    Code:java
    1. package com.fuzzoland.WelcomeBook;
    2. import java.util.List;
    3. import org.bukkit.Bukkit;
    4. import org.bukkit.Material;
    5. import org.bukkit.entity.Player;
    6. import org.bukkit.event.*;
    7. import org.bukkit.event.player.PlayerJoinEvent;
    8. import org.bukkit.inventory.*;
    9. import org.bukkit.inventory.meta.BookMeta;
    10. import org.bukkit.plugin.java.JavaPlugin;
    11. public class Main extends JavaPlugin implements Listener{
    12. public void onEnable(){
    13. getConfig().options().copyDefaults(true);
    14. saveConfig();
    15. Bukkit.getServer().getPluginManager().registerEvents(this, this);
    16. }
    17. @EventHandler
    18. public void onPlayerJoin(PlayerJoinEvent event){
    19. Player player = event.getPlayer();
    20. if(!player.hasPlayedBefore()){
    21. List <String> pages = getConfig().getStringList("BookPages");
    22. ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, 1);
    23. BookMeta metaData = (BookMeta) bookItem.getItemMeta();
    24. metaData.setTitle(getConfig().getString("BookName"));
    25. metaData.setAuthor(getConfig().getString("AuthorName"));
    26. for(String page : pages){
    27. metaData.addPage(page.replaceAll("(&([a-f0-9]))", "\u00A7$2"));
    28. }
    29. bookItem.setItemMeta(metaData);
    30. player.getInventory().addItem(bookItem);
    31. }
    32. }
    33. }


    Example config:
    Code:
    BookName: Welcome Book
    AuthorName: Herobrine
    BookPages:
    - '&2This is the first page of the book.'
    - '&6This is the second page of the book.'
    - '&9This is the third page of the book.'
    - '&aE&bt&cc.'
    Result:
    View attachment 12038

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Oct 29, 2015
  9. Offline

    codename_B

    Jeez... People can't see humor in things these days.
     
    chasechocolate likes this.
  10. Offline

    Fishrock123


    Niiicee. That's a great plugin for the under 50 challenge! ^_^

    You should make it official and upload it to bukkitdev. :p
     
  11. Offline

    YoFuzzy3

    I already did before you even asked! http://dev.bukkit.org/server-mods/welcomebook :D
    Going to be expanding the plugin with new great features. :)
     
  12. Offline

    chaseoes

    I added the exact same thing into FirstJoinPlus 4 hours before you. :( Only I used text files because I thought string lists would be too confusing to make line breaks with.

    Edit: Oh, didn't even see you mentioned FirstJoinPlus in the description! :p
     
  13. Offline

    YoFuzzy3

    Right after I posted the project I saw it was already in your plugin. But I'm expanding mine with a lot more features now anyway.

    EDIT: Taking full advantage of the new API! ;) http://dev.bukkit.org/server-mods/welcomebook/files/2-welcome-book-v2-0/
     
  14. Offline

    ftbastler

    Now a <50 lines of code plugin for a random gigantic firework show. :p
     
  15. Offline

    gabizou

    And thanks to one of the newer changes in 1.4.6-R0.2-SNAPSHOT, we can spawn fireworks :)
     
  16. Offline

    AmoebaMan

    44 line plugin to store the IPs of players logging in, and notify you if two different players are using the same IP. Designed to help server admins detect players using alternate accounts.

    Permission node to get notified is altmaster.notify

    Code:java
    1. import java.io.File;
    2. import java.util.List;
    3. import org.bukkit.Bukkit;
    4. import org.bukkit.ChatColor;
    5. import org.bukkit.configuration.file.YamlConfiguration;
    6. import org.bukkit.entity.Player;
    7. import org.bukkit.event.EventHandler;
    8. import org.bukkit.event.Listener;
    9. import org.bukkit.event.player.PlayerLoginEvent;
    10. import org.bukkit.plugin.java.JavaPlugin;
    11. public class AltMaster extends JavaPlugin implements Listener{
    12. private File recordsFile;
    13. private YamlConfiguration records;
    14. public void onEnable(){
    15. getDataFolder().mkdirs();
    16. recordsFile = new File(getDataFolder().getPath() + "/records.yml");
    17. try{
    18. if(!recordsFile.exists())
    19. recordsFile.createNewFile();
    20. records = new YamlConfiguration();
    21. records.options().pathSeparator('>');
    22. records.load(recordsFile);
    23. getLogger().info("Loaded records"); }
    24. catch(Exception e){ e.printStackTrace(); }
    25. Bukkit.getPluginManager().registerEvents(this, this); }
    26. public void onDisable(){
    27. try{ records.save(recordsFile); }
    28. catch(Exception e){
    29. getLogger().info("Failed to save records");
    30. e.printStackTrace(); } }
    31. @EventHandler
    32. public void logLogins(PlayerLoginEvent event){
    33. if(event.getAddress() == null) return;
    34. String playerName = event.getPlayer().getName();
    35. String address = event.getAddress().toString();
    36. List<String> addressUsers = records.getStringList(address);
    37. if(!addressUsers.contains(playerName))
    38. addressUsers.add(playerName);
    39. if(addressUsers.size() > 1){
    40. Bukkit.getConsoleSender().sendMessage("" + ChatColor.DARK_BLUE + ChatColor.BOLD + "WARNING: " + ChatColor.BLUE + playerName + " logs in from the same address as: " + addressUsers);
    41. for(Player player : Bukkit.getOnlinePlayers()) if(player.hasPermission("altmaster.notify")) player.sendMessage("" + ChatColor.DARK_BLUE + ChatColor.BOLD + "WARNING: " + ChatColor.BLUE + playerName + " logs in from the same address as: " + addressUsers);
    42. }
    43. records.set(address, addressUsers);
    44. onDisable(); } }
     
    YoFuzzy3 likes this.
  17. Offline

    YoFuzzy3

    AmoebaMan
    You can make it 2 lines shorter by compacting the imports. ;)

    Ok this plugin made me think a lot, and I'm quite proud of it. It lets you type /RF <length> <frequency> <distance> and it will start a firework show at the location where you typed in the command. Length being how long the firework show should last in seconds, Frequency being the interval between every firework in milliseconds, and Distance being the distance between the 3 firework spawn points in metres.

    All fireworks are completely random, the plugin chooses 3 random colours, 1 random type, whether to have a trail, whether to flicker, and a random height in every firework. The original plugin was just 40 lines and it would start fireworks at one location, but then I realised at the cost of 10 extra lines I could make that into 3 different locations for fireworks to launch from, making the finished plugin exactly 50 plugins. The only limitation is that you can only have 1 firework show at a time, I even put a check in to make sure that you can't start a 2nd one otherwise it would create an infinite loop.

    EDIT: Thanks to Bone008 I managed to eliminate having to use the task ID which limited it to 1 firework show at a time. My new version of the plugin let's you have as many firework shows as you want at any one time (provided the hashMapID isn't drawn twice, one in many billion chance for that to happen lol). It is now 2 lines less as well. :D

    Code:
    Code:java
    1. package com.fuzzoland.RandomFireworks;
    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("RF.use") && sender instanceof Player && commandLabel.equalsIgnoreCase("RF") && args.length == 3){
    14. final Long hashMapID = (new Random()).nextLong();
    15. final Player player = (Player) sender;
    16. final Location location = player.getLocation();
    17. final List<Type> type = new ArrayList<Type>();
    18. final List<Color> colour = new ArrayList<Color>();
    19. Collections.addAll(type, Type.BALL, Type.BALL_LARGE, Type.BURST, Type.STAR, Type.CREEPER);
    20. 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);
    21. fireworkTimer.put(hashMapID, System.currentTimeMillis());
    22. new BukkitRunnable(){
    23. public void run(){
    24. Firework firework1 = player.getWorld().spawn(new Location(location.getWorld(), location.getX() + Integer.parseInt(args[2]), location.getY(), location.getZ()), Firework.class);
    25. Firework firework2 = player.getWorld().spawn(location, Firework.class);
    26. Firework firework3 = player.getWorld().spawn(new Location(location.getWorld(), location.getX(), location.getY(), location.getZ() + Integer.parseInt(args[2])), Firework.class);
    27. FireworkMeta data1 = (FireworkMeta) firework1.getFireworkMeta();
    28. FireworkMeta data2 = (FireworkMeta) firework2.getFireworkMeta();
    29. FireworkMeta data3 = (FireworkMeta) firework3.getFireworkMeta();
    30. data1.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());
    31. data2.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());
    32. data3.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());
    33. data1.setPower((new Random()).nextInt(2) + 2);
    34. data2.setPower((new Random()).nextInt(2) + 2);
    35. data3.setPower((new Random()).nextInt(2) + 2);
    36. firework1.setFireworkMeta(data1);
    37. firework2.setFireworkMeta(data2);
    38. firework3.setFireworkMeta(data3);
    39. if((System.currentTimeMillis() - fireworkTimer.get(hashMapID) > (Integer.parseInt(args[0]) * 1000))){
    40. fireworkTimer.remove(hashMapID);
    41. this.cancel();
    42. }
    43. }
    44. }.runTaskTimer(this, 0, Integer.parseInt(args[1]) / 50);
    45. }
    46. return false;
    47. }
    48. }


    Results:
    Here are some results using frequency of 200 milliseconds and a distance of 5 metres apart. This was before multiple firework show support.
    imgur.com/PBgPe,SwGEj



    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Oct 29, 2015
  18. Offline

    LaxWasHere

    Lol, didn't know there was a color called FUCHSIA"FUCHSIA"
     
  19. Offline

    YoFuzzy3

    Lol yeah and another odd thing is that there's 17 colours, unlike the 16 dyes. Maybe they put a colour for the default firework that doesn't have a dye?
     
  20. Offline

    codename_B

    Is there a way to spawn *just* the explosion yet as occurs in the net.minecraft.server.EntityFireworks.java?
    Code:
    world.broadcastEntityEffect(this, (byte)17);
    
    Otherwise someone is going to have to do some tasty reflection work (not me).
     
  21. Offline

    Deathmarine

    Ah damn I was ninja'd.. oh well post anyways.

    January 1 Fireworks
    Code:java
    1. package com.modcrafting.under50;
    2.  
    3. import java.util.Calendar;
    4. import java.util.Random;
    5. import org.bukkit.Bukkit;
    6. import org.bukkit.Color;
    7. import org.bukkit.FireworkEffect;
    8. import org.bukkit.Location;
    9. import org.bukkit.entity.EntityType;
    10. import org.bukkit.entity.Firework;
    11. import org.bukkit.inventory.meta.FireworkMeta;
    12. import org.bukkit.entity.Player;
    13. import org.bukkit.plugin.java.JavaPlugin;
    14. public class Fireworks extends JavaPlugin{
    15. int timer,id = 0;
    16. Random gen = new Random();
    17. public void onEnable(){
    18. id = this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
    19. @Override
    20. public void run() {
    21. if(Calendar.getInstance().get(Calendar.YEAR)>2012&&timer<600&&Bukkit.getServer().getOnlinePlayers().length>0){
    22. for(Player player:Bukkit.getServer().getOnlinePlayers()){
    23. for(int i = gen.nextInt(10);i>0;i--){
    24. Location loc = player.getLocation();
    25. Firework item = (Firework) loc.getWorld().spawnEntity(loc, EntityType.FIREWORK);
    26. FireworkMeta fwm = item.getFireworkMeta();
    27. fwm.setPower(gen.nextInt(4)+1);
    28. fwm.addEffect(FireworkEffect.builder().with(FireworkEffect.Type.values()[gen.nextInt(FireworkEffect.Type.values().length)]).flicker(gen.nextBoolean()).trail(gen.nextBoolean()).withColor(Color.fromRGB(gen.nextInt(255), gen.nextInt(255), gen.nextInt(255))).withFade(Color.fromRGB(gen.nextInt(255), gen.nextInt(255), gen.nextInt(255))).build());
    29. item.setFireworkMeta(fwm);
    30. }
    31. }
    32. timer++;
    33. if(timer>600){
    34. Bukkit.getScheduler().cancelTask(id);
    35. Bukkit.getPluginManager().disablePlugin(Bukkit.getPluginManager().getPlugin("Fireworks"));
    36. }
    37. }
    38. }
    39. }, 20L, 20L);
    40. }
    41. }

    I don't understand why the "builder" is setup the way it is but whatever.
     
  22. Offline

    codename_B

    A nano version of my FireworkEffectPlayer
    http://forums.bukkit.org/threads/util-fireworkeffectplayer-v1-0.119424/

    Play fireworks at a specific location, without the wait for the Bukkit api!
    Code:
    package com.bpermissions;
    import java.lang.reflect.Method;
    import org.bukkit.entity.Firework;
    import org.bukkit.inventory.meta.FireworkMeta;
    import org.bukkit.*;
    public class FireworkEffectPlayerNano {
        private Object[] dataStore = new Object[5];
        public void playFirework(World world, Location loc, FireworkEffect fe) throws Exception {
            Firework fw = (Firework) world.spawn(loc, Firework.class);
            if(dataStore[0] == null) dataStore[0] = getMethod(world.getClass(), "getHandle");
            if(dataStore[2] == null) dataStore[2] = getMethod(fw.getClass(), "getHandle");
            dataStore[3] = ((Method) dataStore[0]).invoke(world, (Object[]) null);
            dataStore[4] = ((Method) dataStore[2]).invoke(fw, (Object[]) null);
            if(dataStore[1] == null) dataStore[1] = getMethod(dataStore[3].getClass(), "broadcastEntityEffect");
            FireworkMeta data = (FireworkMeta) fw.getFireworkMeta();
            data.addEffect(fe);
            fw.setFireworkMeta(data);
            ((Method) dataStore[1]).invoke(dataStore[3], new Object[] {dataStore[4], (byte) 17});
            fw.remove();
        }
        private static Method getMethod(Class<?> cl, String method) {
            for(Method m : cl.getMethods()) if(m.getName().equals(method)) return m;
            return null;
        }
    }
    
    I know it's not technically a plugin, but shhh...
    25 lines!
     
  23. Offline

    chasechocolate

  24. Offline

    YoFuzzy3

    I think he stopped putting plugins into the OP a while ago because of the character limit per post.
     
  25. Offline

    codename_B

    Right you are.
     
  26. Offline

    Deathmarine

    Nice reflection. But couldn't you use getWorld from the location object.
     
  27. Offline

    codename_B

    Indeed you could, convenience took precedence. I just wanted to have a nice CraftWorld to getHandle from ;)
     
  28. Offline

    YoFuzzy3

    Not sure if somebody already made something like this. But I made a lightweight Announcer plugin that supports all formatting codes in just 25 lines. It lets you set an interval and supports up to 2,147,483,647 messages in the configuration file.

    Code:java
    1. package com.fuzzoland.Announcer;
    2. import java.util.List;
    3. import org.bukkit.plugin.java.JavaPlugin;
    4. import org.bukkit.scheduler.BukkitRunnable;
    5. public class Main extends JavaPlugin{
    6. private static int count;
    7. public void onEnable(){
    8. getConfig().options().copyDefaults(true);
    9. saveConfig();
    10. final List<String> messages = getConfig().getStringList("Announcer.Messages");
    11. final int interval = getConfig().getInt("Announcer.Interval") * 20;
    12. count = 1;
    13. new BukkitRunnable(){
    14. public void run(){
    15. if(count < messages.size()){
    16. getServer().broadcastMessage(messages.get(count - 1).replaceAll("(&([a-f0-9l-or]))", "\u00A7$2"));
    17. count++;
    18. }else if(count == messages.size()){
    19. getServer().broadcastMessage(messages.get(count - 1).replaceAll("(&([a-f0-9l-or]))", "\u00A7$2"));
    20. count = 1;
    21. }
    22. }
    23. }.runTaskTimer(this, interval, interval);
    24. }
    25. }
     
  29. Offline

    desht

    YoFuzzy3 room for shrinkage there - replace lines 12-23 with:
    Code:java
    1.  
    2. private int count = 0;
    3. new BukkitRunnable(){
    4. public void run(){
    5. getServer().broadcastMessage(messages.get(count).replaceAll("(&([a-f0-9l-or]))", "\u00A7$2"));
    6. count = (count + 1) % messages.size();
    7. }
    8. }.runTaskTimer(this, interval, interval);
    9.  

    (and delete line 6)
     
  30. Offline

    YoFuzzy3

    Nice thinking.
     
Thread Status:
Not open for further replies.

Share This Page