This commit is contained in:
Olof Larsson
2011-02-06 13:36:11 +01:00
commit b3ac8f8614
27 changed files with 4173 additions and 0 deletions

View File

@@ -0,0 +1,156 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.ChatColor;
import com.bukkit.mcteam.factions.util.TextUtil;
import com.bukkit.mcteam.util.AsciiCompass;
//import com.bukkit.mcteam.factions.util.*;
public class Board {
protected static Map<Coord, Integer> coordFactionIds;
static {
coordFactionIds = new HashMap<Coord, Integer>();
}
public static Faction getFactionAt(Coord coord) {
return Faction.get(getFactionIdAt(coord));
}
public static int getFactionIdAt(Coord coord) {
Integer factionId = coordFactionIds.get(coord);
if (factionId == null) {
return 0; // No faction
}
return factionId;
}
public static void unclaim(Coord coord) {
coordFactionIds.remove(coord);
save();
}
public static void claim(Coord coord, Faction faction) {
coordFactionIds.put(coord, faction.id);
save();
}
public static boolean isBorderCoord(Coord coord) {
Faction faction = Board.getFactionAt(coord);
Coord a = coord.getRelative(1, 0);
Coord b = coord.getRelative(-1, 0);
Coord c = coord.getRelative(0, 1);
Coord d = coord.getRelative(0, -1);
return faction != a.getFaction() && faction != b.getFaction() && faction != c.getFaction() && faction != d.getFaction();
}
public static void purgeFaction(Faction faction) {
purgeFaction(faction.id);
}
public static void purgeFaction(int factionId) {
Iterator<Entry<Coord, Integer>> iter = coordFactionIds.entrySet().iterator();
while (iter.hasNext()) {
Entry<Coord, Integer> entry = iter.next();
if (entry.getValue().equals(factionId)) {
iter.remove();
}
}
}
public static int getFactionCoordCount(Faction faction) {
return getFactionCoordCount(faction.id);
}
public static int getFactionCoordCount(int factionId) {
int ret = 0;
for (int thatFactionId : coordFactionIds.values()) {
if(thatFactionId == factionId) {
ret += 1;
}
}
return ret;
}
//----------------------------------------------//
// Map generation
//----------------------------------------------//
/**
* The map is relative to a coord and a faction
* north is in the direction of decreasing x
* east is in the direction of decreasing z
*/
public static ArrayList<String> getMap(Faction faction, Coord coord, double inDegrees) {
ArrayList<String> ret = new ArrayList<String>();
ret.add(TextUtil.titleize("("+coord+") "+coord.getFaction().getName(faction)));
int halfWidth = Conf.mapWidth / 2;
int halfHeight = Conf.mapHeight / 2;
Coord topLeft = coord.getRelative(-halfHeight, halfWidth);
int width = halfWidth * 2 + 1;
int height = halfHeight * 2 + 1;
// For each row
for (int dx = 0; dx < height; dx++) {
// Draw and add that row
String row = "";
for (int dz = 0; dz > -width; dz--) {
if(dz == -(halfWidth) && dx == halfHeight) {
row += ChatColor.AQUA+"+";
} else {
Coord coordHere = topLeft.getRelative(dx, dz);
Faction factionHere = coordHere.getFaction();
if (factionHere.id == 0) {
row += ChatColor.GRAY+"-";
} else {
row += factionHere.getRelation(faction).getColor()+"+";
}
}
}
ret.add(row);
}
// Get the compass
ArrayList<String> asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.RED, Conf.colorChrome);
// Pad the compass some
asciiCompass.set(0, asciiCompass.get(0));
asciiCompass.set(1, asciiCompass.get(1));
asciiCompass.set(2, asciiCompass.get(2));
// Add the compass
ret.set(1, asciiCompass.get(0)+ret.get(1).substring(3*3));
ret.set(2, asciiCompass.get(1)+ret.get(2).substring(3*3));
ret.set(3, asciiCompass.get(2)+ret.get(3).substring(3*3));
return ret;
}
//----------------------------------------------//
// Persistance
//----------------------------------------------//
public static boolean save() {
return EM.boardSave();
}
}

View File

@@ -0,0 +1,211 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.*;
import com.bukkit.mcteam.factions.struct.Relation;
public class Conf {
public static Integer logThreshold;
public static String prefixAdmin;
public static String prefixMod;
public static int factionNameMinLength;
public static int factionNameMaxLength;
public static int mapHeight;
public static int mapWidth;
public static double territoryShieldFactor;
// Chat control:
public static boolean useRelationColoredChat; // This can interfere with other chat formatting plugins. Test to turn it on or off.
// TODO experiment with displayname feature of bukkit
// TODO test to set format instead of overriding and offer a non colored mut **Title alternative...
// Colors
public static ChatColor colorMember;
public static ChatColor colorAlly;
public static ChatColor colorNeutral;
public static ChatColor colorEnemy;
public static ChatColor colorSystem;
public static ChatColor colorAction;
public static ChatColor colorChrome;
public static ChatColor colorCommand;
public static ChatColor colorParameter;
// Command names / aliases
public static List<String> aliasBase = new ArrayList<String>();
public static List<String> aliasHelp = new ArrayList<String>();
public static List<String> aliasList = new ArrayList<String>();
public static List<String> aliasShow = new ArrayList<String>();
public static List<String> aliasMap = new ArrayList<String>();
public static List<String> aliasHere = new ArrayList<String>();
public static List<String> aliasJoin = new ArrayList<String>();
public static List<String> aliasLeave = new ArrayList<String>();
public static List<String> aliasCreate = new ArrayList<String>();
public static List<String> aliasName = new ArrayList<String>();
public static List<String> aliasTitle = new ArrayList<String>();
public static List<String> aliasInvite = new ArrayList<String>();
public static List<String> aliasDeinvite = new ArrayList<String>();
public static List<String> aliasOpen = new ArrayList<String>();
public static List<String> aliasKick = new ArrayList<String>();
public static List<String> aliasModerator = new ArrayList<String>();
public static List<String> aliasAdmin = new ArrayList<String>();
public static List<String> aliasClaim = new ArrayList<String>();
public static List<String> aliasUnclaim = new ArrayList<String>();
public static List<String> aliasRelationAlly = new ArrayList<String>();
public static List<String> aliasRelationNeutral = new ArrayList<String>();
public static List<String> aliasRelationEnemy = new ArrayList<String>();
public static List<String> aliasDescription = new ArrayList<String>();
// Value aliases
public static List<String> aliasTrue = new ArrayList<String>();
// Power
public static double powerPerLand;
public static double powerPerPlayer;
public static double powerPerMinute; // Default health rate
public static double powerPerDeath;
public static double powerDefaultBonus;
// Protected blocks
public static List<Material> territoryProtectedMaterials = new ArrayList<Material>();
static {
logThreshold = 10;
prefixAdmin = "**";
prefixMod = "*";
factionNameMinLength = 3;
factionNameMaxLength = 40;
mapHeight = 8;
mapWidth = 49;
territoryShieldFactor = 0.33;
useRelationColoredChat = true;
colorMember = ChatColor.GREEN;
colorAlly = ChatColor.LIGHT_PURPLE;
colorNeutral = ChatColor.WHITE;
colorEnemy = ChatColor.RED;
colorSystem = ChatColor.YELLOW;
colorAction = ChatColor.LIGHT_PURPLE;
colorChrome = ChatColor.GOLD;
colorCommand = ChatColor.AQUA;
colorParameter = ChatColor.DARK_AQUA;
aliasBase.add("/f");
aliasBase.add("f");
aliasBase.add("/faction");
aliasBase.add("faction");
aliasBase.add("/factions");
aliasBase.add("factions");
aliasHelp.add("help");
aliasHelp.add("h");
aliasHelp.add("?");
aliasList.add("list");
aliasList.add("ls");
aliasShow.add("show");
aliasShow.add("who");
aliasMap.add("map");
aliasHere.add("here");
aliasJoin.add("join");
aliasLeave.add("leave");
aliasCreate.add("create");
aliasCreate.add("new");
aliasName.add("name");
aliasName.add("rename");
aliasTitle.add("title");
aliasInvite.add("invite");
aliasInvite.add("inv");
aliasDeinvite.add("deinvite");
aliasDeinvite.add("deinv");
aliasOpen.add("open");
aliasOpen.add("close");
aliasKick.add("kick");
aliasModerator.add("mod");
aliasAdmin.add("admin");
aliasClaim.add("claim");
aliasUnclaim.add("unclaim");
aliasUnclaim.add("declaim");
aliasRelationAlly.add("ally");
aliasRelationNeutral.add("neutral");
aliasRelationEnemy.add("enemy");
aliasDescription.add("desc");
aliasTrue.add("true");
aliasTrue.add("yes");
aliasTrue.add("y");
aliasTrue.add("ok");
aliasTrue.add("on");
aliasTrue.add("+");
powerPerLand = 1; // 1 power grants one land
powerPerPlayer = 5; // One player has 5 power
powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one death
powerPerDeath = 1; //A death makes you loose 2 power
powerDefaultBonus = 0; //A faction normally has a power bonus
territoryProtectedMaterials.add(Material.WOODEN_DOOR);
territoryProtectedMaterials.add(Material.DISPENSER);
territoryProtectedMaterials.add(Material.CHEST);
territoryProtectedMaterials.add(Material.FURNACE);
}
//----------------------------------------------//
// Color picking and stuff
//----------------------------------------------//
public static ChatColor relationColor(Relation relation) {
if (relation == Relation.MEMBER) {
return colorMember;
} else if (relation == Relation.ALLY) {
return colorAlly;
} else if (relation == Relation.NEUTRAL) {
return colorNeutral;
} else { //if (relation == FactionRelation.ENEMY) {
return colorEnemy;
}
}
//----------------------------------------------//
// Persistance
//----------------------------------------------//
public static boolean save() {
return EM.configSave();
}
}

