Refactoring: org.mcteam.ancientgates -> de.craftinc.gates

This commit is contained in:
Tobias Ottenweller
2012-11-04 19:29:14 +01:00
parent 139bfc7d54
commit 9067f875ce
25 changed files with 70 additions and 57 deletions

View File

@ -0,0 +1,195 @@
package de.craftinc.gates;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import de.craftinc.gates.util.FloodUtil;
public abstract class BaseGate
{
/*
* ATTRIBUTES
*/
protected Location location; /* saving both location and gateBlockLocations is redundant but makes it easy to allow players to reshape gates */
protected Set<Location> gateBlockLocations = new HashSet<Location>(); /* Locations of the blocks inside the gate */
protected Location exit;
protected boolean isHidden = false;
protected boolean isOpen = false;
/*
* SETTER & GETTER
*/
public Location getLocation()
{
return location;
}
public void setLocation(Location location) throws Exception
{
this.location = location;
if (isOpen) {
fillGate();
validate();
}
}
public Location getExit()
{
return exit;
}
public void setExit(Location exit) throws Exception
{
this.exit = exit;
validate();
}
public boolean isHidden()
{
return isHidden;
}
public void setHidden(boolean isHidden) throws Exception
{
this.isHidden = isHidden;
if (isHidden == true) {
emptyGate();
}
else if (isOpen()) {
fillGate();
}
validate();
}
public boolean isOpen()
{
return isOpen;
}
public void setOpen(boolean isOpen) throws Exception
{
if (isOpen == true && this.isOpen == false) {
findPortalBlocks();
if (!isHidden) {
fillGate();
}
}
else if (isOpen == false && this.isOpen == true) {
emptyGate();
}
this.isOpen = isOpen;
validate();
}
public Set<Location> getGateBlockLocations()
{
return gateBlockLocations;
}
/*
* GATE BLOCK HANDLING
*/
protected void fillGate()
{
emptyGate();
findPortalBlocks();
// This is not to do an effect
// It is to stop portal blocks from destroying themself as they cant rely on non created blocks :P
for (Location l : gateBlockLocations) {
l.getBlock().setType(Material.GLOWSTONE);
}
for (Location l : gateBlockLocations) {
l.getBlock().setType(Material.PORTAL);
}
}
protected void emptyGate()
{
for (Location l : gateBlockLocations) {
if (l.getBlock().getType() == Material.PORTAL) {
l.getBlock().setType(Material.AIR);
}
}
}
protected void findPortalBlocks()
{
gateBlockLocations = new HashSet<Location>();
Set<Block> gateBlocks = FloodUtil.getGateFrameBlocks(location.getBlock());
if (gateBlocks != null) {
for (Block b : gateBlocks) {
gateBlockLocations.add(b.getLocation());
}
}
}
/*
* VALIDATION
*/
/**
* Checks if valus attributes do add up; will close gate on wrong values.
*/
public void validate() throws Exception
{
if (!isOpen) {
return;
}
if (location == null) {
setOpen(false);
throw new Exception("Gate got closed. It has no location.");
}
if (exit == null) {
setOpen(false);
throw new Exception("Gate got closed. It has no exit.");
}
if (gateBlockLocations.size() == 0) {
setOpen(false);
throw new Exception("Gate got closed. The frame is missing or broken.");
}
if (isHidden == false) {
for (Location l : gateBlockLocations) {
if (l.getBlock().getType() == Material.AIR) {
setOpen(false);
throw new Exception("Gate got closed. The frame is missing or broken.");
}
}
}
}
}

View File

