diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6e2c058 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.classpath +.project +bin +lib diff --git a/Craftizens.java b/Craftizens.java deleted file mode 100644 index 4967411..0000000 --- a/Craftizens.java +++ /dev/null @@ -1,104 +0,0 @@ -import java.util.HashSet; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.List; -import java.io.File; -import java.io.FileWriter; -import java.io.BufferedWriter; -import java.io.IOException; -import java.util.Scanner; -import java.util.logging.*; - -public class Craftizens extends Plugin { - static final Logger log = Logger.getLogger("Minecraft"); - - public static boolean DEBUG = true; - public static String NPC_PREFIX = "§e"; - public static String NPC_SUFFIX = " (NPC)"; - public static String TEXT_COLOR = Colors.Yellow; - public static int INTERACT_ITEM = 340; - public static int INTERACT_ITEM_2 = 340; - public static int INTERACT_RANGE = 2; - public static int INTERACT_ANGLE_VARIATION = 25; - public static int QADMIN_BOUNDARY_MARKER = 340; - public static boolean QUESTS_ENABLED = true; - - public static CraftizenDataSource data; - public static HashSet npcs; - public static HashMap pendingQuests; - public static HashMap> activeQuests; - public static HashMap newQuests; - - private static CraftizenTicker ticker; - private static CraftizensListener listener; - - public void initialize() { - listener = new CraftizensListener(); - etc.getLoader().addListener(PluginLoader.Hook.COMMAND, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.ARM_SWING, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.BLOCK_DESTROYED, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.BLOCK_CREATED, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.PLAYER_MOVE, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.LOGIN, listener, this, PluginListener.Priority.MEDIUM); - etc.getLoader().addListener(PluginLoader.Hook.DISCONNECT, listener, this, PluginListener.Priority.MEDIUM); - } - - public void enable() { - // load properties - PropertiesFile props = new PropertiesFile("craftizens.properties"); - DEBUG = props.getBoolean("debug-mode",false); - NPC_PREFIX = props.getString("npc-name-prefix","§e"); - NPC_SUFFIX = props.getString("npc-name-suffix"," (NPC)"); - TEXT_COLOR = "§" + props.getString("quest-text-color","e"); - INTERACT_ITEM = props.getInt("npc-interact-item",340); - INTERACT_ITEM_2 = props.getInt("npc-interact-item-2",340); - INTERACT_RANGE = props.getInt("npc-interact-range",2); - INTERACT_ANGLE_VARIATION = props.getInt("npc-interact-angle-variation",25); - QADMIN_BOUNDARY_MARKER = props.getInt("qadmin-boundary-marker",340); - QUESTS_ENABLED = props.getBoolean("quests-enabled",true); - - data = new CraftizenSQLDataSource(); - - Craftizen.getPlayerList(); - npcs = data.loadCraftizens(); - - ticker = new CraftizenTicker(2000); - Thread t = new Thread(ticker); - t.start(); - - // load quests - pendingQuests = new HashMap(); - activeQuests = new HashMap>(); - for (Player p : etc.getServer().getPlayerList()) { - CraftizensListener.loadActiveQuests(p); - } - - log.info("Craftizens v0.6 loaded successfully!"); - } - - public void disable() { - ticker.stop(); - ticker = null; - - for (Craftizen npc : npcs) { - npc.delete(); - } - npcs = null; - - // save quest progress - for (String s : activeQuests.keySet()) { - for (Quest q : activeQuests.get(s)) { - if (q != null) { - q.saveProgress(); - } - } - } - - pendingQuests = null; - activeQuests = null; - newQuests = null; - - data = null; - } - -} diff --git a/Craftizens.updatr b/Craftizens.updatr new file mode 100644 index 0000000..3ac8454 --- /dev/null +++ b/Craftizens.updatr @@ -0,0 +1,5 @@ +name = Craftizens +version = 0.8.2 +url = www.stwing.upenn.edu/~martinja/minecraft/Craftizens.updatr +file = www.stwing.upenn.edu/~martinja/minecraft/Craftizens.jar +notes = Now with Updatr support! \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..4ad4bb7 --- /dev/null +++ b/README.txt @@ -0,0 +1,10 @@ +0.7.0 - Added rankreq and rankreward functionality + +0.7.1 - Added iConomy hook; Also I added the .sql script to the commit + +0.7.2 - Added support for JDBC; Currently HyperSQL and SQLite + +0.8.0 - Bugfixes, updated for Beta + +Find latest compiled JAR here: +http://www.stwing.upenn.edu/~martinja/minecraft/ diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..cd45925 --- /dev/null +++ b/build.xml @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/craftizens.hysql.sql b/craftizens.hysql.sql new file mode 100644 index 0000000..48e0364 --- /dev/null +++ b/craftizens.hysql.sql @@ -0,0 +1,67 @@ +CREATE TABLE craftizens ( + npc_id VARCHAR(12) NOT NULL, + npc_name VARCHAR(30)NOT NULL, + posx DOUBLE NOT NULL, + posy DOUBLE NOT NULL, + posz DOUBLE NOT NULL, + rotation FLOAT NOT NULL, + pitch FLOAT NOT NULL, + PRIMARY KEY (npc_id) +); + +CREATE TABLE quests ( + id VARCHAR(12) NOT NULL, + quest_name VARCHAR(512) NOT NULL, + start_npc VARCHAR(12) NOT NULL, + end_npc VARCHAR(12) NOT NULL, + items_provided VARCHAR(512) DEFAULT NULL, + rewards VARCHAR(512) DEFAULT NULL, + quest_desc VARCHAR(256) NOT NULL, + quest_type VARCHAR(10) NOT NULL, + prereq VARCHAR(12) DEFAULT NULL, + location VARCHAR(512) DEFAULT NULL, + data VARCHAR(512) DEFAULT NULL, + PRIMARY KEY (id) +); + +CREATE TABLE quests_active ( + player_name VARCHAR(25) NOT NULL, + quest_id VARCHAR(12) NOT NULL, + progress VARCHAR(50) DEFAULT NULL, + PRIMARY KEY (player_name,quest_id) +); + +CREATE TABLE quests_completed ( + player_name VARCHAR(25) NOT NULL, + quest_id VARCHAR(12) NOT NULL, + date_completed TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + PRIMARY KEY (player_name,quest_id) +); + +/* v0.2 update */ + +ALTER TABLE craftizens ADD COLUMN item_in_hand INT DEFAULT 0 NOT NULL; + +/* v0.5 update */ + +ALTER TABLE quests ADD COLUMN completion_text VARCHAR(512) DEFAULT NULL; + +CREATE TABLE craftizens_dialog ( + npc_id VARCHAR(12) NOT NULL, + dialog_id VARCHAR(12) NOT NULL, + dialog_text VARCHAR(512) NOT NULL, + PRIMARY KEY (npc_id,dialog_id) +); + +/* v0.6 update */ + +ALTER TABLE craftizens ADD COLUMN route_type VARCHAR(8) DEFAULT NULL; +ALTER TABLE craftizens ADD COLUMN route VARCHAR(512) DEFAULT NULL; + +/* v0.7 update */ +ALTER TABLE quests ADD COLUMN rankreq VARCHAR(12) DEFAULT NULL BEFORE location; +ALTER TABLE quests ADD COLUMN rankreward VARCHAR(12) DEFAULT NULL BEFORE location; + +/* v0.7.1 update */ +ALTER TABLE quests ADD COLUMN cost VARCHAR(12) DEFAULT '0' BEFORE location; +ALTER TABLE quests ADD COLUMN prize VARCHAR(12) DEFAULT '0' BEFORE location; diff --git a/craftizens.mysql.sql b/craftizens.mysql.sql new file mode 100644 index 0000000..e342f24 --- /dev/null +++ b/craftizens.mysql.sql @@ -0,0 +1,67 @@ +CREATE TABLE `craftizens` ( + `npc_id` VARCHAR(12) NOT NULL, + `npc_name` VARCHAR(30) NOT NULL, + `posx` DOUBLE NOT NULL, + `posy` DOUBLE NOT NULL, + `posz` DOUBLE NOT NULL, + `rotation` FLOAT NOT NULL, + `pitch` FLOAT NOT NULL, + PRIMARY KEY (`npc_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +CREATE TABLE `quests` ( + `id` VARCHAR(12) NOT NULL, + `quest_name` TEXT NOT NULL, + `start_npc` VARCHAR(12) NOT NULL, + `end_npc` VARCHAR(12) NOT NULL, + `items_provided` TEXT DEFAULT NULL, + `rewards` TEXT DEFAULT NULL, + `quest_desc` MEDIUMTEXT NOT NULL, + `quest_type` VARCHAR(10) NOT NULL, + `prereq` VARCHAR(12) DEFAULT NULL, + `location` TEXT DEFAULT NULL, + `data` TEXT DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +CREATE TABLE `quests_active` ( + `player_name` VARCHAR(25) NOT NULL, + `quest_id` VARCHAR(12) NOT NULL, + `progress` VARCHAR(50) DEFAULT NULL, + PRIMARY KEY (`player_name`,`quest_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +CREATE TABLE `quests_completed` ( + `player_name` VARCHAR(25) NOT NULL, + `quest_id` VARCHAR(12) NOT NULL, + `date_completed` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`player_name`,`quest_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +-- v0.2 update + +ALTER TABLE `craftizens` ADD COLUMN `item_in_hand` INT NOT NULL DEFAULT 0 AFTER `pitch`; + +-- v0.5 update + +ALTER TABLE `quests` ADD COLUMN `completion_text` TEXT DEFAULT NULL AFTER `data`; + +CREATE TABLE `craftizens_dialog` ( + `npc_id` VARCHAR(12) NOT NULL, + `dialog_id` VARCHAR(12) NOT NULL, + `dialog_text` TEXT NOT NULL, + PRIMARY KEY (`npc_id`,`dialog_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +-- v0.6 update + +ALTER TABLE `craftizens` ADD COLUMN `route_type` VARCHAR(8) DEFAULT NULL AFTER `item_in_hand`; +ALTER TABLE `craftizens` ADD COLUMN `route` TEXT DEFAULT NULL AFTER `route_type`; + +-- v0.7 update +ALTER TABLE `quests` ADD COLUMN `rankreq` VARCHAR(12) DEFAULT NULL AFTER `prereq`; +ALTER TABLE `quests` ADD COLUMN `rankreward` VARCHAR(12) DEFAULT NULL AFTER `rankreq`; + +-- v0.7.1 update +ALTER TABLE `quests` ADD COLUMN `cost` VARCHAR(12) DEFAULT '0' AFTER `rankreward`; +ALTER TABLE `quests` ADD COLUMN `prize` VARCHAR(12) DEFAULT '0' AFTER `cost`; diff --git a/craftizens.sqlite3.sql b/craftizens.sqlite3.sql new file mode 100644 index 0000000..7d6bb4c --- /dev/null +++ b/craftizens.sqlite3.sql @@ -0,0 +1,67 @@ +CREATE TABLE `craftizens` ( + `npc_id` VARCHAR(12) NOT NULL, + `npc_name` VARCHAR(30) NOT NULL, + `posx` DOUBLE NOT NULL, + `posy` DOUBLE NOT NULL, + `posz` DOUBLE NOT NULL, + `rotation` FLOAT NOT NULL, + `pitch` FLOAT NOT NULL, + PRIMARY KEY (`npc_id`) +); + +CREATE TABLE `quests` ( + `id` VARCHAR(12) NOT NULL, + `quest_name` TEXT NOT NULL, + `start_npc` VARCHAR(12) NOT NULL, + `end_npc` VARCHAR(12) NOT NULL, + `items_provided` TEXT DEFAULT NULL, + `rewards` TEXT DEFAULT NULL, + `quest_desc` MEDIUMTEXT NOT NULL, + `quest_type` VARCHAR(10) NOT NULL, + `prereq` VARCHAR(12) DEFAULT NULL, + `location` TEXT DEFAULT NULL, + `data` TEXT DEFAULT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE `quests_active` ( + `player_name` VARCHAR(25) NOT NULL, + `quest_id` VARCHAR(12) NOT NULL, + `progress` VARCHAR(50) DEFAULT NULL, + PRIMARY KEY (`player_name`,`quest_id`) +); + +CREATE TABLE `quests_completed` ( + `player_name` VARCHAR(25) NOT NULL, + `quest_id` VARCHAR(12) NOT NULL, + `date_completed` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + PRIMARY KEY (`player_name`,`quest_id`) +); + +-- v0.2 update + +ALTER TABLE `craftizens` ADD COLUMN `item_in_hand` INT DEFAULT 0 NOT NULL; + +-- v0.5 update + +ALTER TABLE `quests` ADD COLUMN `completion_text` TEXT DEFAULT NULL; + +CREATE TABLE `craftizens_dialog` ( + `npc_id` VARCHAR(12) NOT NULL, + `dialog_id` VARCHAR(12) NOT NULL, + `dialog_text` TEXT NOT NULL, + PRIMARY KEY (`npc_id`,`dialog_id`) +); + +-- v0.6 update + +ALTER TABLE `craftizens` ADD COLUMN `route_type` VARCHAR(8) DEFAULT NULL; +ALTER TABLE `craftizens` ADD COLUMN `route` TEXT DEFAULT NULL; + +-- v0.7 update +ALTER TABLE `quests` ADD COLUMN `rankreq` VARCHAR(12) DEFAULT NULL; +ALTER TABLE `quests` ADD COLUMN `rankreward` VARCHAR(12) DEFAULT NULL; + +-- v0.7.1 update +ALTER TABLE `quests` ADD COLUMN `cost` VARCHAR(12) DEFAULT '0'; +ALTER TABLE `quests` ADD COLUMN `prize` VARCHAR(12) DEFAULT '0'; diff --git a/dist/Craftizens.jar b/dist/Craftizens.jar new file mode 100644 index 0000000..a7f2ad6 Binary files /dev/null and b/dist/Craftizens.jar differ diff --git a/BuildQuest.java b/src/BuildQuest.java similarity index 100% rename from BuildQuest.java rename to src/BuildQuest.java diff --git a/Craftizen.java b/src/Craftizen.java similarity index 98% rename from Craftizen.java rename to src/Craftizen.java index 199fc8a..e75fe63 100644 --- a/Craftizen.java +++ b/src/Craftizen.java @@ -1,5 +1,3 @@ -import net.minecraft.server.MinecraftServer; -import java.util.List; import java.util.ArrayList; import java.util.logging.*; import java.util.Random; @@ -154,7 +152,14 @@ public String getId() { public String getName() { return name; } - + + /** + * @return the speed + */ + public double getSpeed() { + return speed; + } + public enum RouteType { NONE, WANDER, PATROL } diff --git a/CraftizenDataSource.java b/src/CraftizenDataSource.java similarity index 100% rename from CraftizenDataSource.java rename to src/CraftizenDataSource.java diff --git a/src/CraftizenFlatfileDataSource.java b/src/CraftizenFlatfileDataSource.java new file mode 100644 index 0000000..ae12242 --- /dev/null +++ b/src/CraftizenFlatfileDataSource.java @@ -0,0 +1,406 @@ +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.logging.Logger; + + +public class CraftizenFlatfileDataSource extends CraftizenDataSource +{ + static final Logger log = Logger.getLogger("Minecraft"); + + private static final String DATA_FOLDER = "craftizens/"; + + private HashMap> npcQuests; + + public CraftizenFlatfileDataSource() + { + (new File(DATA_FOLDER)).mkdir(); + } + + public HashSet loadCraftizens() + { + synchronized (craftizenLock) + { + HashSet npcs = new HashSet(); + npcQuests = new HashMap>(); + + // get file list + File[] files = (new File(DATA_FOLDER)).listFiles(); + + // load npc data + for (File file : files) + { + if (file.getName().startsWith("npc-")) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + + file.getName()); + Craftizen npc = new Craftizen(data.getString("npc_id"), + data.getString("npc_name"), data.getDouble("posx"), + data.getDouble("posy"), data.getDouble("posz"), + (float) data.getDouble("rotation"), + (float) data.getDouble("pitch"), + data.getInt("item_in_hand")); + + int i = 0; + ArrayList dialog = new ArrayList(); + while (data.containsKey("dialog_" + i)) + { + dialog.add(data.getString("dialog_" + i)); + i++; + } + npc.setDialog(dialog); + npcs.add(npc); + npcQuests.put(npc.getId(), new ArrayList()); + } + } + + // load quest data + for (File file : files) + { + if (file.getName().startsWith("quest-")) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + + file.getName()); + ArrayList quests = npcQuests.get(data + .getString("start_npc")); + if (quests != null) { + quests.add(data.getString("id")); + npcQuests.put(data.getString("start_npc"), quests); + } else { + Craftizens.log.warning("[Craftizens] " + file.getName() + + " has a non-existant start_npc: " + + data.getString("start_npc") + ". Quest not loaded."); + } + } + } + return npcs; + } + } + + public void saveCraftizen(Craftizen c) + { + synchronized (craftizenLock) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + "npc-" + + c.getId() + ".txt"); + data.setString("npc_id", c.getId()); + data.setString("npc_name", c.getName()); + data.setDouble("posx", c.getX()); + data.setDouble("posy", c.getY()); + data.setDouble("posz", c.getZ()); + data.setDouble("rotation", c.getRotation()); + data.setDouble("pitch", c.getPitch()); + data.setInt("item_in_hand", c.getItemInHand()); + } + } + + public void addCraftizenDialog(String npcid, String dialogid, String dialog) + { + synchronized (craftizenLock) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + "npc-" + + npcid + ".txt"); + int i = -1; + while (data.containsKey("dialog_" + ++i)) + { + } + data.setString("dialog_" + i, dialog); + } + } + + public void deleteCraftizen(String id) + { + synchronized (craftizenLock) + { + (new File(DATA_FOLDER + "npc-" + id + ".txt")).delete(); + } + } + + public ArrayList getQuestList() + { + synchronized (questLock) + { + ArrayList quests = null; + + // get file list + File[] files = (new File(DATA_FOLDER)).listFiles(); + + // load quest data + for (File file : files) + { + if (file.getName().startsWith("quest-")) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + + file.getName()); + if (quests == null) quests = new ArrayList(); + quests.add(data.getString("id")); + } + } + + return quests; + } + } + + public QuestInfo loadQuestInfo(String id) + { + synchronized (questLock) + { + if ((new File(DATA_FOLDER + "quest-" + id + ".txt")).exists()) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + "quest-" + + id + ".txt"); + QuestInfo quest = new QuestInfo(data.getString("id"), + data.getString("quest_type"), + data.getString("quest_name"), + data.getString("quest_desc"), + data.getString("start_npc"), data.getString("end_npc"), + data.getString("prereq"), + data.getString("items_provided"), + data.getString("rewards"), data.getString("location"), + data.getString("data"), + data.getString("completion_text"), + data.getString("rankreq"), + data.getString("rankreward"), data.getString("cost"), + data.getString("prize")); + return quest; + } + else + { + return null; + } + } + } + + public ArrayList getAvailableQuests(Craftizen c, Player p) + { + synchronized (questLock) + { + ArrayList quests = new ArrayList(); + // getting quests this NPC has + ArrayList questNames = npcQuests.get(c.id); + if (questNames != null) { + for (String q : npcQuests.get(c.id)) + { + // now we only add QuestInfo objects that the player can + // actually access + QuestInfo quest = loadQuestInfo(q); + + // logic for ranks + String[] groups = p.getGroups(); + if (groups.length > 0) + { + if (groups[0] == null || groups[0].equals("")) + { + if (!quest.rankReq.isEmpty()) + { + continue; + } + } + else + { + if ((!quest.rankReq.isEmpty()) + && (!quest.rankReq.equalsIgnoreCase(groups[0]))) + { + continue; + } + } + } + else + { + if (!quest.rankReq.isEmpty()) + { + continue; + } + } + + PropertiesFile player = loadPlayer(p); + // logic for active quests + String[] activeQuests = player.getString("active-quests") + .split(","); + boolean activeFound = false; + for (String aq : activeQuests) + { + if (aq.equalsIgnoreCase(q)) + { + activeFound = true; + break; + } + } + if (activeFound) + { + continue; + } + // logic for already completed quests + String[] completedQuests = player.getString("completed-quests") + .split(","); + boolean completedFound = false; + boolean prereqFound = false; + boolean hasPrereq = (quest.getPrereq() != null && !quest.getPrereq().isEmpty()); + for (String cq : completedQuests) + { + if (cq.equalsIgnoreCase(q)) + { + completedFound = true; + if (!hasPrereq || prereqFound) break; + } + if (hasPrereq && cq.equalsIgnoreCase(quest.getPrereq())) + { + prereqFound = true; + if (completedFound) break; + } + } + if (completedFound || (hasPrereq && !prereqFound)) + { + continue; + } + + // add the quest to the list + quests.add(quest); + } + } + return quests; + } + } + + private PropertiesFile loadPlayer(Player p) + { + return new PropertiesFile(DATA_FOLDER + "player-" + p.getName() + + ".txt"); + } + + public HashMap getActiveQuests(Player p) + { + synchronized (questLock) + { + HashMap quests = new HashMap(); + + PropertiesFile player = loadPlayer(p); + String[] q = player.getString("active-quests").split(","); + for (String aq : q) + { + QuestInfo quest = loadQuestInfo(aq); + if (quest == null) + { + continue; + } + String progress = player.getString("progress-" + aq); + quests.put(quest, progress); + } + return quests; + } + } + + public void saveActiveQuest(Player player, Quest quest) + { + synchronized (questLock) + { + PropertiesFile p = loadPlayer(player); + if (p.getString("active-quests").isEmpty()) + { + p.setString("active-quests", quest.getId()); + } + else + { + p.setString("active-quests", p.getString("active-quests") + "," + + quest.getId()); + } + } + } + + public void saveQuestProgress(Player player, Quest quest, String progress) + { + synchronized (questLock) + { + PropertiesFile p = loadPlayer(player); + p.setString("progress-" + quest.getId(), progress); + } + } + + public void dropActiveQuest(Player player, Quest quest) + { + synchronized (questLock) + { + PropertiesFile p = loadPlayer(player); + String[] q = p.getString("active-quests").split(","); + String activeQuests = ""; + for (String aq : q) + { + if (!quest.getId().equalsIgnoreCase(aq)) + { + if (activeQuests.isEmpty()) + { + activeQuests = aq; + } + else + { + activeQuests = activeQuests + "," + aq; + } + } + } + p.setString("active-quests", activeQuests); + } + } + + public void saveCompletedQuest(Player player, Quest quest) + { + dropActiveQuest(player, quest); + synchronized (questLock) + { + PropertiesFile p = loadPlayer(player); + if (p.getString("completed-quests").isEmpty()) + { + p.setString("completed-quests", quest.getId()); + } + else + { + p.setString("completed-quests", p.getString("completed-quests") + + "," + quest.getId()); + } + } + } + + public void saveQuest(QuestInfo quest) + { + synchronized (questLock) + { + PropertiesFile data = new PropertiesFile(DATA_FOLDER + "quest-" + + quest.getId() + ".txt"); + + data.setString("id", quest.id); + data.setString("quest_name", (quest.name == null) ? "" : quest.name); + data.setString("quest_type", (quest.type == null) ? "" : quest.type); + data.setString("quest_desc", (quest.desc == null) ? "" : quest.desc); + data.setString("start_npc", (quest.pickUp == null) ? "" + : quest.pickUp); + data.setString("end_npc", (quest.turnIn == null) ? "" + : quest.turnIn); + data.setString("prereq", (quest.prereq == null) ? "" : quest.prereq); + data.setString("items_provided", + (quest.itemsProvidedStr == null) ? "" + : quest.itemsProvidedStr); + data.setString("rewards", (quest.rewardsStr == null) ? "" + : quest.rewardsStr); + data.setString("location", (quest.location == null) ? "" + : quest.location); + data.setString("data", (quest.data == null) ? "" : quest.data); + data.setString("completion_text", + (quest.completionText == null) ? "" : quest.completionText); + data.setString("rankreq", (quest.rankReq == null) ? "" + : quest.rankReq); + data.setString("rankreward", (quest.rankReward == null) ? "" + : quest.rankReward); + data.setInt("cost", quest.cost); + data.setInt("prize", quest.prize); + } + } + + public void deleteQuest(String questid) + { + synchronized (questLock) + { + (new File(DATA_FOLDER + "quest-" + questid + ".txt")).delete(); + } + } + +} diff --git a/CraftizenSQLDataSource.java b/src/CraftizenSQLDataSource.java similarity index 76% rename from CraftizenSQLDataSource.java rename to src/CraftizenSQLDataSource.java index 9339d77..a580947 100644 --- a/CraftizenSQLDataSource.java +++ b/src/CraftizenSQLDataSource.java @@ -7,15 +7,32 @@ public class CraftizenSQLDataSource extends CraftizenDataSource { static final Logger log = Logger.getLogger("Minecraft"); - + + static public Connection getSQLConnection() throws SQLException + { + Connection connection = null; + if (Craftizens.DATA_SOURCE_DRIVER_NAME.isEmpty()) { + connection = etc.getSQLConnection(); + } else { + try { + Class.forName(Craftizens.DATA_SOURCE_DRIVER_NAME); + } catch (ClassNotFoundException ex) { + log.log(Level.SEVERE, null, ex); + return null; + } + connection = DriverManager.getConnection(Craftizens.DATA_SOURCE_CONNECTION_URL, Craftizens.DATA_SOURCE_USERNAME, Craftizens.DATA_SOURCE_PASSWORD); + } + return connection; + } + public void sample() { synchronized (dbLock) { Connection conn = null; PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); - query = conn.prepareStatement("select * from"); + conn = getSQLConnection(); + query = conn.prepareStatement("SELECT * FROM"); results = query.executeQuery(); while (results.next()) { } @@ -40,7 +57,7 @@ public HashSet loadCraftizens() { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("SELECT * FROM craftizens"); results = query.executeQuery(); while (results.next()) { @@ -90,7 +107,7 @@ public void saveCraftizen(Craftizen c) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); // check if npc exists already boolean exists = false; @@ -148,7 +165,7 @@ public void addCraftizenDialog(String npcid, String dialogid, String dialog) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("INSERT INTO craftizens_dialog (npc_id, dialog_id, dialog_text) VALUES (?,?,?)"); query.setString(1,npcid); query.setString(2,dialogid); @@ -173,7 +190,7 @@ public void deleteCraftizen(String id) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("DELETE FROM craftizens WHERE npc_id = ?"); query.setString(1,id); query.executeUpdate(); @@ -198,7 +215,7 @@ public ArrayList getQuestList() { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("SELECT id FROM quests ORDER BY id"); results = query.executeQuery(); while (results.next()) { @@ -229,25 +246,29 @@ public QuestInfo loadQuestInfo(String id) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("SELECT * FROM quests WHERE id = ?"); query.setString(1,id); results = query.executeQuery(); if (results.next()) { quest = new QuestInfo( - results.getString("id"), - results.getString("quest_type"), - results.getString("quest_name"), - results.getString("quest_desc"), - results.getString("start_npc"), - results.getString("end_npc"), - results.getString("prereq"), - results.getString("items_provided"), - results.getString("rewards"), - results.getString("location"), - results.getString("data"), - results.getString("completion_text") - ); + results.getString("id"), + results.getString("quest_type"), + results.getString("quest_name"), + results.getString("quest_desc"), + results.getString("start_npc"), + results.getString("end_npc"), + results.getString("prereq"), + results.getString("items_provided"), + results.getString("rewards"), + results.getString("location"), + results.getString("data"), + results.getString("completion_text"), + results.getString("rankreq"), + results.getString("rankreward"), + results.getString("cost"), + results.getString("prize") + ); } } catch (SQLException e) { log.log(Level.SEVERE,"DB Error loading quest info "+id,e); @@ -272,21 +293,34 @@ public ArrayList getAvailableQuests(Craftizen c, Player p) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement( "SELECT q.* " + - "FROM craftizens c " + - "JOIN quests q ON q.start_npc = c.npc_id " + - "LEFT JOIN quests_completed qc ON qc.player_name = ? AND qc.quest_id = q.prereq " + - "LEFT JOIN quests_completed qc2 ON qc2.player_name = ? AND qc2.quest_id = q.id " + - "LEFT JOIN quests_active qa ON qa.player_name = ? AND qa.quest_id = q.id " + + "FROM craftizens AS c " + + "JOIN quests AS q ON q.start_npc = c.npc_id " + + "LEFT JOIN quests_completed AS qc ON qc.player_name = ? AND qc.quest_id = q.prereq " + + "LEFT JOIN quests_completed AS qc2 ON qc2.player_name = ? AND qc2.quest_id = q.id " + + "LEFT JOIN quests_active AS qa ON qa.player_name = ? AND qa.quest_id = q.id " + "WHERE c.npc_id = ? AND (q.prereq IS NULL OR qc.date_completed IS NOT NULL) " + - "AND qc2.quest_id IS NULL and qa.quest_id IS NULL " + "AND qc2.quest_id IS NULL and qa.quest_id IS NULL " + + "AND (q.rankreq IS NULL OR q.rankreq = ?) " ); query.setString(1, p.getName().toLowerCase()); query.setString(2, p.getName().toLowerCase()); query.setString(3, p.getName().toLowerCase()); query.setString(4, c.getId()); + + String[] groups = p.getGroups(); + if (groups.length > 0) { + if(groups[0] == null || groups[0].equals("")) { + query.setString(5, ""); + } else { + query.setString(5, groups[0]); + } + } else { + query.setString(5, ""); + } + results = query.executeQuery(); while (results.next()) { QuestInfo q = new QuestInfo( @@ -301,7 +335,11 @@ public ArrayList getAvailableQuests(Craftizen c, Player p) { results.getString("rewards"), results.getString("location"), results.getString("data"), - results.getString("completion_text") + results.getString("completion_text"), + results.getString("rankreq"), + results.getString("rankreward"), + results.getString("cost"), + results.getString("prize") ); quests.add(q); } @@ -328,30 +366,34 @@ public HashMap getActiveQuests(Player p) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement( "SELECT q.*, qa.progress " + - "FROM quests_active qa " + - "JOIN quests q ON q.id = qa.quest_id " + + "FROM quests_active AS qa " + + "JOIN quests AS q ON q.id = qa.quest_id " + "WHERE qa.player_name = ? " ); query.setString(1, p.getName().toLowerCase()); results = query.executeQuery(); while (results.next()) { QuestInfo q = new QuestInfo( - results.getString("id"), - results.getString("quest_type"), - results.getString("quest_name"), - results.getString("quest_desc"), - results.getString("start_npc"), - results.getString("end_npc"), - results.getString("prereq"), - results.getString("items_provided"), - results.getString("rewards"), - results.getString("location"), - results.getString("data"), - results.getString("completion_text") - ); + results.getString("id"), + results.getString("quest_type"), + results.getString("quest_name"), + results.getString("quest_desc"), + results.getString("start_npc"), + results.getString("end_npc"), + results.getString("prereq"), + results.getString("items_provided"), + results.getString("rewards"), + results.getString("location"), + results.getString("data"), + results.getString("completion_text"), + results.getString("rankreq"), + results.getString("rankreward"), + results.getString("cost"), + results.getString("prize") + ); String s = results.getString("progress"); quests.put(q,s); } @@ -376,7 +418,7 @@ public void saveActiveQuest(Player player, Quest quest) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("INSERT INTO quests_active (player_name, quest_id) VALUES (?,?)"); query.setString(1, player.getName().toLowerCase()); query.setString(2, quest.getId()); @@ -400,7 +442,7 @@ public void saveQuestProgress(Player player, Quest quest, String progress) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("UPDATE quests_active SET progress = ? WHERE player_name = ? AND quest_id = ?"); query.setString(1, progress); query.setString(2, player.getName().toLowerCase()); @@ -425,7 +467,7 @@ public void dropActiveQuest(Player player, Quest quest) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("DELETE FROM quests_active where player_name = ? AND quest_id = ?"); query.setString(1, player.getName().toLowerCase()); query.setString(2, quest.getId()); @@ -449,7 +491,7 @@ public void saveCompletedQuest(Player player, Quest quest) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("DELETE FROM quests_active WHERE player_name = ? AND quest_id = ?"); query.setString(1, player.getName().toLowerCase()); query.setString(2, quest.getId()); @@ -480,7 +522,7 @@ public void saveQuest(QuestInfo quest) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); boolean exists = false; query = conn.prepareStatement("SELECT * FROM quests WHERE id = ?"); @@ -497,7 +539,9 @@ public void saveQuest(QuestInfo quest) { "quest_name = ?, quest_type = ?, quest_desc = ?, " + "start_npc = ?, end_npc = ?, prereq = ?, " + "items_provided = ?, rewards = ?, " + - "location = ?, data = ?, completion_text = ? " + + "location = ?, data = ?, completion_text = ?, " + + "rankreq = ?, rankreward = ?, " + + "cost = ?, prize = ? " + "WHERE id = ?"); query.setString(1,quest.name); query.setString(2,quest.type); @@ -510,10 +554,14 @@ public void saveQuest(QuestInfo quest) { query.setString(9,quest.location); query.setString(10,quest.data); query.setString(11,quest.completionText); - query.setString(12,quest.id); + query.setString(12,quest.rankReq); + query.setString(13,quest.rankReward); + query.setString(14,(new Integer(quest.cost)).toString()); + query.setString(15,(new Integer(quest.prize)).toString()); + query.setString(16,quest.id); query.executeUpdate(); } else { - query = conn.prepareStatement("INSERT INTO quests (id, quest_name, quest_type, quest_desc, start_npc, end_npc, prereq, items_provided, rewards, location, data, completion_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + query = conn.prepareStatement("INSERT INTO quests (id, quest_name, quest_type, quest_desc, start_npc, end_npc, prereq, items_provided, rewards, location, data, completion_text, rankreq, rankreward, cost, prize) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); query.setString(1,quest.id); query.setString(2,quest.name); query.setString(3,quest.type); @@ -526,6 +574,10 @@ public void saveQuest(QuestInfo quest) { query.setString(10,quest.location); query.setString(11,quest.data); query.setString(12,quest.completionText); + query.setString(13,quest.rankReq); + query.setString(14,quest.rankReward); + query.setString(15,(new Integer(quest.cost)).toString()); + query.setString(16,(new Integer(quest.prize)).toString()); query.executeUpdate(); } } catch (SQLException e) { @@ -548,7 +600,7 @@ public void deleteQuest(String questid) { PreparedStatement query = null; ResultSet results = null; try { - conn = etc.getSQLConnection(); + conn = getSQLConnection(); query = conn.prepareStatement("DELETE FROM quests_active WHERE quest_id = ?"); query.setString(1, questid); query.executeUpdate(); @@ -577,6 +629,4 @@ public void deleteQuest(String questid) { } } - - } diff --git a/CraftizenTicker.java b/src/CraftizenTicker.java similarity index 100% rename from CraftizenTicker.java rename to src/CraftizenTicker.java diff --git a/src/Craftizens.java b/src/Craftizens.java new file mode 100644 index 0000000..1a8e110 --- /dev/null +++ b/src/Craftizens.java @@ -0,0 +1,157 @@ +import java.util.HashSet; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.logging.*; + +public class Craftizens extends Plugin { + static final Logger log = Logger.getLogger("Minecraft"); + + public static boolean DEBUG = false; + public static String NPC_PREFIX = "\u00C2\u00A7e"; + public static String NPC_SUFFIX = " (NPC)"; + public static String TEXT_COLOR = "\u00C2\u00A7e"; + public static int INTERACT_ITEM = 340; + public static int INTERACT_ITEM_2 = 340; + public static int INTERACT_RANGE = 2; + public static int INTERACT_ANGLE_VARIATION = 25; + public static boolean INTERACT_ANYTHING = false; + public static int QADMIN_BOUNDARY_MARKER = 340; + public static boolean QUESTS_ENABLED = true; + public static boolean FLATFILE_DATA = false; + public static String DATA_SOURCE_DRIVER_NAME = ""; + public static String DATA_SOURCE_CONNECTION_URL = ""; + public static String DATA_SOURCE_USERNAME = ""; + public static String DATA_SOURCE_PASSWORD = ""; + public static boolean REPLACE_GROUP = true; + public static boolean ICONOMY_DETECTED = false; + public static boolean ALLOW_COMPASS = true; + public static String NAME = "Craftizens"; + public static String VERSION = "v0.8.2"; + + public static CraftizenDataSource data; + public static HashSet npcs; + public static HashMap pendingQuests; + public static HashMap> activeQuests; + public static HashMap newQuests; + + private static CraftizenTicker ticker; + private static CraftizensListener listener; + + public void initialize() { + listener = new CraftizensListener(); + etc.getLoader().addListener(PluginLoader.Hook.COMMAND, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.ARM_SWING, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.BLOCK_DESTROYED, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.BLOCK_CREATED, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.PLAYER_MOVE, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.LOGIN, listener, this, PluginListener.Priority.MEDIUM); + etc.getLoader().addListener(PluginLoader.Hook.DISCONNECT, listener, this, PluginListener.Priority.MEDIUM); + } + + public void enable() { + etc.getInstance().addCommand("/craftnpc", "Create an npc"); + etc.getInstance().addCommand("/quest", "Command for working with your quests"); + etc.getInstance().addCommand("/qadmin", "Create, modify, delete, control the quests on your server"); + + // load properties + PropertiesFile props = new PropertiesFile("craftizens.properties"); + DEBUG = props.getBoolean("debug-mode", DEBUG); + NPC_PREFIX = props.getString("npc-name-prefix", NPC_PREFIX); + NPC_SUFFIX = props.getString("npc-name-suffix", NPC_SUFFIX); + TEXT_COLOR = props.getString("quest-text-color", TEXT_COLOR); + INTERACT_ITEM = props.getInt("npc-interact-item", INTERACT_ITEM); + INTERACT_ITEM_2 = props.getInt("npc-interact-item-2", INTERACT_ITEM_2); + INTERACT_RANGE = props.getInt("npc-interact-range", INTERACT_RANGE); + INTERACT_ANGLE_VARIATION = props.getInt("npc-interact-angle-variation", INTERACT_ANGLE_VARIATION); + INTERACT_ANYTHING = props.getBoolean("interact-anything", INTERACT_ANYTHING); + QADMIN_BOUNDARY_MARKER = props.getInt("qadmin-boundary-marker", QADMIN_BOUNDARY_MARKER); + QUESTS_ENABLED = props.getBoolean("quests-enabled", QUESTS_ENABLED); + FLATFILE_DATA = props.getBoolean("flatfile-data-enabled", FLATFILE_DATA); + DATA_SOURCE_DRIVER_NAME = props.getString("data-source-driver-name", DATA_SOURCE_DRIVER_NAME); + DATA_SOURCE_CONNECTION_URL = props.getString("data-source-connection-url", DATA_SOURCE_CONNECTION_URL); + DATA_SOURCE_USERNAME = props.getString("data-source-username", DATA_SOURCE_USERNAME); + DATA_SOURCE_PASSWORD = props.getString("data-source-password", DATA_SOURCE_PASSWORD); + REPLACE_GROUP = props.getBoolean("replace-group", REPLACE_GROUP); + ALLOW_COMPASS = props.getBoolean("allow-compass", ALLOW_COMPASS); + + if (FLATFILE_DATA) + data = new CraftizenFlatfileDataSource(); + else + data = new CraftizenSQLDataSource(); + + loadiConomy(); + + Craftizen.getPlayerList(); + npcs = data.loadCraftizens(); + + ticker = new CraftizenTicker(2000); + Thread t = new Thread(ticker); + t.start(); + + // load quests + pendingQuests = new HashMap(); + activeQuests = new HashMap>(); + for (Player p : etc.getServer().getPlayerList()) { + CraftizensListener.loadActiveQuests(p); + } + + log.info("[" + NAME + "] Plugin " + VERSION + " loaded successfully!"); + } + + public void disable() { + etc.getInstance().removeCommand("/craftnpc"); + etc.getInstance().removeCommand("/quest"); + etc.getInstance().removeCommand("/qadmin"); + + ticker.stop(); + ticker = null; + + for (Craftizen npc : npcs) { + npc.delete(); + } + npcs = null; + + // save quest progress + for (String s : activeQuests.keySet()) { + for (Quest q : activeQuests.get(s)) { + if (q != null) { + q.saveProgress(); + } + } + } + + pendingQuests = null; + activeQuests = null; + newQuests = null; + + data = null; + } + + public static boolean loadiConomy() { + if (etc.getLoader().getPlugin("iConomy") != null && etc.getLoader().getPlugin("iConomy").isEnabled()) { + PropertiesFile iConomySettings = new PropertiesFile(iData.mainDir + "settings.properties"); + if (!iConomySettings.containsKey("use-mysql")) { + log.warning("[" + NAME + "] iConomy settings failed to be read."); + ICONOMY_DETECTED = false; + return false; + } + boolean mysql = iConomySettings.getBoolean("use-mysql", false); + + // MySQL + String driver = iConomySettings.getString("driver", "com.mysql.jdbc.Driver"); + String user = iConomySettings.getString("user", "root"); + String pass = iConomySettings.getString("pass", "root"); + String db = iConomySettings.getString("db", "jdbc:mysql://localhost:3306/minecraft"); + + // Data + iData.setup(mysql, 0, driver, user, pass, db); + log.info("[" + NAME + "] iConomy loaded successfully."); + ICONOMY_DETECTED = true; + return true; + } else { + log.warning("[" + NAME + "] iConomy failed to load."); + ICONOMY_DETECTED = false; + return false; + } + } +} diff --git a/CraftizensListener.java b/src/CraftizensListener.java similarity index 77% rename from CraftizensListener.java rename to src/CraftizensListener.java index 2b36fad..b811121 100644 --- a/CraftizensListener.java +++ b/src/CraftizensListener.java @@ -1,4 +1,3 @@ -import net.minecraft.server.MinecraftServer; import java.util.logging.*; import java.util.ArrayList; import java.util.HashMap; @@ -7,7 +6,7 @@ public class CraftizensListener extends PluginListener { static final Logger log = Logger.getLogger("Minecraft"); public boolean onCommand(Player player, String [] split) { - if (split[0].equals("/npc") && player.canUseCommand("/npc")) { + if (split[0].equals("/craftnpc") && player.canUseCommand("/craftnpc")) { npcCommand(player, split); return true; } else if ((split[0].equalsIgnoreCase("/quest") || split[0].equalsIgnoreCase("/q")) && player.canUseCommand("/quest")) { @@ -20,14 +19,20 @@ public boolean onCommand(Player player, String [] split) { return false; } - public void npcCommand(Player player, String [] command) { - MinecraftServer s = etc.getServer().getMCServer(); - if (command[1].equals("clear")) { + public void npcCommand(Player player, String [] command) { + if (command.length > 1 && command[1].equals("clear")) { for (Craftizen npc : Craftizens.npcs) { npc.delete(); } Craftizens.npcs.clear(); - } else if (command[1].equals("create") && command.length > 3) { + } else if (command.length > 1 && command[1].equals("list")) { + for (Craftizen npc : Craftizens.npcs) { + player.sendMessage(Craftizens.TEXT_COLOR + npc.getId() + " - " + npc.getName() + " - " + + ((int) Math.floor(npc.getX())) + "," + + ((int) Math.floor(npc.getY())) + "," + + ((int) Math.floor(npc.getZ())) + ","); + } + } else if (command.length > 3 && command[1].equals("create")) { String id = command[2]; String n = ""; for (int i = 3; i < command.length; i++) { @@ -40,7 +45,7 @@ public void npcCommand(Player player, String [] command) { player.sendMessage("NPC '" + id + "' created."); - } else if (command[1].equals("adddialog") && command.length > 4) { + } else if (command.length > 4 && command[1].equals("adddialog")) { String npcid = command[2]; String dialogid = command[3]; String dialog = ""; @@ -57,25 +62,38 @@ public void npcCommand(Player player, String [] command) { player.sendMessage("No such npc"); } - } else if (command[1].equals("delete") && command.length == 3) { + } else if (command.length == 3 && command[1].equals("delete")) { Craftizen.delete(command[2]); Craftizens.data.deleteCraftizen(command[2]); player.sendMessage("NPC '" + command[2] + "' deleted."); + } else { + player.sendMessage(Craftizens.TEXT_COLOR + "Usage instructions:"); + player.sendMessage(Craftizens.TEXT_COLOR + " /craftnpc list - list your npcs"); + player.sendMessage(Craftizens.TEXT_COLOR + " /craftnpc create - create a new npc"); + player.sendMessage(Craftizens.TEXT_COLOR + " /craftnpc adddialog - add some dialog for your npc"); + player.sendMessage(Craftizens.TEXT_COLOR + " /craftnpc delete - delete your npc"); } } + @SuppressWarnings("unchecked") public void questCommand(Player player, String [] command) { if (command.length == 1) { questCommandUsage(player); } else if ("view".startsWith(command[1].toLowerCase()) && command.length == 3) { if (Craftizens.pendingQuests.containsKey(player.getName())) { Object o = Craftizens.pendingQuests.get(player.getName()); - if (o instanceof ArrayList) { - ArrayList quests = (ArrayList)o; + if (o instanceof ArrayList) { + ArrayList quests = null; + try { +// TODO: this is extremely poor programming practice. Need to refactor/fix later. + quests = (ArrayList) o; + } catch (ClassCastException e) { + Craftizen.log.warning("[Craftizens] Pending quests was not an ArrayList!"); + } int i = -1; try { i = Integer.parseInt(command[2]); @@ -100,14 +118,18 @@ public void questCommand(Player player, String [] command) { Object o = Craftizens.pendingQuests.get(player.getName()); if (o instanceof QuestInfo) { QuestInfo qi = (QuestInfo)o; - Quest q = qi.createQuest(player, true); - Craftizens.pendingQuests.remove(player.getName()); - if (!Craftizens.activeQuests.containsKey(player.getName())) { - Craftizens.activeQuests.put(player.getName(),new ArrayList()); + if (qi.checkBalance(player, true)) { + Quest q = qi.createQuest(player, true); + Craftizens.pendingQuests.remove(player.getName()); + if (!Craftizens.activeQuests.containsKey(player.getName())) { + Craftizens.activeQuests.put(player.getName(),new ArrayList()); + } + Craftizens.activeQuests.get(player.getName()).add(q); + Craftizens.data.saveActiveQuest(player, q); + player.sendMessage(Craftizens.TEXT_COLOR + "Quest accepted!"); + } else { + player.sendMessage(Craftizens.TEXT_COLOR + "You can't afford this quest! It costs " + qi.cost + "."); } - Craftizens.activeQuests.get(player.getName()).add(q); - Craftizens.data.saveActiveQuest(player, q); - player.sendMessage(Craftizens.TEXT_COLOR + "Quest accepted!"); } else { player.sendMessage(Craftizens.TEXT_COLOR + "No quest to accept."); } @@ -167,7 +189,7 @@ public void questCommand(Player player, String [] command) { player.sendMessage(Craftizens.TEXT_COLOR + "No active quests."); } - } else if ("compass".startsWith(command[1].toLowerCase()) && command.length == 3) { + } else if (Craftizens.ALLOW_COMPASS && "compass".startsWith(command[1].toLowerCase()) && command.length == 3) { if (Craftizens.activeQuests.containsKey(player.getName())) { ArrayList quests = Craftizens.activeQuests.get(player.getName()); int i = -1; @@ -213,7 +235,7 @@ public void questCommandUsage(Player player) { player.sendMessage(Craftizens.TEXT_COLOR + " /quest list - list your active quests"); player.sendMessage(Craftizens.TEXT_COLOR + " /quest progress # - shows progress on the quest"); player.sendMessage(Craftizens.TEXT_COLOR + " /quest desc # - shows the quest description"); - player.sendMessage(Craftizens.TEXT_COLOR + " /quest compass # - makes your compass point to the quest"); + if (Craftizens.ALLOW_COMPASS) player.sendMessage(Craftizens.TEXT_COLOR + " /quest compass # - makes your compass point to the quest"); } public void qadminCommand(Player player, String [] command) { @@ -251,8 +273,12 @@ public void qadminCommand(Player player, String [] command) { player.sendMessage("End NPC: " + q.turnIn); player.sendMessage("Prereq quest: " + q.prereq); player.sendMessage("Items prov: " + q.itemsProvidedStr); - player.sendMessage("Rewards: " + q.rewardsStr); - player.sendMessage("Comp text: " + ((q.completionText.length()>50)?q.completionText.substring(0,50)+"...":q.completionText)); + player.sendMessage("Rewards: " + (q.rewardsStr == null ? "None" : q.rewardsStr)); + player.sendMessage("Rank requirement: " + q.rankReq); + player.sendMessage("Rank reward: " + q.rankReward); + player.sendMessage("Cost: " + q.cost + " (iConomy is currently " + (Craftizens.ICONOMY_DETECTED ? "enabled)" : "disabled)")); + player.sendMessage("Prize: " + q.prize + " (iConomy is currently " + (Craftizens.ICONOMY_DETECTED ? "enabled)" : "disabled)")); + player.sendMessage("Comp text: " + ((q.completionText != null && q.completionText.length()>50)?q.completionText.substring(0,50)+"...":q.completionText)); player.sendMessage("Data: " + q.data); q = null; } else { @@ -290,6 +316,19 @@ public void qadminCommand(Player player, String [] command) { player.sendMessage("No such quest."); } + // iConomy Hook + } else if (command.length >= 2 && command[1].equalsIgnoreCase("iConomy")) { + if (command.length > 2 && command[2].equals("-disable")) { + Craftizens.ICONOMY_DETECTED = false; + player.sendMessage("iConomy disabled. Use /qadmin iConomy to turn it back on."); + } else if (Craftizens.loadiConomy()) { + player.sendMessage("iConomy loaded successfully."); + player.sendMessage("use /qadmin iConomy -disable to turn it off."); + } else { + player.sendMessage("iConomy failed to load."); + player.sendMessage("Perhaps you don't have the plugin running?"); + } + } else if (command.length >= 2 && Craftizens.newQuests != null && Craftizens.newQuests.containsKey(player.getName())) { QuestInfo quest = Craftizens.newQuests.get(player.getName()); @@ -412,6 +451,78 @@ public void qadminCommand(Player player, String [] command) { player.sendMessage("Use /qadmin prereq -delete to remove the prereq quest."); } + // rankreq + } else if (command[1].equalsIgnoreCase("rankreq")) { + if (command.length == 3) { + if (command[2].equals("-delete")) { + quest.rankReq = null; + player.sendMessage("Quest rank requirement removed."); + } else if (quest.setRankReq(command[2])){ + player.sendMessage("Quest rank requirmenet set to " + command[2] + "."); + } else { + player.sendMessage("Invalid rank requirement."); + } + } else if (command.length == 2 && quest.rankReq != null) { + player.sendMessage("Quest " + quest.id + " rank requirement: " + quest.rankReq); + } else { + player.sendMessage("Use /qadmin rankreq [rankname] to set the rank requirement."); + player.sendMessage("Use /qadmin rankreq -delete to remove the rank requirement."); + } + + // rankreward + } else if (command[1].equalsIgnoreCase("rankreward")) { + if (command.length == 3) { + if (command[2].equals("-delete")) { + quest.rankReward = null; + player.sendMessage("Quest rank reward removed."); + } else if (quest.setRankReward(command[2])){ + player.sendMessage("Quest rank reward set to " + command[2] + "."); + } else { + player.sendMessage("Invalid rank reward."); + } + } else if (command.length == 2 && quest.rankReward != null) { + player.sendMessage("Quest " + quest.id + " rank reward: " + quest.rankReward); + } else { + player.sendMessage("Use /qadmin rankreward [rankname] to set the rank reward."); + player.sendMessage("Use /qadmin rankreward -delete to remove the rank reward."); + } + + // cost + } else if (command[1].equalsIgnoreCase("cost")) { + if (command.length == 3) { + if (command[2].equals("-delete")) { + quest.cost = 0; + player.sendMessage("Quest cost removed."); + } else if (quest.setCost(command[2])){ + player.sendMessage("Quest cost set to " + command[2] + "."); + } else { + player.sendMessage("Invalid cost."); + } + } else if (command.length == 2) { + player.sendMessage("Quest " + quest.id + " cost: " + quest.cost); + } else { + player.sendMessage("Use /qadmin cost [rankname] to set the quest cost."); + player.sendMessage("Use /qadmin cost -delete to remove the quest cost."); + } + + // prize + } else if (command[1].equalsIgnoreCase("prize")) { + if (command.length == 3) { + if (command[2].equals("-delete")) { + quest.prize = 0; + player.sendMessage("Quest prize removed."); + } else if (quest.setPrize(command[2])){ + player.sendMessage("Quest prize set to " + command[2] + "."); + } else { + player.sendMessage("Invalid prize."); + } + } else if (command.length == 2) { + player.sendMessage("Quest " + quest.id + " prize: " + quest.prize); + } else { + player.sendMessage("Use /qadmin prize [rankname] to set the quest prize."); + player.sendMessage("Use /qadmin prize -delete to remove the quest prize."); + } + // items provided } else if (command[1].equalsIgnoreCase("itemsprovided")) { if (command.length > 2) { @@ -559,7 +670,7 @@ public void qadminCommand(Player player, String [] command) { } public void onArmSwing(Player player) { - if (player.getItemInHand() == Craftizens.INTERACT_ITEM || player.getItemInHand() == Craftizens.INTERACT_ITEM_2) { + if (Craftizens.INTERACT_ANYTHING || player.getItemInHand() == Craftizens.INTERACT_ITEM || player.getItemInHand() == Craftizens.INTERACT_ITEM_2) { if (Craftizens.DEBUG) log.info("Player " + player.getName() + " trying to check quest"); for (Craftizen npc : Craftizens.npcs) { if (Craftizens.DEBUG) log.info("--checking npc " + npc.getName()); @@ -629,7 +740,7 @@ public static boolean lookingAt(Player player, double x, double y, double z) { if (x <= player.getX() && z <= player.getZ()) { angle = 180 - angle; } else if (x <= player.getX() && z >= player.getZ()) { - angle = angle; +// angle = angle; } else if (x >= player.getX() && z >= player.getZ()) { angle = 360 - angle; } else { diff --git a/FetchBlockQuest.java b/src/FetchBlockQuest.java similarity index 98% rename from FetchBlockQuest.java rename to src/FetchBlockQuest.java index 2b489a6..212a843 100644 --- a/FetchBlockQuest.java +++ b/src/FetchBlockQuest.java @@ -57,7 +57,7 @@ public void complete() { for (int i = 0; i < types.length; i++) { inv.removeItem(new Item(types[i], 1)); } - inv.updateInventory(); + inv.update(); super.complete(); } @@ -118,7 +118,7 @@ public void onPlayerMove(Player player, Location from, Location to) { } public void sendFakeBlockPacket(Player player, int x, int y, int z, int type) { - fm packet = new fm(); + gd packet = new gd(); packet.a = x; packet.b = y; packet.c = z; diff --git a/FindLocQuest.java b/src/FindLocQuest.java similarity index 100% rename from FindLocQuest.java rename to src/FindLocQuest.java diff --git a/GatherQuest.java b/src/GatherQuest.java similarity index 96% rename from GatherQuest.java rename to src/GatherQuest.java index 60ccae3..aae6f9d 100644 --- a/GatherQuest.java +++ b/src/GatherQuest.java @@ -36,7 +36,7 @@ public boolean isComplete() { public int countItems(int itemId) { Inventory inv = player.getInventory(); int amt = 0; - for (int i = 0; i < inv.getArray().length; i++) { + for (int i = 0; i < inv.getContents().length; i++) { Item item = inv.getItemFromSlot(i); if (item != null && item.getItemId() == itemId) { amt += item.getAmount(); @@ -50,7 +50,7 @@ public void complete() { for (int i = 0; i < types.size(); i++) { inv.removeItem(new Item(types.get(i), quantities[i])); } - inv.updateInventory(); + inv.update(); super.complete(); } diff --git a/HarvestQuest.java b/src/HarvestQuest.java similarity index 95% rename from HarvestQuest.java rename to src/HarvestQuest.java index a465574..26b6765 100644 --- a/HarvestQuest.java +++ b/src/HarvestQuest.java @@ -41,9 +41,9 @@ public boolean isComplete() { public void complete() { Inventory inv = player.getInventory(); for (int i = 0; i < types.size(); i++) { - inv.removeItem(new Item(types.get(i), quantities[i])); + inv.removeItem(types.get(i), quantities[i]); } - inv.updateInventory(); + inv.update(); super.complete(); } @@ -70,7 +70,7 @@ public String getProgress() { public int countItems(int itemId) { Inventory inv = player.getInventory(); int amt = 0; - for (int i = 0; i < inv.getArray().length; i++) { + for (int i = 0; i < inv.getContents().length; i++) { Item item = inv.getItemFromSlot(i); if (item != null && item.getItemId() == itemId) { amt += item.getAmount(); diff --git a/NonPlayerCharacter.java b/src/NonPlayerCharacter.java similarity index 70% rename from NonPlayerCharacter.java rename to src/NonPlayerCharacter.java index 008cb29..aa25550 100644 --- a/NonPlayerCharacter.java +++ b/src/NonPlayerCharacter.java @@ -4,30 +4,38 @@ public abstract class NonPlayerCharacter { public static List players; - private es user; - private gv handler; + // XXX: VARIABLE TYPE ON AN UPDATE + private fi user; + // XXX: VARIABLE TYPE ON AN UPDATE + private hr handler; public NonPlayerCharacter(String name, double x, double y, double z, float rotation, float pitch, int itemInHand) { if (players == null) getPlayerList(); MinecraftServer s = etc.getServer().getMCServer(); - - user = new es(s, s.e, name, new ju(s.e)); + + // XXX: VARIABLE TYPE ON AN UPDATE + user = new fi(s, s.e, name, new kw(s.e)); teleportTo(x,y,z,rotation,pitch); if (itemInHand > 0) { setItemInHand(itemInHand); + } else { + setItemInHand(0); } - handler = new gv(user, 512, 1 , true ); + // XXX: VARIABLE TYPE ON AN UPDATE + handler = new hr(user, 512, 1 , true ); } public void delete() { for (Object player : players) { - ((es)player).a.b(new dh(handler.a.g)); + // XXX: VARIABLE TYPE ON AN UPDATE + ((fi)player).a.b(new dv(handler.a.g)); } } public void untrack(Player player) { + // XXX: VARIABLE TYPE ON AN UPDATE if (handler.q.contains(player.getUser())) { handler.q.remove(player.getUser()); } @@ -42,11 +50,13 @@ public void broadcastMovement() { } public String getName() { - return user.at; + // XXX: VARIABLE TYPE ON AN UPDATE + return user.aw; } public void setName(String name) { - user.at = name; + // XXX: VARIABLE TYPE ON AN UPDATE + user.aw = name; } public double getX() { @@ -90,11 +100,14 @@ public void setPitch(float pitch) { } public int getItemInHand() { - return user.am.a[0].c; + // XXX: VARIABLE TYPE ON AN UPDATE + if (user.an.a[0] == null) return 0; + return user.an.a[0].c; } public void setItemInHand(int type) { - user.am.a[0] = new hm(type); + // XXX: VARIABLE TYPE ON AN UPDATE + user.an.a[0] = new il(type); } public void teleportTo(double x, double y, double z, float rotation, float pitch) { diff --git a/Quest.java b/src/Quest.java similarity index 66% rename from Quest.java rename to src/Quest.java index 9414a33..5b9eb36 100644 --- a/Quest.java +++ b/src/Quest.java @@ -42,6 +42,62 @@ protected void giveRewards() { player.giveItem(i, info.rewards.get(i)); } } + if (info.rankReward != null) { + setRank(player, info.rankReward); + } + + if (Craftizens.ICONOMY_DETECTED) { + if (info.prize > 0) { + int money = iData.getBalance(player.getName()); + iData.setBalance(player.getName(), money + info.prize); + + player.sendMessage("Awarding cash prize of " + info.prize + "."); + } + } + } + + private void setRank(Player p, String rank) { + etc.getInstance(); + + if (rank.isEmpty()) return; + + Group g = etc.getDataSource().getGroup(rank); + if (g != null) { + String[] groupList = null; + if (Craftizens.REPLACE_GROUP) { + groupList = new String[]{ g.Name }; + } else { + groupList = p.getGroups(); + if (groupList != null && groupList.length > 0) { + String[] fullList = new String[groupList.length + 1]; + fullList[0] = g.Name; + int i = 0; + for (String group : groupList) { + i++; + fullList[i] = group; + } + groupList = fullList; + } else { + groupList = new String[]{ g.Name }; + } + } + p.setGroups(groupList); + p.setIgnoreRestrictions(g.IgnoreRestrictions); + p.setAdmin(g.Administrator); + + int i = 0; + + if (!etc.getDataSource().doesPlayerExist(p.getName())) { + i = 1; + } + + if (i != 0) + etc.getDataSource().addPlayer(p); + else + etc.getDataSource().modifyPlayer(p); + } else { + p.sendMessage("Error setting rank. Please contact your local admin."); + } } protected void complete() { @@ -88,7 +144,8 @@ public boolean compass() { cx /= (6*area); cy /= (6*area); - player.getUser().a.b(new co((int)cx, (int)player.getY(), (int)cy)); + // XXX: VARIABLE TYPE ON AN UPDATE + player.getUser().a.b(new da((int)cx, (int)player.getY(), (int)cy)); return true; } else { diff --git a/QuestInfo.java b/src/QuestInfo.java similarity index 69% rename from QuestInfo.java rename to src/QuestInfo.java index 4e03be2..a62863a 100644 --- a/QuestInfo.java +++ b/src/QuestInfo.java @@ -11,10 +11,16 @@ public class QuestInfo { public String turnIn; public String prereq; + public String rankReq; + public String rankReward; + + public int cost = 0; + public int prize = 0; + public String itemsProvidedStr; - public HashMap itemsProvided; + public HashMap itemsProvided = new HashMap(); public String rewardsStr; - public HashMap rewards; + public HashMap rewards = new HashMap(); public String location; public String data; @@ -27,7 +33,7 @@ public QuestInfo(String id) { this.desc = ""; } - public QuestInfo(String id, String type, String name, String desc, String pickUp, String turnIn, String prereq, String itemsProvided, String rewards, String location, String data, String completionText) { + public QuestInfo(String id, String type, String name, String desc, String pickUp, String turnIn, String prereq, String itemsProvided, String rewards, String location, String data, String completionText, String rankReq, String rankReward, String cost, String prize) { // get normal data this.id = id; this.type = type; @@ -74,6 +80,39 @@ public QuestInfo(String id, String type, String name, String desc, String pickUp this.location = location; this.data = data; this.completionText = completionText; + this.rankReq = rankReq; + this.rankReward = rankReward; + + try { + this.cost = Integer.parseInt(cost); + } catch (NumberFormatException e) { + this.cost = 0; + } + + try { + this.prize = Integer.parseInt(prize); + } catch (NumberFormatException e) { + this.prize = 0; + } + } + + // this function uses hardcoded because iConomy is not a singleton + // so I can't get iConony.moneyName + public boolean checkBalance(Player player, boolean deduct) { + if (Craftizens.ICONOMY_DETECTED) { + int money = iData.getBalance(player.getName()); + if (money >= cost) { + if (deduct && cost > 0) { + iData.setBalance(player.getName(), money - cost); + player.sendMessage(Craftizens.TEXT_COLOR + "Taking cost of " + cost + "."); + } + return true; + } else { + return false; + } + } else { + return true; + } } public void show(Player player) { @@ -96,6 +135,18 @@ public void show(Player player) { if (!rewardsStr.equals("")) { player.sendMessage(Craftizens.TEXT_COLOR + " Reward: " + rewardsStr.split(":")[0]); } + if (rankReq != null && !rankReq.equals("")) { + player.sendMessage(Craftizens.TEXT_COLOR + " Rank Required: " + rankReq); + } + if (rankReward != null && !rankReward.equals("")) { + player.sendMessage(Craftizens.TEXT_COLOR + " Rank Reward: " + rankReward); + } + if (Craftizens.ICONOMY_DETECTED && cost > 0) { + player.sendMessage(Craftizens.TEXT_COLOR + " Cost: " + cost); + } + if (Craftizens.ICONOMY_DETECTED && prize > 0) { + player.sendMessage(Craftizens.TEXT_COLOR + " Prize: " + prize); + } player.sendMessage(Craftizens.TEXT_COLOR + "Type '/quest accept' to accept this quest."); } @@ -171,6 +222,67 @@ public boolean setPrereq(String q) { } } + /** + * @param rankReq the rankReq to set + */ + public boolean setRankReq(String rankReq) { + if (rankReq.matches("^[a-zA-Z0-9]+$")) { + this.rankReq = rankReq; + return true; + } else { + return false; + } + } + + /** + * @param rankReward the rankReward to set + */ + public boolean setRankReward(String rankReward) { + if (rankReward.matches("^[a-zA-Z0-9]+$")) { + etc.getInstance(); + Group g = etc.getDataSource().getGroup(rankReward); + if (g != null) { + this.rankReward = rankReward; + return true; + } + return false; + } else { + return false; + } + } + + /** + * @param cost the cost to set + */ + public boolean setCost(String cost) { + if (cost.matches("^[0-9]+$")) { + try { + this.cost = Integer.parseInt(cost); + return true; + } catch (NumberFormatException e) { + return false; + } + } else { + return false; + } + } + + /** + * @param prize the prize to set + */ + public boolean setPrize(String prize) { + if (prize.matches("^[0-9]+$")) { + try { + this.prize = Integer.parseInt(prize); + return true; + } catch (NumberFormatException e) { + return false; + } + } else { + return false; + } + } + public boolean setItemsProvided(String i) { if (i.matches("[a-zA-Z0-9\\- ]+:([0-9]+ [0-9]+,)*[0-9]+ [0-9]+")) { this.itemsProvidedStr = i; @@ -264,4 +376,8 @@ public String getLocation() { public String getData() { return data; } + + public String getPrereq() { + return prereq; + } } diff --git a/src/iData.java b/src/iData.java new file mode 100644 index 0000000..3da762b --- /dev/null +++ b/src/iData.java @@ -0,0 +1,211 @@ +import java.io.*; +import java.sql.*; +import java.util.Map; +import java.util.logging.Logger; + +public final class iData implements Serializable { + protected static final Logger log = Logger.getLogger("Minecraft"); + public static PropertiesFile accounts; + private static int startingBalance; + + // Serial + private static final long serialVersionUID = -5796481236376288855L; + + // Database + static boolean mysql = false; + static String driver = "com.mysql.jdbc.Driver"; + static String user = "root"; + static String pass = "root"; + static String db = "jdbc:mysql://localhost:3306/minecraft"; + + // Directories + static String mainDir = "iConomy/"; + static String logDir = "logs/"; + + public static void setup(boolean mysql, int balance, String driver, String user, String pass, String db) { + startingBalance = balance; + + // Database + iData.driver = driver; + iData.user = user; + iData.pass = pass; + iData.db = db; + + if (!mysql) { + accounts = new PropertiesFile(mainDir + "balances.properties"); + } else { + // MySQL + iData.mysql = true; + + try { + Class.forName(driver); + } catch (ClassNotFoundException ex) { + log.severe("[iConomy MySQL] Unable to find driver class " + driver); + } + } + } + + public static Connection MySQL() { + try { + return DriverManager.getConnection(db,user,pass); + } catch (SQLException ex) { + log.severe("[iConomy MySQL] Unable to retreive MySQL connection"); + } + + return null; + } + + public static int globalBalance() { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + int current = 0; + + if (mysql) { + try { + conn = MySQL(); + ps = conn.prepareStatement("SELECT balance FROM iBalances"); + rs = ps.executeQuery(); + + while(rs.next()) { + current += rs.getInt("balance"); + } + + return current; + } catch (SQLException ex) { + return 0; + } finally { + try { + if (ps != null) { ps.close(); } + if (rs != null) { rs.close(); } + if (conn != null) { conn.close(); } + } catch (SQLException ex) { } + } + } else { + Map balances; + + try { + balances = accounts.returnMap(); + } catch (Exception ex) { + log.info("[iConomy] Listing failed for accounts."); + return 0; + } + + for (Object key: balances.keySet()) { + int balance = Integer.parseInt((String)balances.get(key)); + current += balance; + } + + return current; + } + } + + public static boolean hasBalance(String playerName) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + boolean has = false; + + if (mysql) { + try { + conn = MySQL(); + ps = conn.prepareStatement("SELECT balance FROM iBalances WHERE player = ? LIMIT 1"); + ps.setString(1, playerName); + rs = ps.executeQuery(); + + has = (rs.next()) ? true : false; + } catch (SQLException ex) { + log.severe("[iConomy] Unable to grab the balance for [" + playerName + "] from database!"); + } finally { + try { + if (ps != null) { ps.close(); } + if (rs != null) { rs.close(); } + if (conn != null) { conn.close(); } + } catch (SQLException ex) { } + } + } else { + return (accounts.getInt(playerName) != 0) ? true : false; + } + + return has; + } + + public static int getBalance(String playerName) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + int balance = startingBalance; + + if (mysql) { + try { + conn = MySQL(); + ps = conn.prepareStatement("SELECT balance FROM iBalances WHERE player = ? LIMIT 1"); + ps.setString(1, playerName); + rs = ps.executeQuery(); + + if (rs.next()) { + balance = rs.getInt("balance"); + } else { + ps = conn.prepareStatement("INSERT INTO iBalances (player, balance) VALUES(?,?)"); + ps.setString(1, playerName); + ps.setInt(2, balance); + ps.executeUpdate(); + } + } catch (SQLException ex) { + log.severe("[iConomy] Unable to grab the balance for [" + playerName + "] from database!"); + } finally { + try { + if (ps != null) { ps.close(); } + if (rs != null) { rs.close(); } + if (conn != null) { conn.close(); } + } catch (SQLException ex) { } + } + } else { + // To work with plugins we must do this. + try { + accounts.load(); + } catch (IOException ex) { + log.severe("[iConomy] Unable to reload balances."); + } + + // Return the balance + return (hasBalance(playerName)) ? accounts.getInt(playerName) : accounts.getInt(playerName, startingBalance); + } + + return balance; + } + + public static void setBalance(String playerName, int balance) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + + if (mysql) { + try { + conn = MySQL(); + + if (hasBalance(playerName)) { + ps = conn.prepareStatement("UPDATE iBalances SET balance = ? WHERE player = ? LIMIT 1", Statement.RETURN_GENERATED_KEYS); + ps.setInt(1, balance); + ps.setString(2, playerName); + ps.executeUpdate(); + } else { + ps = conn.prepareStatement("INSERT INTO iBalances (player, balance) VALUES(?,?)"); + ps.setString(1, playerName); + ps.setInt(2, balance); + ps.executeUpdate(); + } + } catch (SQLException ex) { + log.severe("[iConomy] Unable to update or create the balance for [" + playerName + "] from database!"); + } finally { + try { + if (ps != null) { ps.close(); } + if (rs != null) { rs.close(); } + if (conn != null) { conn.close(); } + } catch (SQLException ex) { } + } + } else { + accounts.setInt(playerName, balance); + } + } +}