Skip to content

Method: GameMemoryIdentifier(int)

1: package de.fhdw.gaming.ipspiel23.memory;
2:
3: import de.fhdw.gaming.core.domain.Move;
4: import de.fhdw.gaming.core.domain.Player;
5: import de.fhdw.gaming.core.domain.State;
6: import de.fhdw.gaming.core.domain.Strategy;
7:
8: /**
9: * A handle uniquely identifying a game memory instance.
10: */
11: public final class GameMemoryIdentifier implements IGameMemoryIdentifier {
12:
13: /**
14: * The hash code/identity value of this identifier.
15: */
16: private final int precomputedHashCode;
17:
18: /**
19: * Creates a new identifier with the given hash code.
20: *
21: * @param hashCode The hash code/identity value of this identifier.
22: */
23: private GameMemoryIdentifier(final int hashCode) {
24: precomputedHashCode = hashCode;
25: }
26:
27: /**
28: * Creates a new identifier for the given player and strategy against the given opponent strategy.
29: * Subsequent calls with the same parameters will return the same identifier instance.
30: *
31: * @param <P> The player type.
32: * @param <S> The state type.
33: * @param <M> The move type.
34: * @param player The player.
35: * @param strategy The strategy.
36: * @param opponentStrategy The opponent's strategy.
37: * @return A new identifier for the given player and strategy against the given opponent strategy.
38: */
39: public static <P extends Player<P>, S extends State<P, S>, M extends Move<P, S>>
40: IGameMemoryIdentifier of(final Player<P> player, final Strategy<P, S, M> strategy,
41: final Strategy<P, S, M> opponentStrategy) {
42:
43: // pre-compute the hash code to avoid having to store this generic madness.
44: // reuse identifier is based on strategy type, and player name.
45: int hash = 7;
46: hash = 31 * hash + player.getName().hashCode();
47: hash = 31 * hash + strategy.getClass().getName().hashCode();
48: hash = 31 * hash + opponentStrategy.getClass().getName().hashCode();
49: return new GameMemoryIdentifier(hash);
50: }
51:
52: @Override
53: public int hashCode() {
54: return precomputedHashCode;
55: }
56:
57: @Override
58: public boolean equals(final Object obj) {
59: if (obj instanceof GameMemoryIdentifier) {
60: return precomputedHashCode == ((GameMemoryIdentifier) obj).precomputedHashCode;
61: }
62: return false;
63: }
64: }