JAVA 3 factions each have their own npc, faction 1 (101, 102, 103...), faction 2 (201,…
- User
JAVA 3 factions each have their own npc, faction 1 (101, 102, 103...), faction 2 (201, 202, 203...), faction 3 (301, 302, 303...) there are some other npc that must be tied to existing like this: 'new npc 401','new npc 402','new npc 403' tied to (101, 201, 301), 'new npc 404', 'new npc 405', 'new npc 406' tied to (102, 202, 302)... we need to tied a couple of new npc to another couple of existing npc what we want to achieve is next: if a player of 'faction X' attacks 'new npc' we want to check if its npc alive (because if 101 is alive 201 and 301 is not and so on) and stop his attack if yes so if a player faction 1 attacks npc 401, 402, 403 and npc 101 is alive - we stop him but if a player with faction 2 attacks npc 401, 402, 403 and npc 101 is alive - we will not stop him, but if it was npc 201 we would u cant hardcode alive or not... we will get this some way, dont worry about it too much (just assume that i have some isAlive method for this in my original code) so how would we do that? all these numbers is just an example and can be different i need a simple, easy to follow approach, dont write a code in unredable way be consice, dont overexplain, i must understand everything from your code not from your explanation (stop flooding with comments in code, comments in code isnt allowed)
show me 2 different ways: #1 the best, whatever u see as the best here #2 the simplest solution possible, as less code as possible and super simple to achive what i need
Assistant
Here are two approaches:
#1 Best approach - using a Map structure to organize relationships:
class FactionSystem { private Map<Integer, List<Integer>> npcToTiedNpcs = new HashMap<>(); private Map<Integer, Integer> npcToFaction = new HashMap<>(); public void init() { npcToFaction.put(101, 1); npcToFaction.put(201, 2); npcToFaction.put(301, 3); npcToTiedNpcs.put(401, Arrays.asList(101, 201, 301)); npcToTiedNpcs.put(402, Arrays.asList(101, 201, 301)); npcToTiedNpcs.put(403, Arrays.asList(101, 201, 301)); } public boolean canAttack(int playerFaction, int targetNpc) { List<Integer> tiedNpcs = npcToTiedNpcs.get(targetNpc); if (tiedNpcs == null) return true; for (int tiedNpc : tiedNpcs) { if (npcToFaction.get(tiedNpc) == playerFaction && isAlive(tiedNpc)) { return false; } } return true; } }#2 Simplest approach - using arrays and basic math:
class FactionSystem { public boolean canAttack(int playerFaction, int targetNpc) { if (targetNpc < 400) return true; int baseNpc = 100 * playerFaction + ((targetNpc - 400) / 3); return !isAlive(baseNpc); } }Both assume you have
boolean isAlive(int npcId)method available.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.