View File

@@ -0,0 +1,77 @@
package com.bukkit.mcteam.factions.entities;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
public class Coord {
protected static transient int cellSize = 16;
public int x, z;
public Coord(int x, int z) {
this.x = x;
this.z = z;
}
// TODO implements cloneable
public Coord(Coord coord) {
this.x = coord.x;
this.z = coord.z;
}
public Coord() {
// Noarg constructor for google gson.
}
public Coord getRelative(int dx, int dz) {
return new Coord(this.x + dx, this.z + dz);
}
public static Coord from(int x, int z) {
return new Coord(x / cellSize - (x < 0 ? 1 : 0), z / cellSize - (z < 0 ? 1 : 0));
}
public static Coord from(Player player) {
return from(player.getLocation());
}
public static Coord from(Follower follower) {
return from(follower.getPlayer());
}
public static Coord from(Location loc) {
return from(loc.getBlockX(), loc.getBlockZ());
}
public static Coord parseCoord(Block block) {
return from(block.getX(), block.getZ());
}
public Faction getFaction() {
return Board.getFactionAt(this);
}
@Override
public String toString() {
return this.x + "," + this.z;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + x;
result = 31 * result + z;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Coord))
return false;
Coord o = (Coord) obj;
return this.x == o.x && this.z == o.z;
}
}

View File

