Player.java

  1. package com.jadventure.game.entities;

  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.io.Reader;
  8. import java.io.Writer;
  9. import java.nio.file.Files;
  10. import java.nio.file.Path;
  11. import java.nio.file.Paths;
  12. import java.nio.file.StandardCopyOption;
  13. import java.util.ArrayList;
  14. import java.util.HashMap;
  15. import java.util.Iterator;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.Map.Entry;
  19. import java.util.Random;
  20. import java.util.Set;

  21. import com.google.gson.Gson;
  22. import com.google.gson.JsonArray;
  23. import com.google.gson.JsonElement;
  24. import com.google.gson.JsonObject;
  25. import com.google.gson.JsonParser;
  26. import com.google.gson.JsonArray;
  27. import com.google.gson.JsonPrimitive;
  28. import com.google.gson.reflect.TypeToken;
  29. import com.jadventure.game.DeathException;
  30. import com.jadventure.game.GameBeans;
  31. import com.jadventure.game.QueueProvider;
  32. import com.jadventure.game.items.Item;
  33. import com.jadventure.game.items.ItemStack;
  34. import com.jadventure.game.items.Storage;
  35. import com.jadventure.game.menus.BattleMenu;
  36. import com.jadventure.game.monsters.Monster;
  37. import com.jadventure.game.navigation.Coordinate;
  38. import com.jadventure.game.navigation.ILocation;
  39. import com.jadventure.game.navigation.LocationType;
  40. import com.jadventure.game.repository.ItemRepository;
  41. import com.jadventure.game.repository.LocationRepository;

  42. /**
  43.  * This class deals with the player and all of its properties.
  44.  * Any method that changes a character or interacts with it should
  45.  * be placed within this class. If a method deals with entities in general or
  46.  * with variables not unique to the player, place it in the entity class.
  47.  */
  48. public class Player extends Entity {
  49.     // @Resource
  50.     protected static ItemRepository itemRepo = GameBeans.getItemRepository();
  51.     protected static LocationRepository locationRepo = GameBeans.getLocationRepository();
  52.     private ILocation location;
  53.     private int xp;
  54.     /** Player type */
  55.     private String type;
  56.     private static HashMap<String, Integer>characterLevels = new HashMap<String, Integer>();

  57.     public Player() {
  58.     }

  59.     protected static void setUpCharacterLevels() {
  60.         characterLevels.put("Sewer Rat", 5);
  61.         characterLevels.put("Recruit", 3);
  62.         characterLevels.put("Syndicate Member", 4);
  63.         characterLevels.put("Brotherhood Member", 4);
  64.     }

  65.     public HashMap<String, Integer> getCharacterLevels() {
  66.         return characterLevels;
  67.     }

  68.     public void setCharacterLevels(HashMap<String, Integer> newCharacterLevels) {
  69.         this.characterLevels = newCharacterLevels;
  70.     }

  71.     public String getCurrentCharacterType() {
  72.         return this.type;
  73.     }
  74.    
  75.     public void setCurrentCharacterType(String newCharacterType) {
  76.         this.type = newCharacterType;
  77.     }

  78.     public void setCharacterLevel(String characterType, int level) {
  79.         this.characterLevels.put(characterType, level);
  80.     }

  81.     public int getCharacterLevel(String characterType) {
  82.         int characterLevel = this.characterLevels.get(characterType);
  83.         return characterLevel;
  84.     }

  85.     protected static String getProfileFileName(String name) {
  86.         return "json/profiles/" + name + "/" + name + "_profile.json";
  87.     }

  88.     public static boolean profileExists(String name) {
  89.         File file = new File(getProfileFileName(name));
  90.         return file.exists();
  91.     }

  92.     public static Player load(String name) {
  93.         player = new Player();
  94.         JsonParser parser = new JsonParser();
  95.         String fileName = getProfileFileName(name);
  96.         try {
  97.             Reader reader = new FileReader(fileName);
  98.             JsonObject json = parser.parse(reader).getAsJsonObject();
  99.             player.setName(json.get("name").getAsString());
  100.             player.setHealthMax(json.get("healthMax").getAsInt());
  101.             player.setHealth(json.get("health").getAsInt());
  102.             player.setArmour(json.get("armour").getAsInt());
  103.             player.setDamage(json.get("damage").getAsInt());
  104.             player.setLevel(json.get("level").getAsInt());
  105.             player.setXP(json.get("xp").getAsInt());
  106.             player.setStrength(json.get("strength").getAsInt());
  107.             player.setIntelligence(json.get("intelligence").getAsInt());
  108.             player.setDexterity(json.get("dexterity").getAsInt());
  109.             player.setLuck(json.get("luck").getAsInt());
  110.             player.setStealth(json.get("stealth").getAsInt());
  111.             player.setCurrentCharacterType(json.get("type").getAsString());
  112.             HashMap<String, Integer> charLevels = new Gson().fromJson(json.get("types"), new TypeToken<HashMap<String, Integer>>(){}.getType());
  113.             player.setCharacterLevels(charLevels);
  114.             if (json.has("equipment")) {
  115.                 Map<String, EquipmentLocation> locations = new HashMap<>();
  116.                 locations.put("head", EquipmentLocation.HEAD);
  117.                 locations.put("chest", EquipmentLocation.CHEST);
  118.                 locations.put("leftArm", EquipmentLocation.LEFT_ARM);
  119.                 locations.put("leftHand", EquipmentLocation.LEFT_HAND);
  120.                 locations.put("rightArm", EquipmentLocation.RIGHT_ARM);
  121.                 locations.put("rightHand", EquipmentLocation.RIGHT_HAND);
  122.                 locations.put("bothHands", EquipmentLocation.BOTH_HANDS);
  123.                 locations.put("bothArms", EquipmentLocation.BOTH_ARMS);
  124.                 locations.put("legs", EquipmentLocation.LEGS);
  125.                 locations.put("feet", EquipmentLocation.FEET);
  126.                 HashMap<String, String> equipment = new Gson().fromJson(json.get("equipment"), new TypeToken<HashMap<String, String>>(){}.getType());
  127.                Map<EquipmentLocation, Item> equipmentMap = new HashMap<>();
  128.                for(Map.Entry<String, String> entry : equipment.entrySet()) {
  129.                    EquipmentLocation el = locations.get(entry.getKey());
  130.                    Item i = itemRepo.getItem(entry.getValue());
  131.                    equipmentMap.put(el, i);
  132.                }
  133.                player.setEquipment(equipmentMap);
  134.             }
  135.             if (json.has("items")) {
  136.                 HashMap<String, Integer> items = new Gson().fromJson(json.get("items"), new TypeToken<HashMap<String, Integer>>(){}.getType());
  137.                 ArrayList<ItemStack> itemList = new ArrayList<>();
  138.                 for (Map.Entry<String, Integer> entry : items.entrySet()) {
  139.                     String itemID = entry.getKey();
  140.                     int amount = entry.getValue();
  141.                     Item item = itemRepo.getItem(itemID);
  142.                     ItemStack itemStack = new ItemStack(amount, item);
  143.                     itemList.add(itemStack);
  144.                 }
  145.                 float maxWeight = (float)Math.sqrt(player.getStrength()*300);
  146.                 player.setStorage(new Storage(maxWeight, itemList));
  147.             }
  148.             Coordinate coordinate = new Coordinate(json.get("location").getAsString());
  149.             locationRepo = GameBeans.getLocationRepository(player.getName());
  150.             player.setLocation(locationRepo.getLocation(coordinate));
  151.             reader.close();
  152.             setUpCharacterLevels();
  153.         } catch (FileNotFoundException ex) {
  154.             QueueProvider.offer( "Unable to open file '" + fileName + "'.");
  155.         } catch (IOException ex) {
  156.             ex.printStackTrace();
  157.         }

  158.         return player;
  159.     }

  160.     // This is known as the singleton pattern. It allows for only 1 instance of a player.
  161.     private static Player player;
  162.    
  163.     public static Player getInstance(String playerClass){
  164.         player = new Player();
  165.         JsonParser parser = new JsonParser();
  166.         String fileName = "json/original_data/npcs.json";
  167.         try {
  168.             Reader reader = new FileReader(fileName);
  169.             JsonObject npcs = parser.parse(reader).getAsJsonObject().get("npcs").getAsJsonObject();
  170.             JsonObject json = new JsonObject();
  171.             for (Map.Entry<String, JsonElement> entry : npcs.entrySet()) {
  172.                 if (entry.getKey().equals(playerClass)) {
  173.                     json = entry.getValue().getAsJsonObject();
  174.                 }
  175.             }

  176.             player.setName(json.get("name").getAsString());
  177.             player.setHealthMax(json.get("healthMax").getAsInt());
  178.             player.setHealth(json.get("health").getAsInt());
  179.             player.setArmour(json.get("armour").getAsInt());
  180.             player.setDamage(json.get("damage").getAsInt());
  181.             player.setLevel(json.get("level").getAsInt());
  182.             player.setXP(json.get("xp").getAsInt());
  183.             player.setStrength(json.get("strength").getAsInt());
  184.             player.setIntelligence(json.get("intelligence").getAsInt());
  185.             player.setDexterity(json.get("dexterity").getAsInt());
  186.             setUpVariables(player);
  187.             JsonArray items = json.get("items").getAsJsonArray();
  188.             for (JsonElement item : items) {
  189.                 player.addItemToStorage(itemRepo.getItem(item.getAsString()));
  190.             }
  191.             Random rand = new Random();
  192.             int luck = rand.nextInt(3) + 1;
  193.             player.setLuck(luck);
  194.             player.setStealth(json.get("stealth").getAsInt());
  195.             player.setIntro(json.get("intro").getAsString());
  196.             if (player.getName().equals("Recruit")) {
  197.                 player.type = "Recruit";
  198.             } else if (player.getName().equals("Sewer Rat")) {
  199.                 player.type = "Sewer Rat";
  200.             } else {
  201.                 QueueProvider.offer("Not a valid class");
  202.             }
  203.             reader.close();
  204.             setUpCharacterLevels();
  205.         } catch (FileNotFoundException ex) {
  206.             QueueProvider.offer( "Unable to open file '" + fileName + "'.");
  207.         } catch (IOException ex) {
  208.             ex.printStackTrace();
  209.         }

  210.         return player;
  211.     }

  212.     public int getXP() {
  213.         return xp;
  214.     }

  215.     public void setXP(int xp) {
  216.         this.xp = xp;
  217.     }

  218.     public static void setUpVariables(Player player) {
  219.         float maxWeight = (float)Math.sqrt(player.getStrength()*300);
  220.         player.setStorage(new Storage(maxWeight));
  221.     }

  222.     public void getStats(){
  223.         Item weapon = itemRepo.getItem(getWeapon());
  224.         String weaponName = weapon.getName();
  225.         if (weaponName.equals(null)) {
  226.             weaponName = "hands";
  227.         }
  228.         String message = "\nPlayer name: " + getName();
  229.               message += "\nType: " + type;
  230.               message += "\nCurrent weapon: " + weaponName;
  231.               message += "\nGold: " + getGold();
  232.               message += "\nHealth/Max: " + getHealth() + "/" + getHealthMax();
  233.               message += "\nDamage/Armour: " + getDamage() + "/" + getArmour();
  234.               message += "\nStrength: " + getStrength();
  235.               message += "\nIntelligence: " + getIntelligence();
  236.               message += "\nDexterity: " + getDexterity();
  237.               message += "\nLuck: " + getLuck();
  238.               message += "\nStealth: " + getStealth();
  239.               message += "\nXP: " + getXP();
  240.               message += "\n" + getName() + "'s level: " + getLevel();
  241.         QueueProvider.offer(message);
  242.     }

  243.     public void printBackPack() {
  244.         storage.display();
  245.     }

  246.     public void save() {
  247.         Gson gson = new Gson();
  248.         JsonObject jsonObject = new JsonObject();
  249.         jsonObject.addProperty("name", getName());
  250.         jsonObject.addProperty("healthMax", getHealthMax());
  251.         jsonObject.addProperty("health", getHealthMax());
  252.         jsonObject.addProperty("armour", getArmour());
  253.         jsonObject.addProperty("damage", getDamage());
  254.         jsonObject.addProperty("level", getLevel());
  255.         jsonObject.addProperty("xp", getXP());
  256.         jsonObject.addProperty("strength", getStrength());
  257.         jsonObject.addProperty("intelligence", getIntelligence());
  258.         jsonObject.addProperty("dexterity", getDexterity());
  259.         jsonObject.addProperty("luck", getLuck());
  260.         jsonObject.addProperty("stealth", getStealth());
  261.         jsonObject.addProperty("weapon", getWeapon());
  262.         jsonObject.addProperty("type", getCurrentCharacterType());
  263.         HashMap<String, Integer> items = new HashMap<String, Integer>();
  264.         for (ItemStack item : getStorage().getItemStack()) {
  265.             items.put(item.getItem().getId(), item.getAmount());
  266.         }
  267.         JsonElement itemsJsonObj = gson.toJsonTree(items);
  268.         jsonObject.add("items", itemsJsonObj);
  269.         Map<EquipmentLocation, String> locations = new HashMap<>();
  270.         locations.put(EquipmentLocation.HEAD, "head");
  271.         locations.put(EquipmentLocation.CHEST, "chest");
  272.         locations.put(EquipmentLocation.LEFT_ARM, "leftArm");
  273.         locations.put(EquipmentLocation.LEFT_HAND, "leftHand");
  274.         locations.put(EquipmentLocation.RIGHT_ARM, "rightArm");
  275.         locations.put(EquipmentLocation.RIGHT_HAND, "rightHand");
  276.         locations.put(EquipmentLocation.BOTH_HANDS, "BothHands");
  277.         locations.put(EquipmentLocation.BOTH_ARMS, "bothArms");
  278.         locations.put(EquipmentLocation.LEGS, "legs");
  279.         locations.put(EquipmentLocation.FEET, "feet");
  280.         HashMap<String, String> equipment = new HashMap<>();
  281.         Item hands = itemRepo.getItem("hands");
  282.         for (Map.Entry<EquipmentLocation, Item> item : getEquipment().entrySet()) {
  283.             if (item.getKey() != null && !hands.equals(item.getValue()) && item.getValue() != null) {
  284.                 equipment.put(locations.get(item.getKey()), item.getValue().getId());
  285.             }
  286.         }
  287.         JsonElement equipmentJsonObj = gson.toJsonTree(equipment);
  288.         jsonObject.add("equipment", equipmentJsonObj);
  289.         JsonElement typesJsonObj = gson.toJsonTree(getCharacterLevels());
  290.         jsonObject.add("types", typesJsonObj);
  291.         Coordinate coordinate = getLocation().getCoordinate();
  292.         String coordinateLocation = coordinate.x+","+coordinate.y+","+coordinate.z;
  293.         jsonObject.addProperty("location", coordinateLocation);

  294.         String fileName = getProfileFileName(getName());
  295.         new File(fileName).getParentFile().mkdirs();
  296.         try {
  297.             Writer writer = new FileWriter(fileName);
  298.             gson.toJson(jsonObject, writer);
  299.             writer.close();
  300.             locationRepo = GameBeans.getLocationRepository(getName());
  301.             locationRepo.writeLocations();
  302.             QueueProvider.offer("\nYour game data was saved.");
  303.         } catch (IOException ex) {
  304.             QueueProvider.offer("\nUnable to save to file '" + fileName + "'.");
  305.         }
  306.     }

  307.     public List<Item> searchItem(String itemName, List<Item> itemList) {
  308.         List<Item> items = new ArrayList<>();
  309.         for (Item item : itemList) {
  310.             String testItemName = item.getName();
  311.             if (testItemName.equalsIgnoreCase(itemName)) {
  312.                 items.add(item);
  313.             }
  314.         }
  315.         return items;
  316.     }

  317.     public List<Item> searchItem(String itemName, Storage storage) {
  318.         return storage.search(itemName);
  319.     }
  320.    
  321.     public List<Item> searchEquipment(String itemName, Map<EquipmentLocation, Item> equipment) {
  322.         List<Item> items = new ArrayList<>();
  323.         for (Item item : equipment.values()) {
  324.             if (item != null && item.getName().equals(itemName)) {
  325.                 items.add(item);
  326.             }
  327.         }
  328.         return items;
  329.     }

  330.     public void pickUpItem(String itemName) {
  331.         List<Item> items = searchItem(itemName, getLocation().getItems());
  332.         if (! items.isEmpty()) {
  333.             Item item = items.get(0);
  334.             addItemToStorage(item);
  335.             location.removeItem(item);
  336.             QueueProvider.offer(item.getName()+ " picked up");
  337.         }
  338.     }

  339.     public void dropItem(String itemName) {
  340.         List<Item> itemMap = searchItem(itemName, getStorage());
  341.         if (itemMap.isEmpty()) {
  342.             itemMap = searchEquipment(itemName, getEquipment());
  343.         }
  344.         if (!itemMap.isEmpty()) {
  345.             Item item = itemMap.get(0);
  346.             Item itemToDrop = itemRepo.getItem(item.getId());
  347.             Item weapon = itemRepo.getItem(getWeapon());
  348.             String wName = weapon.getName();

  349.             if (itemName.equals(wName)) {
  350.                 dequipItem(wName);
  351.             }
  352.             removeItemFromStorage(itemToDrop);
  353.             location.addItem(itemToDrop);
  354.             QueueProvider.offer(item.getName() + " dropped");
  355.         }
  356.     }

  357.     public void equipItem(String itemName) {
  358.         List<Item> items = searchItem(itemName, getStorage());
  359.         if (!items.isEmpty()) {
  360.             Item item = items.get(0);
  361.             if (getLevel() >= item.getLevel()) {
  362.                 Map<String, String> change = equipItem(item.getPosition(), item);
  363.                 QueueProvider.offer(item.getName()+ " equipped");
  364.                 printStatChange(change);
  365.             } else {
  366.                 QueueProvider.offer("You do not have the required level to use this item");
  367.             }
  368.         } else {
  369.             QueueProvider.offer("You do not have that item");
  370.         }
  371.     }

  372.     public void dequipItem(String itemName) {
  373.          List<Item> items = searchEquipment(itemName, getEquipment());
  374.          if (!items.isEmpty()) {
  375.             Item item = items.get(0);
  376.             Map<String, String> change = unequipItem(item);
  377.             QueueProvider.offer(item.getName()+" unequipped");
  378.             printStatChange(change);
  379.          }
  380.     }

  381.     private void printStatChange(Map<String, String> stats) {
  382.          Set<Entry<String, String>> set = stats.entrySet();
  383.          Iterator<Entry<String, String>> iter = set.iterator();
  384.          while (iter.hasNext()) {
  385.               Entry<String, String> me = iter.next();
  386.               double value = Double.parseDouble((String) me.getValue());
  387.               switch ((String) me.getKey()) {
  388.                   case "damage": {
  389.                           if (value >= 0.0) {
  390.                               QueueProvider.offer(me.getKey() + ": " + this.getDamage() + " (+" + me.getValue() + ")");
  391.                           } else {
  392.                               QueueProvider.offer(me.getKey() + ": " + this.getDamage() + " (" + me.getValue() + ")");
  393.                           }
  394.                           break;
  395.                     }
  396.                     case "health": {
  397.                           if (value >= 0) {
  398.                               QueueProvider.offer(me.getKey() + ": " + this.getHealth() + " (+" + me.getValue() + ")");
  399.                           } else {
  400.                               QueueProvider.offer(me.getKey() + ": " + this.getHealth() + " (" + me.getValue() + ")");
  401.                           }
  402.                           break;
  403.                     }
  404.                     case "armour": {
  405.                           if (value >= 0) {
  406.                               QueueProvider.offer(me.getKey() + ": " + this.getArmour() + " (+" + me.getValue() + ")");
  407.                           } else {
  408.                               QueueProvider.offer(me.getKey() + ": " + this.getArmour() + " (" + me.getValue() + ")");
  409.                           }
  410.                           break;
  411.                     }
  412.                     case "maxHealth": {
  413.                           if (value  >= 0) {
  414.                               QueueProvider.offer(me.getKey() + ": " + this.getHealthMax() + " (+" + me.getValue() + ")");
  415.                           } else {
  416.                               QueueProvider.offer(me.getKey() + ": " + this.getHealthMax() + " (" + me.getValue() + ")");
  417.                           }
  418.                           break;
  419.                     }
  420.               }
  421.          }
  422.     }

  423.     public void inspectItem(String itemName) {
  424.         List<Item> itemMap = searchItem(itemName, getStorage());
  425.         if (itemMap.isEmpty()) {
  426.             itemMap = searchItem(itemName, getLocation().getItems());
  427.         }
  428.         if (!itemMap.isEmpty()) {
  429.             Item item = itemMap.get(0);
  430.             item.display();
  431.         } else {
  432.             QueueProvider.offer("Item doesn't exist within your view.");
  433.         }
  434.     }

  435.     public ILocation getLocation() {
  436.         return location;
  437.     }

  438.     public void setLocation(ILocation location) {
  439.         this.location = location;
  440.     }

  441.     public LocationType getLocationType() {
  442.         return getLocation().getLocationType();
  443.     }

  444.     public void attack(String opponentName) throws DeathException {
  445.         Monster monsterOpponent = null;
  446.         NPC npcOpponent = null;
  447.         List<Monster> monsters = getLocation().getMonsters();
  448.         List<NPC> npcs = getLocation().getNpcs();
  449.         for (int i = 0; i < monsters.size(); i++) {
  450.              if (monsters.get(i).monsterType.equalsIgnoreCase(opponentName)) {
  451.                  monsterOpponent = monsters.get(i);
  452.              }
  453.         }
  454.         for (int i=0; i < npcs.size(); i++) {
  455.             if (npcs.get(i).getName().equalsIgnoreCase(opponentName)) {
  456.                 npcOpponent = npcs.get(i);
  457.             }
  458.         }
  459.         if (monsterOpponent != null) {
  460.             monsterOpponent.setName(monsterOpponent.monsterType);
  461.             new BattleMenu(monsterOpponent, this);
  462.         } else if (npcOpponent != null) {
  463.             new BattleMenu(npcOpponent, this);
  464.         } else {
  465.              QueueProvider.offer("Opponent not found");
  466.         }
  467.     }

  468.     public boolean hasItem(Item item) {
  469.         List<Item> searchEquipment = searchEquipment(item.getName(), getEquipment());
  470.         List<Item> searchStorage = searchItem(item.getName(), getStorage());
  471.         return !(searchEquipment.size() == 0 && searchStorage.size() == 0);
  472.     }
  473. }