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

    kyle1320

    Not that it's super laggy or inefficient, just that I turned what should be multiple line stuff into one or two lines just to get it under 50 :p Like so:
    Code:
    for (Block b : oldBlocks) {if (oldMats.containsKey(b)) {b.setTypeId(oldMats.get(b).getId(), false); oldMats.remove(b);}}
    It just feels like cheating to me. Anyway, I could see myself doing a few more of these for practice shortening / optimizing code
     
  2. Offline

    codename_B

    Fun ain't they? Just something a bit different for when big plugins stop becoming a challenge and more of a tedium :p
     
  3. Offline

    rmh4209

    LivingWorld - Regenerate Your World Dynamically (48 Lines)
    Code:
    package org.inesgar.LivingWorld;
     
    import java.util.Random;
    import java.util.logging.Logger;
     
    import org.bukkit.Chunk;
    import org.bukkit.World;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class LivingWorld extends JavaPlugin
    {
     
        private static final Logger log = Logger.getLogger("Minecraft");
     
        @Override
        public void onEnable()
        {
            getServer().getScheduler().scheduleAsyncRepeatingTask(this,
                    new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            for (World w : getServer().getWorlds())
                            {
                                for (Chunk chunk : w.getLoadedChunks())
                                {
                                    Random rand = new Random();
                                    if (rand.nextInt(1) == 1)
                                    {
                                        w.regenerateChunk(chunk.getX(),
                                                chunk.getZ());
                                        break;
                                    }
                                }
                            }
                        }
                    }, 20L * 1, 20L * 30);
            log.info("[LivingWorld] Enabled.");
        }
     
        @Override
        public void onDisable()
        {
            getServer().getScheduler().cancelTasks(this);
            log.info("[LivingWorld] Disabled.");
        }
    }
    
     
  4. rmh4209 Are you sure regenerateChunk() is a threadsafe API call? Also this:
    if (rand.nextInt(1) == 1)
    will always return true as rand.nextInt(1) returns a value between 0 (exclusive) and the given value (inclusive), so in that case always 1. If you want a 50/50 change, why not use if (rand.nextBoolean())? :)
     
  5. Offline

    rmh4209

    I was reading up on the Java documentation website that 0 is inclusive and the given value is exclusive (link here: Random). Also, it's not perfectly polished yet. My completely finished version is going to check for WorldGuard and PreciousStones regions before regenerating and have the range be more 0-100 or something similar. Also, I'm not entirely sure if I should use Synchronous or Asynchronous for the runnable after reading this: Thread Safe Scheduler Programming. It appears I should use Synchronous since it calls a Bukkit method.
     
  6. Offline

    IDragonfire

    not

    Code:
    package sl.nuclearw.under50clc;
    import java.util.logging.Logger;
    import org.bukkit.*;
    public class clc extends JavaPlugin {
        public void onEnable() {       
            getServer().getPluginManager().registerEvent(Event.Type.SERVER_COMMAND, new clcServerListener(), Event.Priority.LOW, this};
            getLogger().log(Level.INFO, "Version " + this.getDescription().getVersion());
        }
        public void onDisable() {
            getLogger().log(Level.INFO, "Version " + this.getDescription().getVersion());
        } 
    }
    class clcServerListener extends ServerListener {
        public void onServerCommand(ServerCommandEvent event) {
            event.setCommand((event.getCommand().startsWith("/")) ? event.getCommand().substring(1) : "say " + event.getCommand());
        }
    }
    
    or

    Code:
    package sl.nuclearw.under50clc;
    import java.util.logging.Logger;
    import org.bukkit.*;
    public class clc extends JavaPlugin {
        public void onEnable() {       
            getServer().getPluginManager().registerEvent(Event.Type.SERVER_COMMAND, new clcServerListener(), Event.Priority.LOW, this};
        }
    }
    class clcServerListener extends ServerListener {
        public void onServerCommand(ServerCommandEvent event) {
            event.setCommand((event.getCommand().startsWith("/")) ? event.getCommand().substring(1) : "say " + event.getCommand());
        }
    }
    
    (not tested)

    ups, new Event System

    Code:
    package sl.nuclearw.under50clc;
    import java.util.*;
    import org.bukkit.*;
    public class clc extends JavaPlugin {
        public void onEnable() {       
            getServer().getPluginManager().registerEvent(this, new clcServerListener()};
        }   
    }
    class clcServerListener extends ServerListener {
        @EventHandler{priority = EventPriority.LOW}
        public void onServerCommand(ServerCommandEvent event) {
            event.setCommand((event.getCommand().startsWith("/")) ? event.getCommand().substring(1) : "say " + event.getCommand());
        }
    }
    
     
  7. Offline

    jacklin213

    Omg this is just what I was looking for thanks
     
  8. Offline

    desht

    Autohop: players automatically try jump onto blocks when they move into them (like Minecraft Pocket Edition does), in 46 lines of code:

    PHP:
    package me.desht.autohop;
    import java.util.*;
    public class 
    AutoHop extends org.bukkit.plugin.java.JavaPlugin implements org.bukkit.event.Listener {
            private static 
    Set<Integerpassable = new HashSet<Integer>();
            static {
                    for (
    int i : new Integer[] { 08962728303132373839405051555963656668697072757678838590939496104105106111115119131132 }) { passable.add(i); }
            }
            @
    Override
            
    public void onEnable() {
                    
    getServer().getPluginManager().registerEvents(thisthis);
            }
            @
    org.bukkit.event.EventHandler(ignoreCancelled true)
            public 
    void onPlayerMove(org.bukkit.event.player.PlayerMoveEvent event) {
                    
    org.bukkit.Location from event.getFrom(), to event.getTo();
                    
    double dx to.getX() - from.getX(), dz to.getZ() - from.getZ();
                    
    double nextX to.getX() + dxnextZ to.getZ() + dz;
                    
    double tx nextX Math.floor(nextX), tz nextZ Math.floor(nextZ);
                    
    float yaw to.getYaw() % 360;
                    if (
    yaw 0yaw += 360;
                    
    org.bukkit.block.BlockFace face null;
                    if (
    yaw >= 45 && yaw 135 && dx <= 0.0 && tx 0.3001face org.bukkit.block.BlockFace.NORTH;
                    else if (
    yaw >= 135 && yaw 225 && dz <= 0.0 && tz 0.3001face org.bukkit.block.BlockFace.EAST;
                    else if (
    yaw >= 225 && yaw 315 && dx >= 0.0 && tx 0.6999face org.bukkit.block.BlockFace.SOUTH;
                    else if ((
    yaw >= 315 || yaw 45) && dz >= 0.0 && tz 0.6999face org.bukkit.block.BlockFace.WEST;
                    else return;
                    
    org.bukkit.block.Block b to.getBlock().getRelative(face);
                    
    boolean climbable false;
                    if (
    b.getTypeId() == 67 || b.getTypeId() == 53)
                            
    climbable = ((org.bukkit.material.Stairs)b.getState().getData()).getAscendingDirection() == face;
                    else if (
    b.getTypeId() == 44 || b.getTypeId() == 126)
                            
    climbable true;
                    if (!
    climbable && !passable.contains(b.getTypeId())) {
                            
    int id1 b.getRelative(0,1,0).getTypeId(), id2 b.getRelative(0,2,0).getTypeId();
                            if ((
    passable.contains(id1) || (id1 == 44 || id1 == 126) && standingOnSlab(from)) && passable.contains(id2)) {
                                    if (
    from.getY() % 0.0001 && !passable.contains(from.getBlock().getRelative(0,-1,0).getTypeId()) || from.getBlock().getTypeId() == 67 || from.getBlock().getTypeId() == 53 || standingOnSlab(from)) {
                                            
    org.bukkit.util.Vector v event.getPlayer().getVelocity();
                                            
    v.setY(0.37);
                                            
    event.getPlayer().setVelocity(v);
                                    }
                            }
                    }
            }
            private 
    boolean standingOnSlab(org.bukkit.Location l) {
                    return (
    l.getBlock().getTypeId() == 44 || l.getBlock().getTypeId() == 126) && l.getY() % <= 0.51;
            }
    }
    This is a considerably condensed version of my published AutoHop plugin (the full AutoHop.java is here) - only thing lacking is the Metrics support (and a lot of code readability :) )
     
  9. Offline

    md_5

    That is very nice.
     
  10. You're right, I mixed it up, sorry. :(
    Yes, sync is the way to go, especially if you plan to hook into other plugins from within the runnable, too. :)
     
  11. Offline

    superpeanut911

    EnderGrenades
    Makes EnderPearls grenades and stops world explosion damage, 25 lines (I think)
    Code:
    package net.endercraftbuild;
     
    import org.bukkit.Location;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.EntityExplodeEvent;
    import org.bukkit.event.player.PlayerTeleportEvent;
    public class EnderGrenade extends JavaPlugin implements Listener{
            public void onEnable(){
            getLogger().info("EnderGrenades by superpeanut911 has been enabled!");
            getServer().getPluginManager().registerEvents(this, this); }
            public void onDisable(){
            getLogger().info("EnderGrenades has been disabled!"); }
            @EventHandler
            public void preventTeleportandturnEnderPearlsIntoGrenades(PlayerTeleportEvent Event) {
            if(Event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL) {
              Event.setCancelled(true);
              Location toExplode = Event.getTo();
              Event.getPlayer().getWorld().createExplosion(toExplode, 5F); }}
            @EventHandler
            public void preventLandDestructionOnExplode(EntityExplodeEvent event) {
                event.blockList().clear();
            }{}
    {}}
     
  12. superpeanut911
    You could've saved at least 2 lines by removing the enabled and disabled messages which are extra, bukkit already sends them for each plugin it activates or deactivates. :p

    But you have a few "{}", those are code blocks which are empty, they're kinda pointless, any reason why you did that ?
     
  13. Offline

    superpeanut911

    Eclipse was bugging me... those made it stop bugging me.... I'm pretttty new at coding so lol.
     
  14. That's no solution.

    I strongly recommend you first learn how to code properly because this thread throws some very important good coding habbits out the window.... like readability and efficiency.
    Sure, small code is great... but only when it's efficient! Most codes posted here are not efficient because the coders literally cut corners to fit in the 50 line limit.
    This is fine for experienced coders which understand the code and know how to properly write it... but it's a very bad example for new coders.
     
    rmh4209 likes this.
  15. Offline

    JayzaSapphire

    IpLogger - 46 lines.

    Code:
    package me.JayzaSapphire;
     
    import java.util.Arrays;
    import java.util.List;
     
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerLoginEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class IpLogger extends JavaPlugin implements Listener {
     
    public void onEnable() {
    getConfig().options().copyDefaults(true);
    saveConfig();
    reloadConfig();
    getServer().getPluginManager().registerEvents(this, this);
    }
     
    @EventHandler
    public void onPlayerLogin(PlayerLoginEvent event) {
    Player user = event.getPlayer();
    String ip = event.getAddress().getHostAddress();
     
    if (getConfig().getString("users." + user.getName()) == null) {
    getConfig().set("users." + user.getName(), Arrays.asList(ip));
    saveConfig();
    }
     
    if (!getConfig().getStringList("users." + user.getName()).contains(ip)) {
    List<String> list = getConfig().getStringList("users." + user.getName());
    list.add(ip);
    getConfig().set("users." + user.getName(), list);
    saveConfig();
    }
    }
    }
    Code:
    # IpLogger
    users: {}
    Code:
    name: IpLogger
    main: me.JayzaSapphire.IpLogger
    version: 0.1
    author: JayzaSapphire
    
     
  16. Offline

    md_5

    I was about to fix your post for you, and then you ninja'd me.
     
    CraftThatBlock and codename_B like this.
  17. Offline

    JayzaSapphire

    I attempted to change the code to java, failed epicly, not sure how to do it.
     
  18. Offline

    kyle1320

    Another entry :D
    Code:
    package me.kyle1320.Under50;
    import java.util.HashMap;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    public class Under50 extends JavaPlugin{
        public HashMap<String, HashMap<Block, Material>> lastAction = new HashMap<String, HashMap<Block, Material>>();
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
            if (sender instanceof Player) {
                Player player = (Player)sender;
                Integer radius = 1, height = 1;
                Material mat = player.getItemInHand().getType();
                if (args.length == 2) {
                    try {radius = Integer.parseInt(args[0]);}catch (NumberFormatException e) {}
                    try {height = Integer.parseInt(args[1]);}catch (NumberFormatException e) {}}
                if (args.length == 1) try {radius = Integer.parseInt(args[0]);}catch (NumberFormatException e) {}
                if (!mat.isBlock()) mat = Material.AIR;
                if (cmd.getName().equalsIgnoreCase("circle")) return this.makeCircle(player, player.getLocation(), radius, 1, mat, false, false, true);
                if (cmd.getName().equalsIgnoreCase("hcircle")) return this.makeCircle(player, player.getLocation(), radius, 1, mat, true, false, false);
                if (cmd.getName().equalsIgnoreCase("cylinder")) return this.makeCircle(player, player.getLocation(), radius, height, mat, false, false, true);
                if (cmd.getName().equalsIgnoreCase("hcylinder")) return this.makeCircle(player, player.getLocation(), radius, height, mat, true, false, false);
                if (cmd.getName().equalsIgnoreCase("sphere")) return this.makeCircle(player, player.getLocation(), radius, 1, mat, false, true, true);
                if (cmd.getName().equalsIgnoreCase("hsphere")) return this.makeCircle(player, player.getLocation(), radius, 1, mat, true, true, false);
                if (cmd.getName().equalsIgnoreCase("undo") && lastAction.containsKey(player.getName()))
                    for (Block b : lastAction.get(player.getName()).keySet()) b.setType(lastAction.get(player.getName()).get(b));
                    lastAction.remove(player.getName());
                    return true;
            } return false;
        }
        public boolean makeCircle(Player player, Location loc, Integer r, Integer h, Material m, Boolean hollow, Boolean sphere, Boolean tele) {
            int cx = loc.getBlockX();
            int cy = loc.getBlockY();
            int cz = loc.getBlockZ();
            HashMap<Block, Material> old = new HashMap<Block, Material>();
            for (int x = cx - r; x <= cx +r; x++)
                for (int z = cz - r; z <= cz +r; z++)
                    for (int y = (sphere ? cy - r : cy); y < (sphere ? cy + r : cy + h); y++) {
                        double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0);
                        if (dist < r*r && !(hollow && dist < (r-1)*(r-1))) {
                            old.put(loc.getWorld().getBlockAt(x, y, z), loc.getWorld().getBlockAt(x, y, z).getType());
                            loc.getWorld().getBlockAt(x, y, z).setType(m);}}
            lastAction.put(player.getName(), old);
            if (tele) player.teleport(player.getWorld().getHighestBlockAt(player.getLocation()).getLocation());
            return true;
        }
    }
    (This is pushing it a little)

    Shaper! Shape your world. Includes seven commands; circle, hcircle, cylinder, hcylinder, sphere, hsphere, and undo. The first six commands will create shapes around the player corresponding with their names. For example:
    "/circle 5" will create a solid horizontal circle with radius 5 around the player made out of the material the player is holding.
    "/hcircle 5" will create a hollow horizontal circle with radius 5 around the player made out of the material the player is holding.
    "/cylinder 5 5" will create a solid cylinder radius 5 height 5.
    "/hsphere 5" will create a hollow sphere radius 5.
    The "/undo" command will remove the last shape the player created.

    50 lines :D
    Edit: Thanks for the help Digi, went from 50 to 41 lines.
    Edit 2: Now with /undo command! Back up to 50 lines.
     
    desht and izak12345678910 like this.
  19. 48 lines if you remove the spam:
    Code:
        @Override public void onDisable() {System.out.println("Shaper disabled.");}
        @Override public void onEnable() {System.out.println("Shaper enabled.");}
    And you could've made it even smaller, instead of:
    Code:
                    if (!sphere)
                        for (int y = cy; y < cy + h; y++) {
                            double dist = (cx - x) * (cx -x) + (cz - z) * (cz - z);
                            if (dist < r*r)
                                if (!(hollow && dist < (r-1)*(r-1))) loc.getWorld().getBlockAt(x, y, z).setType(m);
                        }
                    else
                        for (int y = cy - r; y <= cy + r; y++) {
                            double dist = (cx - x) * (cx -x) + (cz - z) * (cz - z) + (cy - y) * (cy - y);
                            if (dist < r*r)
                                if (!(hollow && dist < (r-1)*(r-1))) loc.getWorld().getBlockAt(x, y, z).setType(m);
                        }
    You can just do:
    Code:
                    for (int y = (sphere ? cy - r : cy); y < (sphere ? cy + r : cy + h); y++) {
                        double dist = (cx - x) * (cx -x) + (cz - z) * (cz - z) + (sphere ? 0 : (cy - y) * (cy - y));
                        if (dist < r*r && !(hollow && dist < (r-1)*(r-1)))
                            loc.getWorld().getBlockAt(x, y, z).setType(m);
                    }
    You should always avoid duplicating code.
     
    -_Husky_- likes this.
  20. Offline

    kyle1320

    Awesome, I knew there had to be some way of compacting them into one loop. Thanks!
     
  21. DragonFix - exactly 50 lines:
    Code:java
    1. package com.modcrafting.dragonfix;
    2.  
    3. import org.bukkit.Chunk;
    4. import org.bukkit.World;
    5. import org.bukkit.craftbukkit.entity.CraftEnderDragon;
    6. import org.bukkit.entity.EnderDragon;
    7. import org.bukkit.entity.Entity;
    8. import org.bukkit.event.EventHandler;
    9. import org.bukkit.event.EventPriority;
    10. import org.bukkit.event.entity.CreatureSpawnEvent;
    11. import org.bukkit.event.entity.EntityExplodeEvent;
    12. import org.bukkit.event.world.ChunkLoadEvent;
    13. import org.bukkit.event.world.ChunkUnloadEvent;
    14.  
    15. public class DragonFix extends org.bukkit.plugin.java.JavaPlugin implements org.bukkit.event.Listener {
    16. public void onEnable() {
    17. for(World w: getServer().getWorlds())
    18. for(Chunk c: w.getLoadedChunks())
    19. chunkLoad(new ChunkLoadEvent(c, false));
    20. getServer().getPluginManager().registerEvents(this, this);
    21. }
    22. public void onDisable() {
    23. for(World w: getServer().getWorlds())
    24. for(Chunk c: w.getLoadedChunks())
    25. chunkUnload(new ChunkUnloadEvent(c));
    26. }
    27. @EventHandler(priority = EventPriority.MONITOR)
    28. public void chunkLoad(ChunkLoadEvent event) {
    29. for(Entity e: event.getChunk().getEntities())
    30. if(e instanceof EnderDragon)
    31. ((CraftEnderDragon)e).getHandle().X = false;
    32. }
    33. @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    34. public void chunkUnload(ChunkUnloadEvent event) {
    35. for(Entity e: event.getChunk().getEntities())
    36. if(e instanceof EnderDragon)
    37. ((CraftEnderDragon)e).getHandle().X = true;
    38. }
    39. @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    40. public void dragonSpawn(CreatureSpawnEvent event) {
    41. if(event.getEntity() instanceof EnderDragon)
    42. ((CraftEnderDragon)event.getEntity()).getHandle().X = false;
    43. }
    44. @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
    45. public void dragonExplode(EntityExplodeEvent event)
    46. {
    47. if(event.getEntity() instanceof EnderDragon)
    48. event.blockList().clear();
    49. }
    50. }

    Credits go to Deathmarine too.
    Explaination:
    This stops dragons from flying through blocks. If you ask why there is a EntityExplodeEvent listener: Well, the dragon is still able to pass some blocks (like torches) or fly a bit into others (like glass panes) which would explode if we wouldn't clear the list. No config, no permissions, no commands. To enable it simply put the compiled jar in the plugins folder and to disable it remove the jar again. ;)
     
  22. Offline

    md_5

    V10lator nice.
    Your signature also confused me for a bit.
     
  23. How to explain this? Well, it throws block how they should be thrown. :D
    Code:java
    1. package de.V10lator.V10Throw;
    2.  
    3. public class V10Throw extends org.bukkit.plugin.java.JavaPlugin implements org.bukkit.event.Listener
    4. {
    5. public void onEnable() {
    6. getServer().getPluginManager().registerEvents(this, this);
    7. }
    8. @org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.HIGHEST, ignoreCancelled = true)
    9. public void throwMe(org.bukkit.event.player.PlayerDropItemEvent event) {
    10. org.bukkit.entity.Item it = event.getItemDrop();
    11. org.bukkit.inventory.ItemStack is = it.getItemStack();
    12. org.bukkit.Location loc = it.getLocation();
    13. org.bukkit.util.Vector v = it.getVelocity().multiply(2.0D);
    14. org.bukkit.World w = loc.getWorld();
    15. org.bukkit.Material mat = is.getType();
    16. org.bukkit.entity.FallingBlock fb;
    17. int am = is.getAmount();
    18. int dr = 0;
    19. byte d = is.getData().getData();
    20. for(int i = 0; i < is.getAmount(); i++) {
    21. try {
    22. fb = w.spawnFallingBlock(loc, mat, d);
    23. }
    24. fb = null;
    25. }
    26. if(fb != null) {
    27. fb.setVelocity(v);
    28. am--;
    29. dr++;
    30. }
    31. }
    32. if(am < 1)
    33. event.setCancelled(true);
    34. else
    35. is.setAmount(am);
    36. org.bukkit.entity.Player p = event.getPlayer();
    37. if(p.getGameMode() != org.bukkit.GameMode.CREATIVE && dr > 0) {
    38. is = p.getItemInHand();
    39. am = is.getAmount() - dr;
    40. if(am < 1)
    41. p.setItemInHand(null);
    42. else
    43. is.setAmount(am);
    44. }
    45. }
    46. }
     
  24. Offline

    slam5000

    I love this thread! It's like code golf for Bukkit plugins :D
    I might have to make something to post here!

    Well that was fast :p I suppose it is a shortest code type thing. Anyway, I made a GUI window for bukkit in under 50 lines. Doesn't do too much (because of the constraint), but maybe I'll continue it without the 50 line limit cause it seems like a cool concept!
    Code:java
    1. package com.ztg.bukkitgui;
    2. import java.awt.event.WindowEvent;
    3. import java.awt.event.WindowListener;
    4. import java.util.logging.Handler;
    5. import java.util.logging.LogRecord;
    6. import javax.swing.JFrame;
    7. import javax.swing.JScrollPane;
    8. import javax.swing.JTextArea;
    9. import org.bukkit.event.Listener;
    10. import org.bukkit.plugin.java.JavaPlugin;
    11. public class Main extends JavaPlugin implements Listener {
    12. public static JTextArea log = new JTextArea();
    13. public static JFrame console = new JFrame("Minecraft Server");
    14. public static JScrollPane sbrText;
    15. public static Main instance;
    16. public void onEnable() {
    17. instance = this;
    18. getServer().getLogger().addHandler(new GuiLogger());
    19. console.setVisible(true);
    20. sbrText = new JScrollPane(log);
    21. sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    22. console.add(sbrText);
    23. console.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    24. console.addWindowListener(new WindowListener() {
    25. public void windowOpened(WindowEvent arg0) { }
    26. public void windowIconified(WindowEvent arg0) {}
    27. public void windowDeiconified(WindowEvent arg0) {}
    28. public void windowDeactivated(WindowEvent arg0) {}
    29. public void windowClosing(WindowEvent e) {
    30. Main.instance.getLogger().info("Shutting down server...");
    31. try {
    32. Thread.sleep(3000);
    33. } catch (InterruptedException e1) {}
    34. Main.instance.getServer().shutdown();
    35. }
    36. public void windowClosed(WindowEvent arg0) {}
    37. public void windowActivated(WindowEvent arg0) {}
    38. });
    39. }
    40. private class GuiLogger extends Handler {
    41. public void close() throws SecurityException {}
    42. public void flush() {}
    43. public void publish(LogRecord lr) {
    44. if (lr.getMessage() != null) {
    45. Main.log.setText(Main.log.getText() + "\n" + lr.getMessage().replaceAll("\\[.*?m", ""));
    46. sbrText.getVerticalScrollBar().setValue(sbrText.getVerticalScrollBar().getMaximum() + 1);
    47. }
    48. }}
    49. }


    I probably should mention this now, but if anyone's actually interested in seeing the finished product, keep checking my bukkitdev, here's a quick screenie of what I have done so far (not in 50 lines of code, but i figured I'd post after this just so people who were interested could take a look, and know I am continuing the project)

    [​IMG]

    So yeah, currently you can kick, ban, set gamemode, and the little
    icon in the bottom is the input mode. The input mode can either be
    "command" (basic commands) "chat" (/say) or "shout" (/broadcast)

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

    md_5

  26. Offline

    slam5000

    Oh there will be colours :) The colors are hidden away in the Map Gui I'm adding. It basically displays a map
    of your server rendered live (surprisingly, there's really no performance issues with it) showing loaded chunk birds-eye views, and player locations. That's FULL of colors! It will also show a player's face's skin when u click on them in the map view! (my favorite feature so far... well... click and drag to teleport on the map view might be cooler...)
     
    chasechocolate likes this.
  27. Offline

    Me4502

    You should make it also work remotely. A lot of people use hosted servers.
     
  28. Yery true. Maybe BukkitHTTPD may help you with its API.
     
  29. Offline

    YoFuzzy3

    Zombies, skeletons and creepers will drop their heads with the same chances as wither skeleton do in Vanilla Minecraft. It also accounts for the Looting enchantment and calculates it accordingly. There's also a permission, SkullDrops.use.

    EDIT: Now just 43 lines and more efficient.
    Code:java
    1. package com.fuzzoland.SkullDrops;
    2. import java.util.Random;
    3. import org.bukkit.Location;
    4. import org.bukkit.Material;
    5. import org.bukkit.enchantments.*;
    6. import org.bukkit.entity.*;
    7. import org.bukkit.event.*;
    8. import org.bukkit.event.entity.*;
    9. import org.bukkit.inventory.ItemStack;
    10. import org.bukkit.plugin.java.JavaPlugin;
    11. public class Main extends JavaPlugin implements Listener{
    12. public void onEnable(){
    13. getServer().getPluginManager().registerEvents(this, this);
    14. }
    15. @EventHandler
    16. public void onEntityDeath(EntityDeathEvent event){
    17. if(event.getEntity().getKiller() instanceof Player){
    18. float random = (new Random()).nextFloat();
    19. Player player = (Player) event.getEntity().getKiller();
    20. LivingEntity entity = event.getEntity();
    21. if(player.hasPermission("SkullDrops.use")){
    22. if(player.getItemInHand().containsEnchantment(new EnchantmentWrapper(21))){
    23. if(random < (0.025f + (player.getItemInHand().getEnchantmentLevel(new EnchantmentWrapper(21)) / 200))){
    24. dropSkull(entity, entity.getLocation(), player);
    25. }
    26. }else{
    27. if(random < 0.025f){
    28. dropSkull(entity, entity.getLocation(), player);
    29. }
    30. }
    31. }
    32. }
    33. }
    34. private void dropSkull(LivingEntity entity, Location location, Player player){
    35. if(entity.getType() == EntityType.SKELETON){
    36. location.getWorld().dropItemNaturally(location, new ItemStack (Material.SKULL_ITEM, 1, (byte) 0));
    37. }else if(entity.getType() == EntityType.ZOMBIE){
    38. location.getWorld().dropItemNaturally(location, new ItemStack (Material.SKULL_ITEM, 1, (byte) 2));
    39. }else if(entity.getType() == EntityType.CREEPER){
    40. location.getWorld().dropItemNaturally(location, new ItemStack (Material.SKULL_ITEM, 1, (byte) 4));
    41. }
    42. }
    43. }
     
    afistofirony likes this.
  30. Offline

    tuxed

    Block rewards in 48 lines, includes Vault support and basic anti-cheat. I call it MiningCashLite:
    Code:
    package com.tropicalwikis.tuxcraft.plugins.miningcash;
    public class MiningCashLite extends org.bukkit.plugin.java.JavaPlugin implements org.bukkit.event.Listener {
        private net.milkbowl.vault.economy.Economy econ;
        private java.util.ArrayList<String> recentlyPlacedOres = new java.util.ArrayList<String>();
        @Override
        public void onEnable() {
            if (!setupEconomy()) {
                getLogger().severe("Vault not found! Disabling plugin.");
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
            getServer().getPluginManager().registerEvents(this, this);
        }
        @Override
        public void onDisable() {
            econ = null;
            recentlyPlacedOres = null;
        }
        private String locationToString(org.bukkit.Location l) {
            return l.getWorld().getName() + ":" + l.getBlockX() + "," + l.getBlockY() + "," + l.getBlockZ();
        }
        @org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
        public boolean onBlockPlace(org.bukkit.event.block.BlockPlaceEvent evt) {
            return recentlyPlacedOres.add(locationToString(evt.getBlock().getLocation()));
        }
        @org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
        public boolean onBlockBreak(org.bukkit.event.block.BlockBreakEvent evt) {
            if (evt.isCancelled() || !evt.getPlayer().hasPermission("miningcashlite.reward")) {
                return true;
            }
            if (recentlyPlacedOres.contains(locationToString(evt.getBlock().getLocation()))) {
                recentlyPlacedOres.remove(locationToString(evt.getBlock().getLocation()));
                return true;
            }
            econ.depositPlayer(evt.getPlayer().getName(), 0.5);
            return true;
        }
        private boolean setupEconomy() {
            if (getServer().getPluginManager().getPlugin("Vault") != null) {
                org.bukkit.plugin.RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> rsp = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
                if (rsp != null) {
                    econ = rsp.getProvider();
                    return econ != null;
                }
            }
            return false;
        }
    }
    Okay, I cheated. Here's a 49-line version, no cheating:
    Code:
    package com.tropicalwikis.tuxcraft.plugins.miningcash;
    import java.util.ArrayList;
    import net.milkbowl.vault.economy.Economy;
    import org.bukkit.Location;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockBreakEvent;
    import org.bukkit.event.block.BlockPlaceEvent;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    public class MiningCashLite extends JavaPlugin implements Listener {
        private Economy econ;
        private ArrayList<String> recentlyPlacedOres = new ArrayList<String>();
        @Override
        public void onEnable() {
            if (getServer().getPluginManager().getPlugin("Vault") != null) {
                RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
                if (rsp != null) {
                    econ = rsp.getProvider();
                }
            } else {
                getLogger().severe("Vault not found! Disabling plugin.");
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
            getServer().getPluginManager().registerEvents(this, this);
        }
        private String locationToString(Location l) {
            return l.getWorld().getName() + ":" + l.getBlockX() + "," + l.getBlockY() + "," + l.getBlockZ();
        }
        @EventHandler(priority = EventPriority.MONITOR)
        public boolean onBlockPlace(BlockPlaceEvent evt) {
            recentlyPlacedOres.add(locationToString(evt.getBlock().getLocation()));
            return true;
        }
        @EventHandler(priority = EventPriority.MONITOR)
        public boolean onBlockBreak(BlockBreakEvent evt) {
            if (evt.isCancelled() || !evt.getPlayer().hasPermission("miningcashlite.reward")) {
                return true;
            }
            if (recentlyPlacedOres.contains(locationToString(evt.getBlock().getLocation()))) {
                recentlyPlacedOres.remove(locationToString(evt.getBlock().getLocation()));
                return true;
            }
            econ.depositPlayer(evt.getPlayer().getName(), 0.5);
            return true;
        }
    }
    Let's top things off with a port of the rolling hills generator to the new interface. It's 50 lines, and I didn't cheat this time. Also, that version didn't work with the latest Bukkit. This one does.

    Code:
    package com.tropicalwikis.tuxcraft.plugins.deisolate;
    import java.util.Random;
    import org.bukkit.World;
    import org.bukkit.generator.ChunkGenerator;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.util.noise.SimplexOctaveGenerator;
    public class Deisolate extends JavaPlugin {
        @Override
        public ChunkGenerator getDefaultWorldGenerator(String w, String i) {
            return new GEN();
        }
        class GEN extends ChunkGenerator {
            SimplexOctaveGenerator gen = null;
            double noise = 1.0;
            public boolean canSpawn(World world, int x, int z) {
                return true;
            }
            public void setBlock(byte[][] result, int x, int y, int z, byte blkid) {
                try {
                    if (result[y >> 4] == null) {
                        result[y >> 4] = new byte[4096];
                    }
                } catch (Exception e) {
                    return;
                }
                if(x <= 15 && z<=15) {
                    result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;
                }
            }
            public byte[][] generateBlockSections(World world, Random random, int chunkX, int chunkZ, BiomeGrid biomeGrid) {
                byte[][] res = new byte[16][];
                if(gen==null) {
                    gen =  new SimplexOctaveGenerator(random, 8);
                    gen.setScale(1/64.0);
                }
                for (int x=0; x<16; x++) {
                    for (int z=0; z<16; z++){
                        noise = gen.noise(x+chunkX*16, z+chunkZ*16, 0.5, 0.5)*16;
                        for(int y=0; y<32+noise; y++){
                            if(y==0)
                            setBlock(res, x, y, z, (byte) 7);
                            else
                            setBlock(res, x, y, z, (byte) 1);
                        }
                    }
                }
                return res;
            }
        }
    }
    I plan to modify it for a server concept that is still somewhat sketchy at the moment.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Oct 29, 2015
Thread Status:
Not open for further replies.

Share This Page