@@ -0,0 +1,316 @@
package com.bukkit.mcteam.factions.entities;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.Factions;
import com.bukkit.mcteam.factions.util.*;
import com.bukkit.mcteam.util.DiscUtil;
import com.google.gson.*;
/**
* This is a entity manager that persists object to json.
* Before using the the EM you should always EM.loadAll().
* The methods assume that all on disc is loaded into memory.
*/
public class EM {
protected static Map<String, Follower> followers = new HashMap<String, Follower>(); // Where String is a lowercase playername
protected static Map<Integer, Faction> factions = new HashMap<Integer, Faction>(); // Where Integer is a primary auto increment key
protected static int nextFactionId;
// hardcoded config
protected final static String ext = ".json";
protected final static File folderBase = Factions.folder;
protected final static File folderFaction = new File(folderBase, "faction");
protected final static File folderFollower = new File(folderBase, "follower");
protected final static File fileConfig = new File(folderBase, "conf"+ext);
protected final static File fileBoard = new File(folderBase, "board"+ext);
public final static Gson gson = new GsonBuilder()
.setPrettyPrinting()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE)
.registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter()) // a "must have" adapter for GSON
.create();
public static void loadAll() {
configLoad();
Log.threshold = Conf.logThreshold;
boardLoad();
followerLoadAll();
factionLoadAll();
}
//----------------------------------------------//
// Config methods (load, save)
//----------------------------------------------//
public static boolean configLoad() {
if (fileConfig.exists()) {
try {
gson.fromJson(DiscUtil.read(fileConfig), Conf.class);
Log.info("Config was loaded from disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to load the config");
return false;
}
}
Log.info("No conf.json found! Creating a new one with the default values");
//configSave(); // FOR DEBUGGING...
return true;
}
public static boolean configSave() {
try {
DiscUtil.write(fileConfig, gson.toJson(new Conf()));
Log.debug("Config was saved to disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the config");
return false;
}
}
//----------------------------------------------//
// Board methods (load, save)
//----------------------------------------------//
public static boolean boardLoad() {
if (fileBoard.exists()) {
try {
gson.fromJson(DiscUtil.read(fileBoard), Board.class);
Log.info("Board was loaded from disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to load the board");
return false;
}
}
Log.info("No board.json found! Creating a new one with the default values");
//boardSave(); // FOR DEBUGGING...
return true;
}
public static boolean boardSave() {
try {
DiscUtil.write(fileBoard, gson.toJson(new Board()));
Log.debug("Board was saved to disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the board");
return false;
}
}
//----------------------------------------------//
// Follower methods (loadAll, get, save)
//----------------------------------------------//
/**
* This method will create a follower entity and assign the link to the corresponding player.
*/
public static void onPlayerLogin(Player player) {
Follower follower = followerGet(player);
follower.player = player;
}
public static void onPlayerLogout(Player player) {
followers.get(player.getName()).player = null;
}
/**
* This method loads all followers from disc into memory.
*/
public static void followerLoadAll() {
Log.info("Loading all followers from disc...");
folderFollower.mkdirs();
class jsonFileFilter implements FileFilter {
public boolean accept(File file) {
return (file.getName().toLowerCase().endsWith(ext) && file.isFile());
}
}
File[] jsonFiles = folderFollower.listFiles(new jsonFileFilter());
for (File jsonFile : jsonFiles) {
// Extract the name from the filename. The name is filename minus ".json"
String name = jsonFile.getName();
name = name.substring(0, name.length() - ext.length());
try {
Follower follower = gson.fromJson(DiscUtil.read(jsonFile), Follower.class);
follower.id = name;
followers.put(follower.id, follower);
Log.debug("loaded follower "+name);
} catch (Exception e) {
e.printStackTrace();
Log.warn("failed to load follower "+name);
}
}
}
public static Collection<Follower> followerGetAll() {
return followers.values();
}
/**
* This method returns the follower object for a player
* A new Follower will be created if the player did not have one
*/
public static Follower followerGet(Player player) {
String key = followerKey(player);
if (followers.containsKey(key)) {
return followers.get(key);
}
return followerCreate(player);
}
public static boolean followerSave(String id) {
Object obj = followers.get(id);
if (obj == null) {
Log.warn("Could not save follower "+id+" as it was not loaded");
return false;
}
folderFollower.mkdirs();
File file = new File(folderFollower, id+ext);
try {
DiscUtil.write(file, gson.toJson(obj));
Log.debug("Saved the follower "+id);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the follower "+id);
return false;
}
}
protected static String followerKey(Player player) {
return player.getName();
}
protected static Follower followerCreate(Player player) {
Log.debug("Creating new follower "+followerKey(player));
Follower follower = new Follower();
follower.id = followerKey(player);
followers.put(follower.id, follower);
follower.save();
return follower;
}
//----------------------------------------------//
// Faction methods (loadAll, get, create, delete, save)
//----------------------------------------------//
/**
* This method loads all followers from disc into memory.
*/
public static void factionLoadAll() {
Log.info("Loading all factions from disc...");
folderFaction.mkdirs();
class jsonFileFilter implements FileFilter
{
public boolean accept(File file) {
return (file.getName().toLowerCase().endsWith(ext) && file.isFile());
}
}
nextFactionId = 0;
File[] jsonFiles = folderFaction.listFiles(new jsonFileFilter());
for (File jsonFile : jsonFiles) {
// Extract the name from the filename. The name is filename minus ".json"
String name = jsonFile.getName();
name = name.substring(0, name.length() - ext.length());
int id = Integer.parseInt(name);
// Eventually push next id forward
if (nextFactionId < id) {
nextFactionId = id;
}
try {
Faction faction = gson.fromJson(DiscUtil.read(jsonFile), Faction.class);
faction.id = id;
factions.put(faction.id, faction);
Log.debug("loaded faction "+id);
} catch (Exception e) {
e.printStackTrace();
Log.warn("Failed to load faction "+id);
}
}
nextFactionId += 1; // make it the next id and not the current highest.
// Make sure the default neutral faction exists
if ( ! factions.containsKey(0)) {
Faction faction = new Faction();
faction.name = "*No faction*";
faction.description = "\"The faction for the factionless :P\"";
faction.id = 0;
factions.put(faction.id, faction);
}
}
public static Faction factionGet(Integer factionId) {
return factions.get(factionId);
}
public static Collection<Faction> factionGetAll() {
return factions.values();
}
public static Faction factionCreate(){
Faction faction = new Faction();
faction.id = nextFactionId;
nextFactionId += 1;
factions.put(faction.id, faction);
Log.debug("created new faction "+faction.id);
faction.save();
return faction;
}
public static boolean factionDelete(Integer id) {
// NOTE that this does not do any security checks.
// Follower might get orphaned foreign id's
// purge from board
Board.purgeFaction(id);
// Remove the file
File file = new File(folderFaction, id+ext);
file.delete();
// Remove the faction
factions.remove(id);
return true; // TODO
}
public static boolean factionSave(Integer id) {
Object obj = factions.get(id);
if (obj == null) {
Log.warn("Could not save faction "+id+" as it was not loaded");
return false;
}
folderFaction.mkdirs();
File file = new File(folderFaction, id+ext);
try {
DiscUtil.write(file, gson.toJson(obj));
Log.debug("saved the faction "+id);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("failed to save the faction "+id);
return false;
}
}
}