@ -0,0 +1,173 @@
package de.craftinc.gates;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import de.craftinc.gates.util.LocationSerializer;
/**
* Adds persistence and serialization to the base gate class.
*/
public class Gate extends BaseGate implements ConfigurationSerializable
{
/*
* ATTRIBUTES
*/
protected String id;
protected static Map<String, Gate> instances = new HashMap<String, Gate>();
/*
* CONSTRUCTORS
*/
public Gate(String id) throws Exception
{
setId(id);
}
/*
* SETTER & GETTER
*/
public String getId()
{
return id;
}
public void setId(String id) throws Exception
{
if (exists(id)) {
throw new Exception("A gate with '" + id + "' already exists");
}
this.id = id;
}
/*
* INTERFACE: ConfigurationSerializable
*/
static String idKey = "id";
static String locationKey = "location";
static String gateBlocksKey = "gateBlocks";
static String exitKey = "exit";
static String isHiddenKey = "hidden";
static String isOpenKey = "open";
@SuppressWarnings("unchecked")
public Gate(Map<String, Object> map)
{
id = (String)map.get(idKey);
location = LocationSerializer.deserializeLocation((Map<String, Object>) map.get(locationKey));
exit = LocationSerializer.deserializeLocation((Map<String, Object>) map.get(exitKey));
isHidden = (Boolean)map.get(isHiddenKey);
isOpen = (Boolean)map.get(isOpenKey);
gateBlockLocations = new HashSet<Location>();
List<Map<String, Object>> serializedGateBlocks = (List<Map<String, Object>>)map.get(gateBlocksKey);
for (Map<String, Object> sgb : serializedGateBlocks) {
gateBlockLocations.add(LocationSerializer.deserializeLocation(sgb));
}
instances.put(id, this);
}
public Map<String, Object> serialize()
{
try {
validate(); // make sure to not write invalid stuff to disk
}
catch (Exception e) {
}
Map<String, Object> retVal = new HashMap<String, Object>();
retVal.put(idKey, id);
retVal.put(locationKey, LocationSerializer.serializeLocation(location));
retVal.put(exitKey, LocationSerializer.serializeLocation(exit));
retVal.put(isHiddenKey, isHidden);
retVal.put(isOpenKey, isOpen);
List<Map<String, Object>> serializedGateBlocks = new ArrayList<Map<String, Object>>();
for (Location l : gateBlockLocations) {
serializedGateBlocks.add(LocationSerializer.serializeLocation(l));
}
retVal.put(gateBlocksKey, serializedGateBlocks);
return retVal;
}
/*
* ENTITY MANAGEMENT
*/
public static Gate get(String id)
{
return instances.get(id);
}
public static boolean exists(String id)
{
return instances.containsKey(id);
}
public static Gate create(String id) throws Exception
{
Gate gate = new Gate(id);
instances.put(gate.id, gate);
return gate;
}
public static void rename(String oldId, String newId) throws Exception
{
Gate gate = get(oldId);
gate.setId(newId);
delete(oldId);
instances.put(gate.id, gate);
}
public static void delete(String id)
{
Gate g = get(id);
if (g != null) {
g.emptyGate();
}
instances.remove(id);
}
public static Collection<Gate> getAll()
{
return instances.values();
}
}

View File

