Bukkit私人背包实现
json数据格式为:
1、 JsonFileUtil.java
1 package com.sklm.lhb.json; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.FileReader; 6 import java.io.OutputStreamWriter; 7 import java.io.Writer; 8 import org.json.simple.JSONArray; 9 import org.json.simple.JSONObject; 10 import org.json.simple.parser.JSONParser; 11 12 public class JsonFileUtil { 13 14 /** 15 * 生成.json格式文件 16 * @param jsonString json内容 17 * @param filePath 文件路径 18 * @param fileName json文件名称 19 * @return 如果文件创建成功返回true,否则返回false 20 */ 21 public static boolean createJsonFile(String jsonString, String filePath, String fileName) { 22 boolean flag = true; 23 String fullPath = filePath +File.separator+ fileName + ".json"; 24 try { 25 File file = new File(fullPath); 26 if(!file.getParentFile().exists()) { 27 file.getParentFile().mkdirs(); 28 } 29 if(file.exists()) { 30 file.delete(); 31 file.createNewFile(); 32 }else { 33 file.createNewFile(); 34 } 35 36 //格式化json字符串 37 jsonString = JsonFormatTool.formatJson(jsonString); 38 39 Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); 40 write.write(jsonString); 41 write.flush(); 42 write.close(); 43 44 } catch (Exception e) { 45 flag = false; 46 e.printStackTrace(); 47 } 48 49 return flag; 50 } 51 52 /** 53 * 读取json文件 54 * @param jsonPath 文件路径 55 * @param jsonName 文件名称 56 * @return 返回JSONArray,如果发生 异常则返回null 57 */ 58 public static JSONArray readJsonToArray(String jsonPath, String jsonName) { 59 String path = jsonPath+"\\"+jsonName+".json"; 60 try { 61 JSONParser parse = new JSONParser(); 62 File jsonFile = new File(path); 63 if(!jsonFile.exists()) { 64 JsonFileUtil.createJsonFile("[]", jsonPath, jsonName); 65 } 66 JSONArray jsonArray = (JSONArray) parse.parse(new FileReader(jsonFile)); 67 return jsonArray; 68 } catch (Exception e) { 69 e.printStackTrace(); 70 } 71 return null; 72 } 73 74 /** 75 * 读取json文件 76 * @param jsonPath 文件路径 77 * @param jsonName 文件名称 78 * @return 返回JSONObject,如果发生 异常则返回null 79 */ 80 public static JSONObject readJsonToObject(String jsonPath, String jsonName) { 81 String path = jsonPath+"\\"+jsonName+".json"; 82 try { 83 JSONParser parse = new JSONParser(); 84 File jsonFile = new File(path); 85 if(!jsonFile.exists()) { 86 JsonFileUtil.createJsonFile("[]", path, jsonName); 87 } 88 JSONObject jsonObject = (JSONObject) parse.parse(new FileReader(jsonFile)); 89 return jsonObject; 90 } catch (Exception e) { 91 e.printStackTrace(); 92 } 93 return null; 94 } 95 }
2、 JsonFormatTool.java 为json格式转换工具类
1 package com.sklm.lhb.json; 2 3 public class JsonFormatTool { 4 5 /** 6 * 单位缩进字符串。 7 */ 8 private static String SPACE = " "; 9 10 /** 11 * 返回格式化JSON字符串。 12 * 13 * @param json 未格式化的JSON字符串。 14 * @return 格式化的JSON字符串。 15 */ 16 public static String formatJson(String json) { 17 StringBuffer result = new StringBuffer(); 18 int length = json.length(); 19 int number = 0; 20 char key = 0; 21 22 // 遍历输入字符串。 23 for (int i = 0; i < length; i++) { 24 // 1、获取当前字符。 25 key = json.charAt(i); 26 27 // 2、如果当前字符是前方括号、前花括号做如下处理: 28 if ((key == '[') || (key == '{')) { 29 // (1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。 30 if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) { 31 result.append('\n'); 32 result.append(indent(number)); 33 } 34 35 // (2)打印:当前字符。 36 result.append(key); 37 38 // (3)前方括号、前花括号,的后面必须换行。打印:换行。 39 result.append('\n'); 40 41 // (4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。 42 number++; 43 result.append(indent(number)); 44 45 // (5)进行下一次循环。 46 continue; 47 } 48 49 // 3、如果当前字符是后方括号、后花括号做如下处理: 50 if ((key == ']') || (key == '}')) { 51 // (1)后方括号、后花括号,的前面必须换行。打印:换行。 52 result.append('\n'); 53 54 // (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。 55 number--; 56 result.append(indent(number)); 57 58 // (3)打印:当前字符。 59 result.append(key); 60 61 // (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。 62 if (((i + 1) < length) && (json.charAt(i + 1) != ',')) { 63 result.append('\n'); 64 } 65 66 // (5)继续下一次循环。 67 continue; 68 } 69 70 // 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。 71 if ((key == ',')) { 72 result.append(key); 73 result.append('\n'); 74 result.append(indent(number)); 75 continue; 76 } 77 78 // 5、打印:当前字符。 79 result.append(key); 80 } 81 82 return result.toString(); 83 } 84 85 /** 86 * 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。 87 * 88 * @param number 缩进次数。 89 * @return 指定缩进次数的字符串。 90 */ 91 private static String indent(int number) { 92 StringBuffer result = new StringBuffer(); 93 for (int i = 0; i < number; i++) { 94 result.append(SPACE); 95 } 96 return result.toString(); 97 } 98 }
3、 PersionalChestToken.java口令实现类
1 package com.sklm.lhb.chestHandler; 2 3 import java.util.List; 4 import org.bukkit.Material; 5 import org.bukkit.block.Block; 6 import org.bukkit.block.Chest; 7 import org.bukkit.entity.Player; 8 import org.bukkit.inventory.ItemStack; 9 import org.bukkit.metadata.FixedMetadataValue; 10 import org.bukkit.metadata.MetadataValue; 11 import org.json.simple.JSONArray; 12 import org.json.simple.JSONObject; 13 import org.json.simple.parser.JSONParser; 14 import org.json.simple.parser.ParseException; 15 16 import com.sklm.lhb.persionalChest.PersionalChest; 17 18 public class PersionalChestToken { 19 20 /** 21 * 添加物品口令 22 * @param player 口令所有者 23 * @param block 要添加的口令的方块 24 */ 25 @SuppressWarnings("unchecked") 26 public void addToken(Player player, Block block) { 27 if(block.getState().getType()==Material.CHEST) { 28 List<MetadataValue> metaList = player.getMetadata("persionalChest"); 29 String persionalChestMsg = null; 30 if(metaList.size() == 1) { 31 persionalChestMsg = metaList.get(0).asString(); 32 JSONParser parse = new JSONParser(); 33 try { 34 JSONArray jsonArray = (JSONArray) parse.parse(persionalChestMsg); 35 JSONObject jsonObject = new JSONObject(); 36 jsonObject.put("holder", player.getName()); 37 jsonObject.put("world", block.getLocation().getWorld().getName()); 38 jsonObject.put("x", block.getLocation().getBlockX()); 39 jsonObject.put("y", block.getLocation().getBlockY()); 40 jsonObject.put("z", block.getLocation().getBlockZ()); 41 jsonArray.add(jsonObject); 42 player.removeMetadata("persionalChest", PersionalChest.instance); 43 player.setMetadata("persionalChest", new FixedMetadataValue(PersionalChest.instance, jsonArray.toJSONString())); 44 } catch (ParseException e) { 45 e.printStackTrace(); 46 } 47 }else if(metaList.size() == 0) { 48 JSONArray jsonArray = new JSONArray(); 49 JSONObject jsonObject = new JSONObject(); 50 jsonObject.put("holder", player.getName()); 51 jsonObject.put("world", block.getLocation().getWorld().getName()); 52 jsonObject.put("x", block.getLocation().getBlockX()); 53 jsonObject.put("y", block.getLocation().getBlockY()); 54 jsonObject.put("z", block.getLocation().getBlockZ()); 55 jsonArray.add(jsonObject); 56 player.removeMetadata("persionalChest", PersionalChest.instance); 57 player.setMetadata("persionalChest", new FixedMetadataValue(PersionalChest.instance, jsonArray.toJSONString())); 58 } 59 } 60 } 61 62 /** 63 * 敲碎物品时移除口令,如果该玩家没有权限敲碎该物品,则口令不会移除 64 * @param player 敲碎物品的玩家 65 * @param block 敲碎的物品 66 * @param event 敲碎物品检测事件 67 * @return 如果口令移除成功返回true,否则返回false 68 */ 69 @SuppressWarnings("unchecked") 70 public boolean removeToken(Player player, Block block) { 71 boolean flag = true; 72 if(block.getState().getType() == Material.CHEST) { 73 Chest persionalChest = (Chest) block.getState(); 74 ItemStack[] itemAll = persionalChest.getBlockInventory().getContents(); 75 for (ItemStack itemStack : itemAll) { 76 if(itemStack != null && itemStack.getType() != Material.AIR) { 77 flag = false; 78 } 79 } 80 List<MetadataValue> metaList = player.getMetadata("persionalChest"); 81 if(metaList != null && metaList.size() == 1 && !metaList.get(0).asString().equals("[]")) { 82 JSONParser parse = new JSONParser(); 83 try { 84 JSONArray jsonArray = (JSONArray) parse.parse(metaList.get(0).asString()); 85 JSONObject blockJson = new JSONObject(); 86 blockJson.put("holder", player.getName()); 87 blockJson.put("world", block.getLocation().getWorld().getName()); 88 blockJson.put("x", block.getLocation().getBlockX()); 89 blockJson.put("y", block.getLocation().getBlockY()); 90 blockJson.put("z", block.getLocation().getBlockZ()); 91 if(jsonArray.toJSONString().contains(blockJson.toJSONString())) { 92 String jsonStr = jsonArray.toJSONString().replace(blockJson.toJSONString(), "").trim(); 93 if(jsonStr.contains("},,{")) { 94 jsonStr = jsonStr.replace("},,{", "},{"); 95 }else if(jsonStr.contains("[,{")) { 96 jsonStr = jsonStr.replace("[,{", "[{"); 97 }else if(jsonStr.contains("},]")) { 98 jsonStr = jsonStr.replace("},]", "}]"); 99 } 100 player.removeMetadata("persionalChest", PersionalChest.instance); 101 player.setMetadata("persionalChest", new FixedMetadataValue(PersionalChest.instance, jsonStr)); 102 }else { 103 flag = false; 104 } 105 } catch (ParseException e) { 106 flag = false; 107 e.printStackTrace(); 108 } 109 }else { 110 flag = false; 111 } 112 } 113 return flag; 114 } 115 116 /** 117 * 检测口令是否正确,如果正确可以操作方块,否则无法操作方块 118 * @param player 要操作方块的玩家 119 * @param block 要操作的方块 120 * @return 如果口令正确返回true,否则返回false 121 */ 122 @SuppressWarnings("unchecked") 123 public boolean checkToken(Player player, Block block) { 124 boolean flag = true; 125 if(block.getState().getType() == Material.CHEST) { 126 List<MetadataValue> metaList = player.getMetadata("persionalChest"); 127 if(metaList !=null && metaList.size()==1 && !metaList.get(0).asString().equals("[]")) { 128 JSONParser parse = new JSONParser(); 129 try { 130 JSONArray jsonArray = (JSONArray) parse.parse(metaList.get(0).asString()); 131 JSONObject blockJson = new JSONObject(); 132 blockJson.put("holder", player.getName()); 133 blockJson.put("world", block.getLocation().getWorld().getName()); 134 blockJson.put("x", block.getLocation().getBlockX()); 135 blockJson.put("y", block.getLocation().getBlockY()); 136 blockJson.put("z", block.getLocation().getBlockZ()); 137 if(!jsonArray.toJSONString().contains(blockJson.toJSONString())) { 138 flag = false; 139 } 140 } catch (ParseException e) { 141 flag = false; 142 e.printStackTrace(); 143 } 144 }else { 145 flag = false; 146 } 147 } 148 return flag; 149 } 150 }
4、PersionalChestToken类调用
1 package com.sklm.lhb.chestHandler; 2 import java.util.List; 3 4 import org.bukkit.block.Block; 5 import org.bukkit.entity.Player; 6 import org.bukkit.event.EventHandler; 7 import org.bukkit.event.Listener; 8 import org.bukkit.event.block.Action; 9 import org.bukkit.event.block.BlockBreakEvent; 10 import org.bukkit.event.block.BlockPlaceEvent; 11 import org.bukkit.event.player.PlayerInteractEvent; 12 import org.bukkit.event.player.PlayerJoinEvent; 13 import org.bukkit.event.player.PlayerQuitEvent; 14 import org.bukkit.metadata.FixedMetadataValue; 15 import org.bukkit.metadata.MetadataValue; 16 import org.json.simple.JSONArray; 17 18 import com.sklm.lhb.json.JsonFileUtil; 19 import com.sklm.lhb.persionalChest.PersionalChest; 20 public class ChestActionHandler implements Listener { 21 22 @EventHandler 23 public void playerPlaceChest(BlockPlaceEvent event) { 24 Player player = event.getPlayer(); 25 Block block = event.getBlockPlaced(); 26 new PersionalChestToken().addToken(player, block); 27 } 28 29 @EventHandler 30 public void playerBreakChest(BlockBreakEvent event) { 31 Block block = event.getBlock(); 32 Player player = event.getPlayer(); 33 PersionalChestToken token = new PersionalChestToken(); 34 boolean correct = token.removeToken(player, block); 35 if(!correct && !player.isOp()) { 36 event.setCancelled(true); 37 player.sendMessage(PersionalChest.languageSection.getString("persionalChest.permission")); 38 } 39 40 } 41 42 @EventHandler 43 public void playerOpenChest(PlayerInteractEvent event) { 44 Player player = event.getPlayer(); 45 Block block = event.getClickedBlock(); 46 if(event.getAction() == Action.RIGHT_CLICK_BLOCK) { 47 PersionalChestToken token = new PersionalChestToken(); 48 boolean correct = token.checkToken(player, block); 49 if(!correct && !player.isOp()) { 50 event.setCancelled(true); 51 player.sendMessage(PersionalChest.languageSection.getString("persionalChest.permission")); 52 } 53 } 54 } 55 56 @EventHandler 57 public void playerJoinEvent(PlayerJoinEvent event) { 58 Player player = event.getPlayer(); 59 JSONArray jsonArray = JsonFileUtil.readJsonToArray(PersionalChest.getPath()+"player\\", player.getName()); 60 if(jsonArray != null) { 61 player.setMetadata("persionalChest", new FixedMetadataValue(PersionalChest.instance, jsonArray.toJSONString())); 62 } 63 } 64 65 @EventHandler 66 public void playerQueryGame(PlayerQuitEvent event) { 67 Player player = event.getPlayer(); 68 List<MetadataValue> metaList = player.getMetadata("persionalChest"); 69 if(metaList.size() == 1) { 70 JsonFileUtil.createJsonFile(metaList.get(0).asString(), PersionalChest.getPath()+"player\\", player.getName()); 71 } 72 } 73 74 }