View File

@@ -0,0 +1,363 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.Factions;
import com.bukkit.mcteam.factions.struct.Relation;
import com.bukkit.mcteam.factions.struct.Role;
import com.bukkit.mcteam.factions.util.Log;
import com.bukkit.mcteam.util.ChatFixUtil;
public class Faction {
public transient int id;
protected Map<Integer, Relation> relationWish;
protected Set<String> invites; // Where string is a follower id (lower case name)
protected boolean open;
protected String name;
protected String description;
public Faction() {
this.relationWish = new HashMap<Integer, Relation>();
this.invites = new HashSet<String>();
this.open = true;
this.name = "Untitled Faction :(";
this.description = "Default faction description :(";
}
// -------------------------------
// Information
// -------------------------------
public String getName() {
return this.getName("");
}
public String getName(String prefix) {
return prefix+this.name;
}
public String getName(Faction otherFaction) {
return this.getName(otherFaction.getRelationColor(this).toString());
}
public String getName(Follower otherFollower) {
return this.getName(otherFollower.getRelationColor(this).toString());
}
public void setName(String newName) {
this.name = newName;
this.save();
}
public String getDescription() {
return this.description;
}
public void setDescription(String value) {
this.description = value;
this.save();
}
public boolean getOpen() {
return open;
}
public void setOpen(boolean isOpen) {
open = isOpen;
this.save();
}
//----------------------------------------------//
// Power
//----------------------------------------------//
public double getPower() {
double ret = this.getPowerBonus();
for (Follower follower : this.getFollowersAll()) {
ret += follower.getPower();
}
return ret;
}
public double getPowerBonus() {
return Conf.powerDefaultBonus; // TODO this could be modified by commands later on
}
public double getPowerMax() {
double ret = this.getPowerBonus();
for (Follower follower : this.getFollowersAll()) {
ret += follower.getPowerMax();
}
return ret;
}
public int getPowerRounded() {
return (int) Math.round(this.getPower());
}
public int getPowerMaxRounded() {
return (int) Math.round(this.getPowerMax());
}
public int getLandRounded() {
return Board.getFactionCoordCount(this);
}
public double getLandMax() {
return this.getPower() / Conf.powerPerLand;
}
public int getLandMaxRounded() {
return (int) Math.round(this.getLandMax());
}
public boolean hasLandInflation() {
return Board.getFactionCoordCount(this) > this.getLandMaxRounded();
}
// -------------------------------
// Membership management
// -------------------------------
public ArrayList<String> invite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
Log.debug("follower.getFaction().id"+follower.getFaction().id);
Log.debug("this.id"+this.id);
if (follower.getFaction().equals(this)) { // error här?
errors.add(Conf.colorSystem+follower.getFullName()+" is already a member of "+this.getName());
}
if(errors.size() > 0) {
return errors;
}
this.invites.add(follower.id);
this.save();
return errors;
}
public ArrayList<String> deinvite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if (follower.getFaction().equals(this)) {
errors.add(Conf.colorSystem+follower.getFullName()+" is already a member of "+this.getName());
errors.add(Conf.colorSystem+"You might want to "+Conf.colorCommand+Conf.aliasBase.get(0)+" "+Conf.aliasKick.get(0)+Conf.colorParameter+" "+follower.getName());
}
if(errors.size() > 0) {
return errors;
}
this.invites.remove(follower.id);
this.save();
return errors;
}
public ArrayList<String> kick(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
removeFollower(follower);
return errors;
}
public boolean isInvited(Follower follower) {
return invites.contains(follower.id);
}
// -------------------------------
// Followers
// -------------------------------
public ArrayList<Follower> getFollowersAll() {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id) {
ret.add(follower);
}
}
return ret;
}
public ArrayList<Follower> getFollowersWhereOnline(boolean online) {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id && follower.isOnline() == online) {
ret.add(follower);
}
}
return ret;
}
public ArrayList<Follower> getFollowersWhereRole(Role role) {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id && follower.role.equals(role)) {
ret.add(follower);
}
}
return ret;
}
public void removeFollower(Follower follower) {
if (this.id != follower.factionId) {
return; // safety check
}
this.invites.remove(follower.id);
follower.resetFactionData();
follower.save();
this.save();
}
public ArrayList<Player> getOnlinePlayers() {
ArrayList<Player> ret = new ArrayList<Player>();
for (Player player: Factions.server.getOnlinePlayers()) {
Follower follower = Follower.get(player);
if (follower.factionId == this.id) {
ret.add(player);
}
}
return ret;
}
//----------------------------------------------//
// Faction name
//----------------------------------------------//
private transient static ArrayList<String> nameWhitelist = new ArrayList<String>(Arrays.asList(new String []{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z"
}));
public static String toComparisonName(String name) {
String ret = "";
for (char c : name.toCharArray()) {
if (nameWhitelist.contains(String.valueOf(c))) {
ret += c;
}
}
return ret.toLowerCase();
}
public static ArrayList<String> validateName(String name) {
ArrayList<String> errors = new ArrayList<String>();
if(Faction.toComparisonName(name).length() < Conf.factionNameMinLength) {
errors.add(Conf.colorSystem+"That name is to short");
}
if(name.length() > Conf.factionNameMaxLength) {
errors.add(Conf.colorSystem+"That name is to long");
}
return errors;
}
public String getComparisonName() {
return Faction.toComparisonName(this.name);
}
public static Faction find(String name) {
String compName = Faction.toComparisonName(name);
for (Faction faction : Faction.getAll()) {
if (faction.getComparisonName().equals(compName)) {
return faction;
}
}
return null;
}
public static boolean isNameTaken(String name) {
return Faction.find(name) != null;
}
//----------------------------------------------//
// Messages - Directly connected to ChatFixUtil
//----------------------------------------------//
public void sendMessage(String message, boolean fix) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), message, fix);
}
public void sendMessage(List<String> messages, boolean fix) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), messages, fix);
}
public void sendMessage(String message) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), message, true);
}
public void sendMessage(List<String> messages) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), messages, true);
}
// -------------------------------
// Relation and relation colors
// -------------------------------
public Relation getRelationWish(Faction otherFaction) {
if (this.relationWish.containsKey(otherFaction.id)){
return this.relationWish.get(otherFaction.id);
}
return Relation.NEUTRAL;
}
public void setRelationWish(Faction otherFaction, Relation relation) {
if (this.relationWish.containsKey(otherFaction.id) && relation.equals(Relation.NEUTRAL)){
this.relationWish.remove(otherFaction.id);
return;
}
this.relationWish.put(otherFaction.id, relation);
}
public Relation getRelation(Faction otherFaction) {
if (otherFaction.id == 0 || this.id == 0) {
return Relation.NEUTRAL;
}
if (otherFaction.equals(this)) {
return Relation.MEMBER;
}
if(this.getRelationWish(otherFaction).value >= otherFaction.getRelationWish(this).value) {
return otherFaction.getRelationWish(this);
}
return this.getRelationWish(otherFaction);
}
public Relation getRelation(Follower follower) {
return getRelation(follower.getFaction());
}
public ChatColor getRelationColor(Faction otherFaction) {
return this.getRelation(otherFaction).getColor();
}
public ChatColor getRelationColor(Follower follower) {
return this.getRelation(follower).getColor();
}
//----------------------------------------------//
// Persistance and entity management
//----------------------------------------------//
public static Faction create() {
return EM.factionCreate();
}
public static Faction get(Integer factionId) {
return EM.factionGet(factionId);
}
public static Collection<Faction> getAll() {
return EM.factionGetAll();
}
public boolean save() {
return EM.factionSave(this.id);
}
}