@ -0,0 +1,193 @@
package de.craftinc.gates;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import de.craftinc.gates.commands.*;
import de.craftinc.gates.listeners.PluginBlockListener;
import de.craftinc.gates.listeners.PluginPlayerListener;
import de.craftinc.gates.listeners.PluginPortalListener;
public class Plugin extends JavaPlugin
{
public static Plugin instance;
public static final String permissionInfo = "ancientgates.info";
public static final String permissionManage = "ancientgates.manage";
public static final String permissionAll = "ancientgates.*";
public static final String permissionUse = "ancientgates.use";
public PluginPlayerListener playerListener = new PluginPlayerListener();
public PluginBlockListener blockListener = new PluginBlockListener();
public PluginPortalListener portalListener = new PluginPortalListener();
private String baseCommand;
private String gatesPath = "gates";
// Commands
public List<BaseCommand> commands = new ArrayList<BaseCommand>();
public Plugin()
{
instance = this;
}
@Override
public void onLoad()
{
ConfigurationSerialization.registerClass(Gate.class);
}
@Override
public void onDisable()
{
// Save gates
saveGates();
log("Disabled");
}
@Override
public void onEnable()
{
// Add the commands
commands.add(new CommandHelp());
commands.add(new CommandCreate());
commands.add(new CommandDelete());
commands.add(new CommandSetLocation());
commands.add(new CommandSetExit());
commands.add(new CommandOpen());
commands.add(new CommandRename());
commands.add(new CommandClose());
commands.add(new CommandList());
commands.add(new CommandInfo());
commands.add(new CommandSetHidden());
commands.add(new CommandSetVisible());
// Register events
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this.playerListener, this);
pm.registerEvents(this.blockListener, this);
pm.registerEvents(this.portalListener, this);
// Load gates
loadGates();
log("Enabled");
}
// -------------------------------------------- //
// Commands
// -------------------------------------------- //
public String getBaseCommand()
{
if (this.baseCommand != null)
return this.baseCommand;
Map<String, Map<String, Object>> Commands = this.getDescription().getCommands();
this.baseCommand = Commands.keySet().iterator().next();
return this.baseCommand;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
List<String> parameters = new ArrayList<String>(Arrays.asList(args));
this.handleCommand(sender, parameters);
return true;
}
public void handleCommand(CommandSender sender, List<String> parameters)
{
if (parameters.size() == 0)
{
this.commands.get(0).execute(sender, parameters);
return;
}
String commandName = parameters.get(0).toLowerCase();
parameters.remove(0);
for (BaseCommand fcommand : this.commands)
{
if (fcommand.getAliases().contains(commandName))
{
fcommand.execute(sender, parameters);
return;
}
}
sender.sendMessage("Unknown gate-command \"" + commandName + "\". Try " + "/" + getBaseCommand() + " help");
}
/*
* Logging
*/
public static void log(String msg)
{
log(Level.INFO, msg);
}
public static void log(Level level, String msg) {
Logger.getLogger("Minecraft").log(level, "["+instance.getDescription().getFullName()+"] "+msg);
}
/*
* Saving and Loading Gates
*/
public void loadGates()
{
File gatesFile = new File(getDataFolder(), "gates.yml");
FileConfiguration gatesConfig = YamlConfiguration.loadConfiguration(gatesFile);
gatesConfig.getList(gatesPath); // this will create all the gates
}
public void saveGates()
{
File gatesFile = new File(getDataFolder(), "gates.yml");
FileConfiguration gatesConfig = YamlConfiguration.loadConfiguration(gatesFile);
gatesConfig.set(gatesPath, new ArrayList<Object>(Gate.getAll()));
try {
gatesConfig.save(gatesFile);
}
catch (IOException e) {
log("ERROR: Could not save gates to disk.");
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,169 @@
package de.craftinc.gates.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
import de.craftinc.gates.util.TextUtil;
public abstract class BaseCommand
{
public List<String> aliases;
public List<String> requiredParameters;
public List<String> optionalParameters;
public String helpDescription;
public CommandSender sender;
public boolean senderMustBePlayer;
public boolean hasGateParam;
public Player player;
public Gate gate;
public List<String> parameters;
public String requiredPermission;
public BaseCommand() {
aliases = new ArrayList<String>();
requiredParameters = new ArrayList<String>();
optionalParameters = new ArrayList<String>();
senderMustBePlayer = true;
hasGateParam = true;
helpDescription = "no description";
}
public List<String> getAliases() {
return aliases;
}
public void execute(CommandSender sender, List<String> parameters) {
this.sender = sender;
this.parameters = parameters;
if ( ! validateCall()) {
return;
}
if (this.senderMustBePlayer) {
this.player = (Player)sender;
}
perform();
}
public void perform() {
}
public void sendMessage(String message) {
sender.sendMessage(message);
}
public void sendMessage(List<String> messages) {
for(String message : messages) {
this.sendMessage(message);
}
}
public boolean validateCall()
{
// validate player
if ( this.senderMustBePlayer && ! (sender instanceof Player))
{
sendMessage("This command can only be used by ingame players.");
return false;
}
// validate permission
if( !hasPermission(sender))
{
sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+".");
return false;
}
// valide parameter count
if (parameters.size() < requiredParameters.size())
{
sendMessage("Usage: "+this.getUseageTemplate(true));
return false;
}
// validate gate parameter
if (this.hasGateParam)
{
String id = parameters.get(0);
if ( ! Gate.exists(id))
{
sendMessage("There exists no gate with id "+id);
return false;
}
gate = Gate.get(id);
}
return true;
}
public boolean hasPermission(CommandSender sender)
{
if (sender.hasPermission(Plugin.permissionAll)) {
return true;
}
if (sender.hasPermission(requiredPermission)) {
return true;
}
return false;
}
// -------------------------------------------- //
// Help and usage description
// -------------------------------------------- //
public String getUsageTemplate(boolean withColor, boolean withDescription) {
String ret = "";
// if (withColor) {
// ret += Conf.colorCommand;
// }
ret += "/" + Plugin.instance.getBaseCommand() + " " + TextUtil.implode(this.getAliases(), ",")+" ";
List<String> parts = new ArrayList<String>();
for (String requiredParameter : this.requiredParameters) {
parts.add("["+requiredParameter+"]");
}
for (String optionalParameter : this.optionalParameters) {
parts.add("*["+optionalParameter+"]");
}
// if (withColor) {
// ret += Conf.colorParameter;
// }
ret += TextUtil.implode(parts, " ");
// if (withDescription) {
// ret += " "+Conf.colorSystem + this.helpDescription;
// }
return ret;
}
public String getUseageTemplate(boolean withColor) {
return getUsageTemplate(withColor, false);
}
public String getUseageTemplate() {
return getUseageTemplate(true);
}
}

View File

@ -0,0 +1,31 @@
package de.craftinc.gates.commands;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
public abstract class BaseLocationCommand extends BaseCommand
{
protected Location getValidPlayerLocation()
{
// The player might stand in a halfblock or a sign or whatever
// Therefore we load som extra locations and blocks
Block playerBlock = player.getLocation().getBlock();
Block upBlock = playerBlock.getRelative(BlockFace.UP);
if (playerBlock.getType() == Material.AIR) {
return player.getLocation();
}
else if (upBlock.getType() == Material.AIR) {
return new Location(player.getLocation().getWorld(),
player.getLocation().getX(),
player.getLocation().getY() + 1,
player.getLocation().getZ(),
player.getLocation().getYaw(),
player.getLocation().getPitch());
}
return null;
}
}

View File

@ -0,0 +1,32 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Plugin;
public class CommandClose extends BaseCommand
{
public CommandClose()
{
aliases.add("close");
requiredParameters.add("id");
helpDescription = "Closes a gate to prevent players from using it.";
requiredPermission = Plugin.permissionManage;
}
@Override
public void perform()
{
try {
gate.setOpen(false);
}
catch(Exception e) {
}
sendMessage("The gate was closed.");
}
}

View File

@ -0,0 +1,58 @@
package de.craftinc.gates.commands;
import org.bukkit.Location;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
public class CommandCreate extends BaseLocationCommand
{
public CommandCreate()
{
aliases.add("create");
aliases.add("new");
requiredParameters.add("id");
senderMustBePlayer = true;
hasGateParam = false;
helpDescription = "Create a gate at your current location.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
String id = parameters.get(0);
try {
gate = Gate.create(id);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Location playerLocation = getValidPlayerLocation();
if (playerLocation != null) {
try {
gate.setLocation(playerLocation);
}
catch (Exception e) {
}
sendMessage("Gate with id \"" + id + "\" was created.");
sendMessage("The gates location has been set to your current location.");
}
else {
sendMessage("Gate with id \"" + id + "\" was created.");
sendMessage("Now you should build a frame and:");
sendMessage(new CommandSetLocation().getUsageTemplate(true, true));
}
}
}

View File

@ -0,0 +1,31 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
public class CommandDelete extends BaseCommand
{
public CommandDelete()
{
aliases.add("delete");
aliases.add("del");
aliases.add("remove");
aliases.add("rm");
requiredParameters.add("id");
senderMustBePlayer = false;
helpDescription = "Removes the gate from the game.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
Gate.delete(gate.getId());
sendMessage("Gate with id '" + gate.getId() + "' was deleted.");
}
}

View File

@ -0,0 +1,94 @@
package de.craftinc.gates.commands;
import java.util.ArrayList;
import org.bukkit.command.CommandSender;
import de.craftinc.gates.util.TextUtil;
public class CommandHelp extends BaseCommand
{
public CommandHelp()
{
aliases.add("help");
aliases.add("h");
aliases.add("?");
optionalParameters.add("page");
hasGateParam = false;
helpDescription = "Prints a list of all availible commands.";
}
@Override
public boolean hasPermission(CommandSender sender)
{
return true;
}
public void perform()
{
int page = 1;
if (parameters.size() > 0)
{
try
{
page = Integer.parseInt(parameters.get(0));
}
catch (NumberFormatException e)
{
// wasn't an integer
}
}
sendMessage(TextUtil.titleize("AncientGates Help ("+page+"/"+helpPages.size()+")"));
page -= 1;
if (page < 0 || page >= helpPages.size())
{
sendMessage("This page does not exist");
return;
}
sendMessage(helpPages.get(page));
}
//----------------------------------------------//
// Build the help pages
//----------------------------------------------//
public static ArrayList<ArrayList<String>> helpPages;
static
{
helpPages = new ArrayList<ArrayList<String>>();
ArrayList<String> pageLines;
pageLines = new ArrayList<String>();
pageLines.add( new CommandHelp().getUsageTemplate(true, true) );
pageLines.add( new CommandCreate().getUsageTemplate(true, true) );
pageLines.add( new CommandDelete().getUsageTemplate(true, true) );
pageLines.add( new CommandSetLocation().getUsageTemplate(true, true) );
pageLines.add( new CommandSetExit().getUsageTemplate(true, true) );
pageLines.add( new CommandOpen().getUsageTemplate(true, true) );
helpPages.add(pageLines);
pageLines = new ArrayList<String>();
pageLines.add( new CommandRename().getUsageTemplate(true, true) );
pageLines.add( new CommandClose().getUsageTemplate(true, true) );
pageLines.add( new CommandList().getUsageTemplate(true, true) );
pageLines.add( new CommandInfo().getUsageTemplate(true, true) );
pageLines.add( new CommandSetHidden().getUsageTemplate(true, true) );
pageLines.add( new CommandSetVisible().getUsageTemplate(true, true) );
helpPages.add(pageLines);
}
}

View File

@ -0,0 +1,52 @@
package de.craftinc.gates.commands;
import org.bukkit.ChatColor;
import de.craftinc.gates.Plugin;
public class CommandInfo extends BaseCommand
{
public CommandInfo()
{
aliases.add("info");
aliases.add("details");
requiredParameters.add("id");
helpDescription = "Prints detailed informations about a certain gate.";
requiredPermission = Plugin.permissionInfo;
}
public void perform()
{
sendMessage(ChatColor.LIGHT_PURPLE + "Information about " + ChatColor.WHITE + gate.getId() + ChatColor.LIGHT_PURPLE + ":");
String openHiddenMessage = "This gate is";
if (gate.isOpen())
openHiddenMessage += " open";
else
openHiddenMessage += " closed";
if (gate.isHidden())
openHiddenMessage += " and hidden";
openHiddenMessage += ".";
sendMessage(openHiddenMessage);
if (gate.getLocation() != null)
sendMessage(ChatColor.GREEN + "'from' location: " + ChatColor.YELLOW + "( " + gate.getLocation().getBlockX() + " | " + gate.getLocation().getBlockY() + " | " + gate.getLocation().getBlockZ() + " ) in " + gate.getLocation().getWorld().getName());
else
sendMessage(ChatColor.GREEN + "this gate has no 'from' location");
if (gate.getExit() != null)
sendMessage(ChatColor.GREEN + "'to' location: " + ChatColor.YELLOW + "( " + gate.getExit().getBlockX() + " | " + gate.getExit().getBlockY() + " | " + gate.getExit().getBlockZ() + " ) in " + gate.getExit().getWorld().getName());
else
sendMessage(ChatColor.GREEN + "this gate has no 'to' location");
}
}

View File

@ -0,0 +1,217 @@
package de.craftinc.gates.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.bukkit.ChatColor;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
import de.craftinc.gates.util.TextUtil;
public class CommandList extends BaseCommand
{
public CommandList()
{
aliases.add("list");
aliases.add("ls");
optionalParameters.add("page");
hasGateParam = false;
helpDescription = "Prints a list of all availible gates.";
requiredPermission = Plugin.permissionInfo;
}
protected String intToTitleString(int i)
{
if ( i < 26 ) {
return ChatColor.GREEN + "" + (char)(i+65) + ":";
}
else if ( i == 26 ) {
return ChatColor.GREEN + "0 - 9:";
}
else {
return ChatColor.GREEN + "!@#$:";
}
}
// pages start at 1
// will return null if requested page not availible
protected List<String> message(int page)
{
Collection<Gate> gates = Gate.getAll();
if (gates.size() == 0) {
return null;
}
/* sort all gates by there first character
* put gates in corresponding Lists
* list 0-25: a,b,c, ... ,z
* list 26: 0-9
* list 27: other
*/
List<List<String>> ids = new ArrayList<List<String>>();
for (int i=0; i<28; i++) {
ids.add(new ArrayList<String>());
}
for (Gate gate : gates) {
String id = gate.getId();
int first = id.charAt(0);
if (first > 96 && first < 123) { // convert lower case chars
first -= 97;
}
else if (first > 64 && first < 91) { // convert upper case chars
first -= 65;
}
else if (first > 47 && first < 58) { // convert numbers
first = 26;
}
else { // everything else
first = 27;
}
ids.get(first).add(id);
}
/* calculating which gates will be displayed on which page.
* this is a little bit fuzzy. but hopefully it will look
* great. (tell me if there is a better way!)
*/
// list<string>: a list from ids
// Integer: the number of lines neccessary for displaying the corresponding list
HashMap<List<String>, Integer> lines = new HashMap<List<String>, Integer>(27);
for (List<String> currentIds : ids) {
if (currentIds.size() == 0) {
continue;
}
int characters = TextUtil.implode(currentIds, ", ").length();
lines.put(currentIds, characters / 52 + 2);
}
int currentPage = 1;
int currentStartingCharList = 0;
boolean finishedCurrentIds = true;
List<String> pageMessages = new ArrayList<String>();
while (currentStartingCharList < ids.size()) {
int linesLeftOnCurrentPage = 9;
while (linesLeftOnCurrentPage > 1 && currentStartingCharList < ids.size()) {
List<String> currentIds = ids.get(currentStartingCharList);
if (currentIds.size() > 0) {
// add header line
if (currentPage == page) {
pageMessages.add(intToTitleString(currentStartingCharList));
}
//sort
Collections.sort(currentIds);
// add ids
if (lines.get(currentIds) <= linesLeftOnCurrentPage) { // all ids fit on current page
linesLeftOnCurrentPage -= lines.get(currentIds);
if (currentPage == page) {
pageMessages.add(TextUtil.implode(currentIds, ", "));
if (finishedCurrentIds == false) {
pageMessages.set(pageMessages.size() -2, pageMessages.get(pageMessages.size() -2) + " (more on previous page)");
}
}
finishedCurrentIds = true;
}
else { // NOT all ids fit on current page
int charsAvailible = (linesLeftOnCurrentPage - 1) * 52;
int idsPos = 0;
do {
charsAvailible -= currentIds.get(idsPos).length() + 2;
idsPos++;
} while (charsAvailible > 0);
List<String> idsToPutOnCurrentPage = currentIds.subList(0, idsPos);
currentIds.remove(idsToPutOnCurrentPage);
String stringToPutOnCurrentPage = TextUtil.implode(idsToPutOnCurrentPage, ", ");
if (currentPage == page) {
pageMessages.add(stringToPutOnCurrentPage);
pageMessages.set(pageMessages.size() -2, pageMessages.get(pageMessages.size() -2) + " (more on next page)");
}
lines.put(currentIds, TextUtil.implode(currentIds, ", ").length() / 52 + 2);
linesLeftOnCurrentPage -= stringToPutOnCurrentPage.length() / 52 + 2;
finishedCurrentIds = false;
}
}
if (finishedCurrentIds) {
currentStartingCharList++;
}
}
currentPage++;
}
if (pageMessages.isEmpty()) {
return null;
}
else {
ArrayList<String> retVal = new ArrayList<String>();
retVal.add(ChatColor.LIGHT_PURPLE + "This is page " + ChatColor.WHITE + page + ChatColor.LIGHT_PURPLE + "/" + ChatColor.WHITE + --currentPage + ChatColor.LIGHT_PURPLE + ". There are " + gates.size() + " gates on this server: ");
retVal.addAll(pageMessages);
return retVal;
}
}
public void perform()
{
Collection<Gate> gates = Gate.getAll();
if (gates.size() == 0) {
sendMessage("There are no gates yet.");
}
else {
int page = 1;
try {
page = new Integer(parameters.get(0));
}
catch (Exception e) {
}
List<String> messages = message(page);
if (messages == null) {
sendMessage("The requested page is not availible");
}
else {
sendMessage(messages);
}
}
}
}

View File

@ -0,0 +1,34 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Plugin;
public class CommandOpen extends BaseCommand
{
public CommandOpen()
{
aliases.add("open");
requiredParameters.add("id");
helpDescription = "Open a gate so players can use it.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
try {
gate.setOpen(true);
} catch (Exception e) {
sendMessage(e.getMessage());
return;
}
sendMessage("The gate was opened.");
}
}

View File

@ -0,0 +1,41 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
public class CommandRename extends BaseCommand
{
public CommandRename()
{
aliases.add("rename");
aliases.add("changename");
aliases.add("cn");
hasGateParam = true;
senderMustBePlayer = false;
requiredParameters.add("current name");
requiredParameters.add("new name");
helpDescription = "Changes the id of a gate.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
String newId = parameters.get(1);
try {
Gate.rename(gate.getId(), newId);
}
catch (Exception e) {
sendMessage("Cannot rename " + gate.getId() + ". There is already a gate named " + newId + ".");
}
sendMessage("Gate " + gate.getId() + " is now known as " + newId + ".");
}
}

View File

@ -0,0 +1,34 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Plugin;
public class CommandSetExit extends BaseCommand
{
public CommandSetExit()
{
aliases.add("setto");
aliases.add("st");
requiredParameters.add("id");
helpDescription = "Changes the location where the gate will teleport players to your current location.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
try {
gate.setExit(player.getLocation());
}
catch (Exception e) {
sendMessage(e.getMessage());
}
sendMessage("The exit of gate '" + gate.getId() + "' is now where you stand.");
}
}

View File

@ -0,0 +1,32 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Plugin;
public class CommandSetHidden extends BaseCommand
{
public CommandSetHidden()
{
aliases.add("setHidden");
aliases.add("sh");
requiredParameters.add("id");
helpDescription = "Makes a gate NOT consist of gate blocks while open.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
try {
gate.setHidden(true);
}
catch (Exception e) {
sendMessage(e.getMessage());
}
sendMessage("The gate '" + gate.getId() + "' is now hidden.");
}
}

View File

@ -0,0 +1,45 @@
package de.craftinc.gates.commands;
import org.bukkit.Location;
import de.craftinc.gates.Plugin;
public class CommandSetLocation extends BaseLocationCommand
{
public CommandSetLocation()
{
aliases.add("setlocation");
aliases.add("sl");
requiredParameters.add("id");
helpDescription = "Set the entrance of the gate to your current location.";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
Location playerLocation = getValidPlayerLocation();
if (playerLocation == null) {
sendMessage("There is not enough room for a gate to open here");
return;
}
try {
gate.setLocation(playerLocation);
}
catch (Exception e) {
sendMessage(e.getMessage());
}
sendMessage("The location of '" + gate.getId() + "' is now at your current location.");
}
}

View File

@ -0,0 +1,34 @@
package de.craftinc.gates.commands;
import de.craftinc.gates.Plugin;
public class CommandSetVisible extends BaseCommand
{
public CommandSetVisible()
{
aliases.add("makevisible");
aliases.add("mv");
requiredParameters.add("id");
helpDescription = "Make that gate visible";
requiredPermission = Plugin.permissionManage;
}
public void perform()
{
try {
gate.setHidden(false);
}
catch (Exception e) {
sendMessage(e.getMessage());
}
sendMessage("The gate " + gate.getId() + " is now visible.");
}
}

View File

@ -0,0 +1,97 @@
package de.craftinc.gates.listeners;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.player.PlayerMoveEvent;
import de.craftinc.gates.Gate;
public abstract class BaseLocationListener
{
protected Gate getValidGateAtPlayerLocation(PlayerMoveEvent e) {
Gate gate = null;
Location playerLocation = e.getPlayer().getLocation();
World playerWorld = playerLocation.getWorld();
Block blockTo = e.getFrom().getBlock();
Block blockToUp = blockTo.getRelative(BlockFace.UP);
for (Gate g : Gate.getAll()) {
// Check if the gate is open and useable
World gateWorld = g.getLocation().getWorld();
if (g.isOpen() == false || !gateWorld.equals(playerWorld)) {
continue;
}
// Check if the location matches
for (Location l: g.getGateBlockLocations()) {
if (locationsAreAtSamePositions(l, blockTo.getLocation()) || locationsAreAtSamePositions(l, blockToUp.getLocation())) {
// Check if the gate is still valid
try {
g.validate();
gate = g;
break;
}
catch (Exception e2) {
// do nothing - gate is closed
}
}
}
}
return gate;
}
protected Gate getGateAtPlayerLocation(PlayerMoveEvent e) {
Gate gate = null;
Block blockTo = e.getFrom().getBlock();
Block blockToUp = blockTo.getRelative(BlockFace.UP);
System.out.println(blockTo.getLocation().getWorld().getName());
for (Gate g : Gate.getAll()) {
// Check if the location matches
for (Location l: g.getGateBlockLocations()) {
if (locationsAreAtSamePositions(l, blockTo.getLocation()) || locationsAreAtSamePositions(l, blockToUp.getLocation())) {
gate = g;
}
}
}
return gate;
}
/**
* Does the same as the equal method of Location but ignores pitch and yaw.
*/
protected boolean locationsAreAtSamePositions(final Location l1, final Location l2)
{
if (l1.getWorld() != l2.getWorld() && (l1.getWorld() == null || !l1.getWorld().equals(l2.getWorld()))) {
return false;
}
if (Double.doubleToLongBits(l1.getX()) != Double.doubleToLongBits(l2.getX())) {
return false;
}
if (Double.doubleToLongBits(l1.getY()) != Double.doubleToLongBits(l2.getY())) {
return false;
}
if (Double.doubleToLongBits(l1.getZ()) != Double.doubleToLongBits(l2.getZ())) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,51 @@
package de.craftinc.gates.listeners;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
public class PluginBlockListener implements Listener
{
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockPhysics(BlockPhysicsEvent event)
{
if (event.isCancelled())
return;
if (event.getBlock().getType() != Material.PORTAL) {
return;
}
if (isBlockInPortal(event.getBlock())) {
event.setCancelled(true);
}
}
public boolean isBlockInPortal(Block block)
{
if (block.getRelative(BlockFace.UP).getType() == Material.AIR) {
return false;
}
if (block.getRelative(BlockFace.DOWN).getType() == Material.AIR) {
return false;
}
if ( block.getRelative(BlockFace.NORTH).getType() != Material.AIR && block.getRelative(BlockFace.SOUTH).getType() != Material.AIR ) {
return true;
}
if ( block.getRelative(BlockFace.WEST).getType() != Material.AIR && block.getRelative(BlockFace.EAST).getType() != Material.AIR ) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,77 @@
package de.craftinc.gates.listeners;
import java.util.logging.Level;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import de.craftinc.gates.Gate;
import de.craftinc.gates.Plugin;
public class PluginPlayerListener extends BaseLocationListener implements Listener
{
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event)
{
if (event.isCancelled()) {
return;
}
// Check for permission
if (!hasPermission(event.getPlayer())) {
return;
}
// Find the gate at the current location.
Gate gateAtLocation = getValidGateAtPlayerLocation(event);
if (gateAtLocation == null) {
return;
}
// Teleport the player
checkChunkLoad(gateAtLocation.getLocation().getBlock());
Location gateExit = gateAtLocation.getExit();
Location playerLocation = event.getPlayer().getLocation();
Float newYaw = gateExit.getYaw() - gateExit.getYaw() + playerLocation.getYaw();
Location teleportToLocation = new Location( gateExit.getWorld(),
gateExit.getX(),
gateExit.getY(),
gateExit.getZ(),
newYaw,
playerLocation.getPitch() );
event.getPlayer().teleport(teleportToLocation);
event.setTo(teleportToLocation);
}
private void checkChunkLoad(Block b)
{
World w = b.getWorld();
Chunk c = b.getChunk();
if ( ! w.isChunkLoaded(c) )
{
Plugin.log(Level.FINE, "Loading chunk: " + c.toString() + " on: " + w.toString());
w.loadChunk(c);
}
}
protected boolean hasPermission(Player player) {
return player.hasPermission(Plugin.permissionUse) || player.hasPermission(Plugin.permissionAll);
}
}

View File

@ -0,0 +1,27 @@
package de.craftinc.gates.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPortalEvent;
import de.craftinc.gates.Gate;
public class PluginPortalListener extends BaseLocationListener implements Listener
{
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPortal(PlayerPortalEvent event)
{
if (event.isCancelled()) {
return;
}
// Find the gate at the current location.
Gate gateAtLocation = getGateAtPlayerLocation(event);
if (gateAtLocation != null) {
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,91 @@
package de.craftinc.gates.util;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import de.craftinc.gates.Plugin;
public class FloodUtil
{
private final static int frameBlockSearchLimit = 20;
private static final Set<BlockFace> exp1 = new HashSet<BlockFace>();
private static final Set<BlockFace> exp2 = new HashSet<BlockFace>();
static
{
exp1.add(BlockFace.UP);
exp1.add(BlockFace.DOWN);
exp1.add(BlockFace.EAST);
exp1.add(BlockFace.WEST);
exp2.add(BlockFace.UP);
exp2.add(BlockFace.DOWN);
exp2.add(BlockFace.NORTH);
exp2.add(BlockFace.SOUTH);
}
// For the same frame and location this set of blocks is deterministic
public static Set<Block> getGateFrameBlocks(Block block)
{
Set<Block> blocks1 = getAirFloodBlocks(block, new HashSet<Block>(), exp1, frameBlockSearchLimit);
Set<Block> blocks2 = getAirFloodBlocks(block, new HashSet<Block>(), exp2, frameBlockSearchLimit);
if (blocks1 == null && blocks2 == null) {
return null;
}
if (blocks1 == null) {
return blocks2;
}
if (blocks2 == null) {
return blocks1;
}
if (blocks1.size() > blocks2.size()) {
return blocks2;
}
return blocks1;
}
public static Set<Block> getAirFloodBlocks(Block startBlock, Set<Block> foundBlocks, Set<BlockFace> expandFaces, int limit)
{
if (foundBlocks == null)
return null;
if (foundBlocks.size() > limit)
{
Plugin.log(Level.ALL, "exceeding gate size limit.");
return null;
}
if (foundBlocks.contains(startBlock))
return foundBlocks;
if (startBlock.getType() == Material.AIR || startBlock.getType() == Material.PORTAL)
{
// ... We found a block :D ...
foundBlocks.add(startBlock);
// ... And flood away !
for (BlockFace face : expandFaces)
{
Block potentialBlock = startBlock.getRelative(face);
foundBlocks = getAirFloodBlocks(potentialBlock, foundBlocks, expandFaces, limit);
}
}
return foundBlocks;
}
}

View File

@ -0,0 +1,15 @@
package de.craftinc.gates.util;
import org.bukkit.Location;
public class GeometryUtil {
// How long between two locations?
public static double distanceBetweenLocations(Location location1, Location location2) {
double X = location1.getX() - location2.getX();
double Y = location1.getY() - location2.getY();
double Z = location1.getZ() - location2.getZ();
return Math.sqrt(X*X+Y*Y+Z*Z);
}
}

View File

@ -0,0 +1,62 @@
package de.craftinc.gates.util;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import de.craftinc.gates.Plugin;
/**
* NOTE: We do not care about yaw and pitch for gate locations. So we won't serialize them.
*/
public class LocationSerializer
{
protected static String worldKey = "world";
protected static String xKey = "x";
protected static String yKey = "y";
protected static String zKey = "z";
protected static World getWorld(String name)
{
World world = Plugin.instance.getServer().getWorld(name);
// TODO: Creating a world silently in the background is not a good thing I think. No one expects a Gate
// Plugin to do that. It would be better to handle gates which point to non-existing worlds safely (not
// teleporting at all)
if (world == null) {
world = Plugin.instance.getServer().createWorld(new WorldCreator(name).environment(Environment.NORMAL));
}
return world;
}
public static Map<String, Object> serializeLocation(Location l)
{
Map<String, Object> serializedLocation = new HashMap<String, Object>();
serializedLocation.put(worldKey, l.getWorld().getName());
serializedLocation.put(xKey, l.getX());
serializedLocation.put(yKey, l.getY());
serializedLocation.put(zKey, l.getZ());
return serializedLocation;
}
public static Location deserializeLocation(Map<String, Object> map)
{
World w = getWorld((String)map.get(worldKey));
double x = (Double) map.get(xKey);
double y = (Double) map.get(yKey);
double z = (Double) map.get(zKey);
return new Location(w, x, y, z);
}
}

View File

@ -0,0 +1,68 @@
package de.craftinc.gates.util;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
public class TextUtil
{
public static String titleize(String str)
{
String line = ChatColor.GOLD + repeat("_", 60);
String center = ".[ " + ChatColor.YELLOW + str + ChatColor.GOLD + " ].";
int pivot = line.length() / 2;
int eatLeft = center.length() / 2;
int eatRight = center.length() - eatLeft;
return line.substring(0, pivot - eatLeft) + center + line.substring(pivot + eatRight);
}
public static String repeat(String s, int times)
{
if (times <= 0)
return "";
return s + repeat(s, times-1);
}
/**
* Joins all emements of list into a single string, sperating the original strings with glue.
*/
public static String implode(List<String> list, String glue)
{
if (list.size() == 0) {
return "";
}
String ret = list.get(0);
for (int i=1; i<list.size(); i++) {
ret += glue + list.get(i);
}
return ret;
}
/**
* Joins all emements of list into a single string.
*/
public static String implode(List<String> list) {
return implode(list, "");
}
public static String getMaterialName(Material material)
{
String ret = material.toString();
ret = ret.replace('_', ' ');
ret = ret.toLowerCase();
return ret.substring(0, 1).toUpperCase() + ret.substring(1);
}
}