Sammy tutorials - Small chunks of code that may help you

Discussion in 'Resources' started by Sammy, Mar 31, 2011.

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

    Sammy

    So, I learn many things from this forum, and now I feel it's time to share the knowledge not only by answering to questions but making small contributions that may help.

    Please feel free to correct me if you think there's a better way to do some of the things I'm showing here

    The ant anthology - Storing data in files
    Introduction - Just why and a thanks (open)
    I have seen many variations of how too do this, in my opinion using the java Properties Class is the way to go, I must give a huge thanks to samkio, cause' he was the one who show us this on one of his tutorials

    Storing an awsome Object
    The object can be anything, from a integer to a string or even a location, you just need to know that you are storing everything necessary.
    Lets do a simple one:
    Code:
    private static final File FileP = new File("plugins/account.txt");
    Code:
        public void MakeLoan(Player p, int amountMoney, int amountBones) {
            Properties prop = new Properties();
            String Key = p.getName().toLowerCase();
            try {
                FileInputStream in = new FileInputStream(FileP);
                prop.load(in);
                prop.put(Key, amountMoney + ";" + amountBones);
                prop.store(new FileOutputStream(FileP), "[Name]= amount");
            } catch (Exception ex) {
            }
        }
    Nerdy content (open)
    Using a regex like ";" makes it extra easy to get the values back

    The idea is, you use a unique key for each entry and store the info you want, easy no? cake time: [cake]
    Now some times you need to know if that key already exists right ?

    Does the Key exists?
    Code:
        public boolean DoesItExists(Player p) {
            Properties prop = new Properties();
            String Key = p.getName().toLowerCase();
            try {
                FileInputStream in = new FileInputStream(FileP);
                prop.load(in);
                if (prop.containsKey(Key)) {
                    return true;
                }
            } catch (IOException ex) {
            }
            return false;
        }
    Easy one no ? no cake this time
    Lets add some bling bling to that guys account:

    Make it rain!!
    Code:
            public void MakeItRain(Player p, int amount) {
            Properties prop = new Properties();
            String Key = p.getName().toLowerCase();
            try {
                FileInputStream in = new FileInputStream(FileP);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] money = values.split(";");
                int Initial = Integer.parseInt(money[0]) + amount;
                money[0] = String.valueOf(Initial);
                String propString = money[0] + ";" + money[1];
                prop.put(Key, propString);
                prop.store(new FileOutputStream(FileP), "[Name]=Money;Bones");
            } catch (Exception ex) {
            }
        }
    Nerdy content 2 (open)
    See ? using the regex I splited the string parsed the 1st value to a integer and added the amount... after you just need to make it a string again... DONT forger the other values (in this case the sweet sweet bones)

    So now you feel like 50cent, you made it rain... but lets be a struggling rockstar and check if he have the $$ for a 6pack

    Am I broke or what?
    Code:
                public boolean AmIBrokeOrWhat(String p, int amount) {
            Properties prop = new Properties();
            String Key = p.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(FileP);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] money = values.split(";");
                int value = Integer.parseInt(money[0]);
                if (value >= amount) {
                    return true;
                } else {
                }
            } catch (Exception ex) {
            }
            return false;
        }
    We have just barley for a soda, lets pay the guy that knows a guy

    PayUPman
    Code:
                    public void TakeMoney(String p, int amount) {
            Properties prop = new Properties();
            String Key = p.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(FileP);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] money = values.split(";");
                int Initial = Integer.parseInt(money[0]) - amount;
                money[0] = String.valueOf(Initial);
                String propString = money[0] + ";" + money[1];
                prop.put(Key, propString);
                prop.store(new FileOutputStream(FileP), "[Name]=Money;Bones");
            } catch (Exception ex) {
            }
        }
    Ok we had cake and a soda now its time to say goodbye.... but here have some more examples:

    The good ones are always hiden
    I'll make a prison for your heart

    Code:
        private static final File WantedList = new File("plugins/RPGmod/bountyhunter/prisons.txt");
    
        public boolean HasPrison(String p) {
            Properties prop = new Properties();
            String Key = p.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                if (prop.containsKey(Key)) {
                    return true;
                }
            } catch (IOException ex) {
            }
            return false;
        }
    
        public void RegPrison(String p, Location loc, Location locR, Location locL, Location sign) {
            Properties prop = new Properties();
            String Key = p.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                prop.put(Key, loc.getBlockX() + ";" + loc.getBlockY() + ";" + loc.getBlockZ() + ";" + loc.getWorld() + ";" + locR.getBlockX() + ";" + locR.getBlockY() + ";" + locR.getBlockZ() + ";" + locR.getWorld() + ";" + locL.getBlockX() + ";" + locL.getBlockY() + ";" + locL.getBlockZ() + ";" + locL.getWorld() + ";" + sign.getBlockX() + ";" + sign.getBlockY() + ";" + sign.getBlockZ() + ";" + sign.getWorld());
                prop.store(new FileOutputStream(WantedList), "[Name]=Location");
            } catch (Exception ex) {
            }
        }
    
        public Location GetPrisonLocation(Player p, String s) {
            Properties prop = new Properties();
            String Key = s.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] qnt = values.split(";");
                Location loc = p.getLocation();
                loc.setX(Double.parseDouble(qnt[0]));
                loc.setY(Double.parseDouble(qnt[1]));
                loc.setZ(Double.parseDouble(qnt[2]));
                return loc;
            } catch (Exception ex) {
            }
            return null;
        }
    
        public Location GetChestR(Player p, String s) {
            Properties prop = new Properties();
            String Key = s.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] qnt = values.split(";");
                Location loc = p.getLocation();
                loc.setX(Double.parseDouble(qnt[4]));
                loc.setY(Double.parseDouble(qnt[5]));
                loc.setZ(Double.parseDouble(qnt[6]));
                return loc;
            } catch (Exception ex) {
            }
            return null;
        }
    
        public Location GetChestL(Player p, String s) {
            Properties prop = new Properties();
            String Key = s.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] qnt = values.split(";");
                Location loc = p.getLocation();
                loc.setX(Double.parseDouble(qnt[8]));
                loc.setY(Double.parseDouble(qnt[9]));
                loc.setZ(Double.parseDouble(qnt[10]));
                return loc;
            } catch (Exception ex) {
            }
            return null;
        }
    
        public Location GetSign(Player p, String s) {
            Properties prop = new Properties();
            String Key = s.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                String values = prop.getProperty(Key);
                String[] qnt = values.split(";");
                Location loc = p.getLocation();
                loc.setX(Double.parseDouble(qnt[12]));
                loc.setY(Double.parseDouble(qnt[13]));
                loc.setZ(Double.parseDouble(qnt[14]));
                return loc;
            } catch (Exception ex) {
            }
            return null;
        }
    
        public void RemovePrison(String p) {
            Properties prop = new Properties();
            String Key = p.toLowerCase();
            try {
                FileInputStream in = new FileInputStream(WantedList);
                prop.load(in);
                prop.remove(Key);
                prop.store(new FileOutputStream(WantedList), "[Name]=Location");
            } catch (Exception ex) {
          


    Set the controls for the heart of the sun - Scheduling Tasks

    To thread or not to Thread (open)
    So, schedules are very useful and I have seen many coders using Java classes that are NOT thread safe, what this means ? every time you use them a creeper is born somewhere CLOSE [creeper] TO YOU
    Ok not really... but you can create lag or even mess up the server...
    So, the good folks that are making bukkit come up with a great solution: Bukkit based Schedules (Name not yet rated)

    If you didn't opened the spoiler, DON'T use classes like java timers they may or may not explode your PC
    Code:
    SAFE TO USE --> int     scheduleSyncDelayedTask (Plugin plugin, Runnable task, long delay)
    SAFE TO USE --> int     scheduleSyncDelayedTask (Plugin plugin, Runnable task)
    SAFE TO USE --> int     scheduleSyncRepeatingTask (Plugin plugin, Runnable task, long delay, long period)
    
    int     scheduleAsyncDelayedTask (Plugin plugin, Runnable task, long delay)
    int     scheduleAsyncDelayedTask (Plugin plugin, Runnable task)
    int     scheduleAsyncRepeatingTask (Plugin plugin, Runnable task, long delay, long period)
    synchronous - run on the server thread
    Asynchronous will create a new thread, only use them if you're sure that it won't mess up the server thread
    Lets start:

    Tick tick tick tick BOOOM (The Hives song :p) - One time schedule
    Delayed Tasks are very very useful of things that will happen after a chill-out session ^^
    Code:
     int OneTime = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
    
                public void run() {
                    //WTF BOOOOOM\\
                }
            }, 60 * 20L);
    TIPS:
    -- Every 1 second the server "counts" 20 ticks so 1minute = 60*20L
    -- You can implement the Runnable on another class just by doing new MyClass() and implementing Runnable on that class

    Shoot me all night long (AC/DC anyone??) - Repeating Schedule
    Maybe you want to repeat the schedule every so often:
    Code:
    int Repeat = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
    
                public void run() {
                  //Shoot me once shoot me twice\\
                }
            }, 120 * 21L, 60 * 21L);
    
        }
    TIPS:
    -- 120 * 21L --> Triggers 2 minutes after start
    -- 60* 21L --> The following times it triggers every 1 minute
    -- 21L why ? if you use this in conjunction with a one time schedule, 1tick will help the reppeting schedule not trigger at the same time as the other one

    How could I stop once I start(Rolling stones) - Stopping Schedules
    As you may have seen, the schedules I created all have a integer, they aren't void, why?
    this is optional, but if you want to cancel the tasks before they trigger you need to have and ID (or just stop all the plugins schedules):
    Code:
    plugin.getServer().getScheduler().cancelTask(OneTime));
    plugin.getServer().getScheduler().cancelTask(Repeat));
    OR
    plugin.getServer().getScheduler().cancelAllTasks();
    [creeper]NEXT WEEK ON WEEDS [creeper]

    If I get feedback I will make some more "useful things"
     
    Rayzr522, Xaostica, thescreem and 3 others like this.
  2. Offline

    MrChick

    Thanks for the scheduler stuff, that's actually what I needed today :)
     
  3. Offline

    Roujo

    Awesome stuff! Thanks for the snippets, the helped me out quite a bit. =)

    About the Repeating Schedule thing, won't using 21L end up delaying the Event 1 second per 20 times run? For example, if I understood correctly, 60 * 20L is 2 minutes, but 120 * 21L is actually 1 minute and 3 seconds instead of just 1 minute. Since that 3 second delay will accumulate, doesn't that cancel out the inital intention of avoiding simultaneous events? A 60 * 20L will sync up with a 60 * 21L event each 21 iterations. To avoid them syncing up, I think using an initial delay of 120 * 20L + 1L (or 121 * 20L) would be better. They'll run at the same rhythm, but they'll be offset by one tick. Being new here, I may have missed something tough, so feel free to correct me. =P

    Once again, thanks for the snippets! =D
     
  4. Offline

    MrChick

    You can't always assume that the server is running lag-free. I'm not sure how lag influences this behaviour but I think it might very well do so.
     
  5. Offline

    Roujo

    True, true. If they're running in different threads, they might - or rather, will - end up out-of-sync. Oh well. (^_^)
     
  6. Offline

    Sammy

    @Roujo The server does 20L (20 ticks) per second so (60*20L) is one minute.

    What I'm doing is just giving a few milliseconds extra time.
    The "one time schedule" triggers lets say at 5mins
    The "repeating schedule" triggers every 1min and 50milliseconds
    So the "one time schedule" can cancel the "repeating schedule" without it triggers the 5th time

    this is useful for deadlines
    It the deadline has ended you don't want to have a warning that the deadline is coming after it comes, am I right ? ;)


    But I'm quite new to java, so if I'm wrong please help me, I don't want to have a bad snippet posted =)


    But @MrChick is right I should give even more slack because of lag prevention.

    Thanks you both for the support !!
     
  7. Offline

    Roujo

    @Sammy Thanks for the clarification! It should work, as long as the delays don't add up until both events happen at the same time - but with a 50 ms delay... It'll take a looooong time until that happens. =P
     
  8. Offline

    magicksid

    1500 points for the Pink Floyd refrence
     
  9. Offline

    Sammy

    @magicksid
    Thanks man, my real passion is music so I always try to incorporate something ^^
    On my persistence video, the initial song was made by me :cool: ihihih
     
  10. Offline

    cvenomz

    Thanks for this. I had no idea how long a "tick" was, and I was just going to be guessing random values before this guide. Very helpful; thanks
     
  11. Offline

    askmeaboutlo0m

    This is really useful, thank you.
    Though I'm having a problem with the scheduler because I can't seem to get "plugin" declared properly, how did you do it?
     
  12. Offline

    Lolmewn Retired Staff

    Woops! I almost forgot to like this!
     
    Rayzr522 and Sammy like this.
Thread Status:
Not open for further replies.

Share This Page