View File

@@ -0,0 +1,400 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.struct.*;
import com.bukkit.mcteam.factions.util.Log;
import com.bukkit.mcteam.util.ChatFixUtil;
public class Follower {
public transient String id; // The is the name of the player
public transient Player player; // The is the name of the player
public int factionId;
public Role role;
private String title;
private double power;
private long lastPowerUpdateTime;
private boolean mapAutoUpdating;
public Follower() {
this.resetFactionData();
this.power = this.getPowerMax();
this.lastPowerUpdateTime = System.currentTimeMillis();
this.mapAutoUpdating = false;
}
protected void resetFactionData() {
this.factionId = 0; // The default neutral faction
this.role = Role.NORMAL;
this.title = "";
}
public Player getPlayer() {
return this.player;
}
public boolean isOnline() {
return this.getPlayer() != null;
}
public boolean isMapAutoUpdating() {
return mapAutoUpdating;
}
public void setMapAutoUpdating(boolean mapAutoUpdating) {
this.mapAutoUpdating = mapAutoUpdating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
this.save();
}
//----------------------------------------------//
// Health
//----------------------------------------------//
public void heal(int amnt) {
Player player = this.getPlayer();
if (player == null) {
return;
}
player.setHealth(player.getHealth() + amnt);
}
//----------------------------------------------//
// Power
//----------------------------------------------//
public double getPower() {
this.updatePower();
return this.power;
}
protected void alterPower(double delta) {
this.power += delta;
if (this.power > this.getPowerMax()) {
this.power = this.getPowerMax();
} else if (this.power < this.getPowerMin()) {
this.power = this.getPowerMin();
}
Log.debug("Power of "+this.getFullName()+" is now: "+this.power);
}
public double getPowerMax() {
return Conf.powerPerPlayer;
}
public double getPowerMin() {
return -Conf.powerPerPlayer;
}
public int getPowerRounded() {
return (int) Math.round(this.getPower());
}
public int getPowerMaxRounded() {
return (int) Math.round(this.getPowerMax());
}
public int getPowerMinRounded() {
return (int) Math.round(this.getPowerMin());
}
protected void updatePower() {
long now = System.currentTimeMillis();
long millisPassed = now - this.lastPowerUpdateTime;
this.lastPowerUpdateTime = now;
int millisPerMinute = 60*1000;
this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute);
//this.save(); // This would save to often. So we save this on player quit instead.
}
public void onDeath() {
this.updatePower();
this.alterPower(-Conf.powerPerDeath);
}
//----------------------------------------------//
// Territory
//----------------------------------------------//
public boolean isInOwnTerritory() {
return Board.getFactionAt(this.getCoord()) == this.getFaction();
}
public boolean isInOthersTerritory() {
Faction factionHere = Board.getFactionAt(this.getCoord());
return factionHere.id != 0 && factionHere != this.getFaction();
}
public Coord getCoord() {
return Coord.from(this);
}
public void sendFactionHereMessage() {
Faction factionHere = Board.getFactionAt(this.getCoord());
String msg = Conf.colorSystem+" ~ "+factionHere.getName(this);
this.sendMessage(msg);
}
//----------------------------------------------//
// Faction management
//----------------------------------------------//
public Faction getFaction() {
return EM.factionGet(factionId);
}
public ArrayList<String> join(Faction faction) {
ArrayList<String> errors = new ArrayList<String>();
if (faction.id == this.factionId) {
errors.add(Conf.colorSystem+"You are already a member of "+faction.getRelationColor(this)+faction.getName());
}
if( ! faction.getOpen() && ! faction.isInvited(this)) {
errors.add(Conf.colorSystem+"This guild requires invitation.");
}
if (this.factionId != 0) {
errors.add(Conf.colorSystem+"You must leave your current faction first.");
}
if (errors.size() > 0) {
return errors;
}
this.resetFactionData();
if(faction.getFollowersAll().size() == 0) {
this.role = Role.ADMIN;
} else {
this.role = Role.NORMAL;
}
this.factionId = faction.id;
faction.deinvite(this);
this.save();
return errors;
}
public ArrayList<String> leave() {
ArrayList<String> errors = new ArrayList<String>();
if (this.role == Role.ADMIN && this.getFaction().getFollowersAll().size() > 1) {
errors.add(Conf.colorSystem+"You must give the admin role to someone else first.");
}
if(this.factionId == 0) {
errors.add(Conf.colorSystem+"You are not member of any faction.");
}
if (errors.size() > 0) {
return errors;
}
this.resetFactionData();
this.save();
return errors;
}
public ArrayList<String> createFaction(String name) {
ArrayList<String> errors = new ArrayList<String>();
if (this.factionId != 0) {
errors.add(Conf.colorSystem+"You must leave your current faction first.");
}
if (Faction.isNameTaken(name)) {
errors.add(Conf.colorSystem+"That name is already in use.");
}
errors.addAll(Faction.validateName(name));
if (errors.size() > 0) {
return errors;
}
Faction faction = EM.factionCreate();
faction.setName(name);
faction.save();
this.join(faction);
this.role = Role.ADMIN;
this.save();
return errors;
}
public ArrayList<String> invite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
//Log.debug("this.role: "+this.role);
//Log.debug("this.role.value: "+this.role.value);
//Log.debug("FactionRole.MODERATOR.value: "+FactionRole.MODERATOR.value);
if (this.role.value < Role.MODERATOR.value) {
errors.add(Conf.colorSystem+"You must me be a moderator to invite.");
}
if(errors.size() > 0) {
return errors;
}
return this.getFaction().invite(follower);
}
public ArrayList<String> deinvite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if (this.role.value < Role.MODERATOR.value) {
errors.add(Conf.colorSystem+"You must me be a moderator to deinvite.");
}
if(errors.size() > 0) {
return errors;
}
return follower.getFaction().deinvite(follower);
}
public ArrayList<String> kick(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if ( ! follower.getFaction().equals(this.getFaction())) {
errors.add(this.getRelationColor(follower)+follower.getFullName()+Conf.colorSystem+" is not a member of "+Conf.colorMember+this.getFaction().getName());
} else if (follower.equals(this)) {
errors.add(Conf.colorSystem+"You can not kick yourself.");
errors.add(Conf.colorSystem+"You might want to "+Conf.colorCommand+Conf.aliasBase.get(0)+" "+Conf.aliasLeave.get(0));
} else if (follower.role.value >= this.role.value) { // TODO add more informative messages.
errors.add(Conf.colorSystem+"Your rank is to low to kick this player.");
}
if(errors.size() > 0) {
return errors;
}
return follower.getFaction().kick(follower);
}
//----------------------------------------------//
// Login info
//----------------------------------------------//
public void sendJoinInfo() { // TODO Missplaced!?
// Do we even whant to use message of the day...
// Perhaps that is up to another plugin...
//this.getPlayer().sendMessage(ChatColor.GREEN + "This is a faction server! Type "+Conf.colorCommand+"/f"+ChatColor.GREEN +" for more info :D");
}
//----------------------------------------------//
// Messages - Directly connected to ChatFixUtil
//----------------------------------------------//
public void sendMessage(String message, boolean fix) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, message, fix);
}
public void sendMessage(List<String> messages, boolean fix) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, messages, fix);
}
public void sendMessage(String message) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, message, true);
}
public void sendMessage(List<String> messages) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, messages, true);
}
//----------------------------------------------//
// Search
//----------------------------------------------//
public static Follower find(String name) {
for (Follower follower : EM.followerGetAll()) {
if (follower.getName().equalsIgnoreCase(name.trim())) {
return follower;
}
}
return null;
}
// -------------------------------
// Relation and relation colors
// -------------------------------
public Relation getRelation(Faction faction) {
return faction.getRelation(this);
}
public Relation getRelation(Follower follower) {
return this.getFaction().getRelation(follower);
}
public ChatColor getRelationColor(Faction faction) {
return faction.getRelationColor(this);
}
public ChatColor getRelationColor(Follower follower) {
return this.getRelation(follower).getColor();
}
//----------------------------------------------//
// Display the name of this follower
//----------------------------------------------//
public String getName() {
return this.id;
}
public String getFullName() {
return getFullName("");
}
public String getFullName(Faction otherFaction) {
return getFullName(otherFaction.getRelationColor(this).toString());
}
public String getFullName(Follower otherFollower) {
return getFullName(otherFollower.getRelationColor(this).toString());
}
public String getFullName(String prefix) {
String ret = prefix;
if (this.role.equals(Role.ADMIN)) {
ret += Conf.prefixAdmin;
} else if (this.role.equals(Role.MODERATOR)) {
ret += Conf.prefixMod;
}
if (this.title.length() > 0) {
ret += this.title + " ";
}
ret += this.getName();
return ret;
}
//----------------------------------------------//
// Persistance and entity management
//----------------------------------------------//
public boolean save() {
return EM.followerSave(this.id);
}
public static Follower get(Player player) {
return EM.followerGet(player);
}
public static Collection<Follower> getAll() {
return EM.followerGetAll();
}
}