用Java写一个Bukkit1201 玩家放置箱子后自动将箱子坐标和放置者ID记录到配置文件两个箱子合并后只记录一个一个坐标并且非配置文件记录的放置者禁止打开箱子
以下是一个使用Java编写的示例代码,实现了在Bukkit 1.20.1中,玩家放置箱子后自动将箱子坐标和放置者ID记录到配置文件的功能。同时,当两个箱子合并后,只记录一个坐标,并且非配置文件记录的放置者将被禁止打开箱子。
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
public class ChestTracker extends JavaPlugin implements Listener {
private FileConfiguration config;
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
this.saveDefaultConfig();
config = this.getConfig();
}
@Override
public void onDisable() {
this.saveConfig();
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Block block = event.getBlockPlaced();
Player player = event.getPlayer();
if (block.getType() == Material.CHEST) {
Location chestLocation = block.getLocation();
String chestOwner = player.getUniqueId().toString();
// Check if the chest is already recorded in the config
if (!isChestRecorded(chestLocation)) {
// Record the chest location and owner in the config
config.set("chests." + chestLocationToString(chestLocation) + ".owner", chestOwner);
saveConfig();
player.sendMessage("Chest location recorded.");
}
}
}
@EventHandler
public void onInventoryOpen(InventoryOpenEvent event) {
if (event.getInventory().getType() == org.bukkit.event.inventory.InventoryType.CHEST) {
Inventory inventory = event.getInventory();
Block block = inventory.getLocation().getBlock();
if (block.getType() == Material.CHEST) {
Chest chest = (Chest) block.getState();
Player player = (Player) event.getPlayer();
Location chestLocation = block.getLocation();
// Check if the chest is recorded in the config
if (!isChestRecorded(chestLocation)) {
// Prevent non-config recorded players from opening the chest
event.setCancelled(true);
player.sendMessage("You are not allowed to open this chest.");
}
}
}
}
private boolean isChestRecorded(Location chestLocation) {
String chestLocationString = chestLocationToString(chestLocation);
return config.contains("chests." + chestLocationString);
}
private String chestLocationToString(Location location) {
return location.getWorld().getName() + "_" + location.getBlockX() + "_" + location.getBlockY() + "_" + location.getBlockZ();
}
}
请注意,您需要将此代码保存为名为ChestTracker.java的文件,并将其放置在Bukkit插件的源代码目录中。编译并运行插件后,它将在玩家放置箱子时自动记录箱子的位置和放置者ID,并在非配置文件记录的放置者尝试打开箱子时禁止他们。配置文件将保存在插件的文件夹中的config.yml文件中,并在插件启用和禁用时自动保存。
原文地址: https://www.cveoy.top/t/topic/ifOz 著作权归作者所有。请勿转载和采集!