Wednesday, December 2, 2015

java - RPG Factions - Friendly/Hostile check


I'm having some trouble checking if one faction is hostile to another faction in my RPG. I'm using enums for my factions and relations but I feel like there's a better way to approach this.
Currently this is my code for the factions (copy+paste ruined format...)



public enum Faction {
/*
* Position 1 = Humans
* Position 2 = Elves
* Position 3 = Dwarves
* Position 4 = Orcs
* Position 5 = Undead
* Position 6 = Trolls
* ....
*/


Human(Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/),
Elf(Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Dwarf(Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Orc(Relations.Neutral, Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Hostile, Relations.Friendly),
Undead(Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Friendly, Relations.Hostile),
Troll(Relations.Hostile, Relations.Hostile, Relations.Hostile,Relations.Friendly, Relations.Hostile, Relations.Friendly);

Faction(Relations... relation) {


}


}

enum Relations {
Hostile(),
Neutral(),
Friendly();
}


class FactionHandler {
public boolean checkIfHostile(Faction faction1, Faction faction2) {
//How do I check?
}
}

The lazy way to do this would be to do lots of if/else statements but I want a more clean way to check.


Basically I want it to check faction1's relation with faction2, and return true if they are enemies, and false if they are friends. Feel free to entirely scrap my code if there's a better solution to this problem as this code is mainly just me experimenting.



Answer




Build a 2D array of enum Relations, where row and column are the Factions.


You can then check using a simple array lookup:


public boolean checkIfHostile(Faction faction1, Faction faction2) {
return relations[faction1.ordinal()][faction2.ordinal()] == Relations.Hostile;
}

Fill it in making sure [x][y] == [y][x] and that the diagonal [i][i] is Friendly or Neutral.


For example:


Relations[][] relations = new Relations[][]{
{ Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/},

{ Relations.Neutral, Relations.Friendly, ...},
...,
};

(I didn't fill in the whole table for readability, just keep going where the ... are)


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...