0
\$\begingroup\$

For a Java game, say I have two classes:

Player, representing a player in the game. Faction, representing a faction of players in the game.

When the game starts up, all factions are loaded into some collection and all players are loaded into some collection.

Collection<Player> players;
Collection<Faction> factions;

Say there are two variables:

Player player1;
Faction the_destroyers;

player1 is in the faction the_destroyers.

the_destroyers needs to reference player1, since player1 is in the_destroyers. At the same time, player1 needs to reference the_destroyers, for quick lookup (otherwise I would have to iterate through the collection of factions, which may be a very large collection).

Obviously, whichever variable is loaded first cannot reference the other, since the other has not yet been loaded.

Generally speaking, how do I get around this issue? Is there a simpler solution?

\$\endgroup\$

2 Answers 2

9
\$\begingroup\$

What I would do is make the factions be simple symbols which represent their information regardless of members (name, description etc), and keep some sort of dictionary for each match, which keeps track of which players are in which faction.

Dictionary<Faction, List<Player>>

This also allows you to do more exotic stuff like players betraying their faction and switching more easily.

For accessing the faction from the player's point of view, you can just use a field in the player's class.

void addToDictionary(Faction faction, Player player) {
    dict[faction].add(player);
    player.setFaction(faction);
}
\$\endgroup\$
3
\$\begingroup\$

Create one type of object first without adding any references to the other.

Then you create the other type of object, and during its construction you create the bidirectional links between itself and the other object type.

The calling code would look like this:

// create players
Player player1 = new Player("1");
Player player2 = new Player("2");
Player player3 = new Player("3");

// create factions
Faction jpf = new Faction("Judean People's Front");
jpf.addPlayer(player1);
jpf.addPlayer(player3);

Faction pfj = new Faction("People's Front of Judea");
pfj.addPlayer(player1);
pfj.addPlayer(player2);

The implementation of addPlayer would then both add the player to the faction and tell the player that it is now a member of this faction:

public void addPlayer(Player player) {
    this.players.add(player);
    player.addFaction(this);
}

(omitted for clarity: Checking that the player isn't already a member of that faction, and when that's the case, throw an exception)

This example loads the players first and then the factions, but you can of course also do it the other way around. You can also choose to add factions to players instead of adding players to factions. Choose whatever option makes more sense in the context of your game.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .