Change contents of a chest

Discussion in 'Plugin Development' started by randomizer1234, Jul 4, 2012.

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

    randomizer1234

    Hello,
    I'm a C programmer and I'm trying to make a Java plugin and I need an advice on how to implement a function.

    I've got a org.bukkit.block.Chest, what is the best object-oriented way to change its contents?

    The plugin I'm making randomizes the contents of a chest, everything works but I'm writing all the code in just one file (the plugin class)...

    I don't want ready-to-use code, I want to write all the code by my self... I just want some advices on how to structure my plugin because I'm new to OOP.

    Thank you!
     
  2. Offline

    tabr

    Code:
    Chest c = [...].getBlock().getState();
    Inventory inv    = c.getBlockInventory();
    inv.setItem(int pos, ItemStack i);
    inv.getItem(int pos);
    inv.clean();
    
     
  3. Offline

    randomizer1234

    Thank you, but this isn't what I was looking for...
    I can already change/randomize the content of a chest, but the problem is that I'm writing everything into the onCommand method, and I was asking help on how to structure my plugin, not only on how to change a chest's content...
     
  4. Offline

    sayaad

    Oh, well you can do what I do.
    Create a new package in your main package called util (so it would be youmainpackage.util).
    In that package create a new class called API and in there create static voids/strings/booleans etc to suit your needs.
    Then, import the api class (import yourmainpackage.util.API)
    And call the methods you coded anywhere you want in the format API.method(Argument);

    Example (open)

    Code:java
    1. package me.sayaad.CCTV.util;
    2.  
    3. import java.io.BufferedReader;
    4. import java.io.BufferedWriter;
    5. import java.io.File;
    6. import java.io.FileReader;
    7. import java.io.FileWriter;
    8. import java.io.IOException;
    9. import java.io.PrintWriter;
    10. import java.util.Map.Entry;
    11. import java.util.Scanner;
    12.  
    13. import me.sayaad.CCTV.main;
    14.  
    15. import org.bukkit.ChatColor;
    16. import org.bukkit.Location;
    17. import org.bukkit.Material;
    18. import org.bukkit.configuration.file.FileConfiguration;
    19. import org.bukkit.entity.Player;
    20. import org.bukkit.potion.PotionEffect;
    21. import org.bukkit.potion.PotionEffectType;
    22.  
    23. public class API
    24. {
    25. public static main plugin;
    26.  
    27. public API(main instance)
    28. {
    29. plugin = instance;
    30. }
    31.  
    32. public static void checkConfig(FileConfiguration config)
    33. {
    34. try {
    35. File Config = new File(VAR.mainDirectory + "config.yml");
    36. config.set("Camera.Camera Block IDS", config.getString("Camera.Camera Block IDS", "49,19,23"));
    37. config.set("Camera.Camera can be dispensor", config.getBoolean("Camera.Camera can be dispensor", true));
    38. config.set("Screen.Screen Block IDS", config.getString("Screen.Screen Block IDS", "35:15,35:7"));
    39. config.set("CCTV.Only player that created link can use link", config.getBoolean("CCTV.Only player that created link can use link", true));
    40. config.save(Config);
    41. } catch (Exception e) {
    42. VAR.log.severe("[CCTV Camera] An error occured checking the config file. Please make a ticket of this error :\n");
    43. e.printStackTrace();
    44. }
    45. }
    46.  
    47. public static void getLinkLocations()
    48. {
    49. VAR.Links.clear();
    50. try
    51. {
    52. Scanner file = new Scanner(VAR.LinksFile);
    53. VAR.Links.clear();
    54.  
    55. while (file.hasNextLine())
    56. {
    57. VAR.Links.add(file.nextLine());
    58. }
    59. file.close();
    60. }
    61. catch (IOException e) {
    62. VAR.log.severe("[CCTV Camera] An error occured reading and adding to the LinksLocation Array. Please make a ticket of this error :\n");
    63. e.printStackTrace();
    64. }
    65. }
    66.  
    67. public static void addLink()
    68. {
    69. if ((VAR.cameraLocation != null) && (VAR.screenLocation != null))
    70. {
    71. String message = VAR.cameraLocation.getWorld().getName() + "," + (int)VAR.cameraLocation.getX() + "," + (int)VAR.cameraLocation.getY() + "," + (int)VAR.cameraLocation.getZ() + "," + VAR.cameraName + ";" + VAR.screenLocation.getWorld().getName() + "," + (int)VAR.screenLocation.getX() + "," + (int)VAR.screenLocation.getY() + "," + (int)VAR.screenLocation.getZ() + "," + VAR.screenName + ";" + VAR.playerUsing + ";" + VAR.DispensorFace + ";" + VAR.cameraLocation.getBlock().getTypeId();
    72. try
    73. {
    74. BufferedWriter writer = new BufferedWriter(new FileWriter(VAR.LinksFile, true));
    75. writer.write(message);
    76. writer.newLine();
    77. writer.flush();
    78. writer.close();
    79. }
    80. catch (IOException e) {
    81. VAR.log.severe("[CCTV Camera] An error occured adding to Link File. Please make a ticket of this error :\n");
    82. e.printStackTrace();
    83. }
    84.  
    85. getLinkLocations();
    86. }
    87. }
    88.  
    89. public static void goToCamera(Player player, Location loc) {
    90.  
    91. VAR.cameraUsers.add(player.getName());
    92.  
    93. loc.getBlock().setType(Material.GLASS);
    94.  
    95. player.hidePlayer(player);
    96.  
    97. loc.setX(loc.getX() + 0.5D);
    98. loc.setZ(loc.getZ() + 0.5D);
    99. loc.setY(loc.getY() - 1.0D);
    100.  
    101. loc.getBlock().setType(Material.GLOWSTONE);
    102.  
    103. player.teleport(loc);
    104. player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20, 2));
    105.  
    106. player.sendMessage(ChatColor.GREEN + "[CCTV Camera] Right-Click to exit the view.");
    107. }
    108.  
    109. public static void exitCamera(Player player, Location loc2) {
    110.  
    111. VAR.cameraUsers.remove(player.getName());
    112. player.showPlayer(player);
    113. player.setDisplayName(player.getName());
    114.  
    115. if(VAR.dispensorCameraUsers.contains(player.getName())){
    116.  
    117. VAR.dispensorCameraUsers.remove(player.getName());
    118. }
    119.  
    120. for (Entry<Player, Location> entry : VAR.backlocation.entrySet()) {
    121.  
    122. if (!((Player)entry.getKey()).equals(player))
    123. continue;
    124.  
    125. player.teleport((Location)entry.getValue());
    126. }
    127.  
    128. API.getLinkLocations();
    129.  
    130. for (int i = 0; i < VAR.Links.size(); i++) {
    131. String logLine = (String)VAR.Links.get(i);
    132.  
    133. String[] derp = logLine.split(";");
    134.  
    135. String[] cameraLocation =
    136. derp[0].split(",");
    137. String[] screenLocation =
    138. derp[1].split(",");
    139.  
    140. if ((cameraLocation.length == 5) && (screenLocation.length == 5))
    141. {
    142.  
    143. Byte data = 0;
    144. Location loc = new Location(
    145. player.getServer().getWorld(cameraLocation[0]),
    146. Double.parseDouble(cameraLocation[1]),
    147. Double.parseDouble(cameraLocation[2]),
    148. Double.parseDouble(cameraLocation[3]));
    149.  
    150. if(loc.equals(loc2)){
    151. // north = 0; east = 1; south = 2; west = 3;
    152.  
    153. loc.getBlock().setTypeId(Integer.parseInt(derp[4]));
    154.  
    155. if(derp[3].equals("SOUTH")){
    156. data = 2;
    157. }
    158. if(derp[3].equals("EAST")){
    159. data = 1;
    160. }
    161. if(derp[3].equals("WEST")){
    162. data = 3;
    163. }
    164.  
    165. loc.getBlock().setData(data);
    166.  
    167. }
    168. }
    169. }
    170.  
    171. player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20, 2));
    172. }
    173.  
    174. public static void removeLineFromFile(String file, String lineToRemove)
    175. {
    176. try
    177. {
    178. VAR.Links.clear();
    179. VAR.blockDamageArray.clear();
    180.  
    181. File inFile = new File(file);
    182.  
    183. File tempFile = new File(VAR.mainDirectory + "Data/" + "temp" + ".tmp");
    184.  
    185. PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
    186.  
    187. String line = null;
    188.  
    189. while ((line = br.readLine()) != null)
    190. {
    191. if (line.trim().equals(lineToRemove))
    192. continue;
    193. pw.println(line);
    194. pw.flush();
    195. }
    196.  
    197. pw.close();
    198. br.close();
    199.  
    200. if (!inFile.delete())
    201. VAR.log.severe("[CCTV] Could not delete links file!");
    202. else {
    203. tempFile.renameTo(inFile);
    204. }
    205. }
    206. catch (Exception ex)
    207. {
    208. ex.printStackTrace();
    209. }
    210. }
    211. }

    And I call it like this :
    Code:java
    1. public void onEnable(){
    2. API.checkConfig(VAR.config);
    3. }

     
  5. Offline

    desht

    Your question is about OOP rather than specific implementation details. Learning OOP principles is a big task but here are a couple of thoughts:
    • Considering your problem space, what are the objects? You want something to randomize the contents of a Chest. Two types of objects here: the Chest, and the "thing" that does the randomization. That's what you want to create: a ChestRandomizer.
    • What would a ChestRandomizer work on? A Chest!
    So a skeletal class might look like:
    PHP:
    public class ChestRandomizer {
      private final 
    Chest chest;  // the chest we're working on
      
      
    public ChestRandomizer(Chest chest) {
        
    this.chest chest;
      }
      public 
    void randomize() {
        
    // here you put your code to shuffle the contents
      
    }
    }
    Now in your command executor, you can say:
    PHP:
    ChestRandomizer cr = new ChestRandomizer(chest);
    cr.randomize();
    That's it basically. One caveat: a Chest object (like all subclasses of BlockState) should be considered a transient object - don't keep it around for extended periods, because the underlying Block it represents could change in the meantime, invalidating the BlockState. So your ChestRandomizer objects should also be considered transient - it's safest not to let them live beyond the scope of the methods that create them (or if you do, take care to always validate before using).
     
    ferrybig likes this.
  6. Offline

    sayaad

    Or you know....could dump your voids in an API class like I do xD
     
  7. Offline

    desht

    Yeah, I know, but he wanted an OO approach :)
     
  8. Offline

    randomizer1234

    And, tell me if I'm wrong, I could make an abstract ChestRandomizer class and then create different classes which extend it which randomize the chest in different ways... Right?

    Hey?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 26, 2016
  9. Offline

    desht

    Yes, you could certainly do that...
     
Thread Status:
Not open for further replies.

Share This Page