Skip to content

Method: static {...}

1: package de.fhdw.gaming.ipspiel23.c4.strategies.internals;
2:
3: import java.util.Optional;
4: import java.util.Random;
5:
6: import de.fhdw.gaming.core.domain.GameException;
7: import de.fhdw.gaming.ipspiel23.c4.domain.C4PositionMaterializer;
8: import de.fhdw.gaming.ipspiel23.c4.domain.IC4Player;
9: import de.fhdw.gaming.ipspiel23.c4.domain.IC4Position;
10: import de.fhdw.gaming.ipspiel23.c4.domain.IC4State;
11: import de.fhdw.gaming.ipspiel23.c4.moves.IC4Move;
12: import de.fhdw.gaming.ipspiel23.c4.moves.factory.IC4MoveFactory;
13: import de.fhdw.gaming.ipspiel23.c4.strategies.IC4Strategy;
14:
15: /**
16: * A strategy that picks a random legal move.
17: */
18: public class C4RandomMoveStrategy implements IC4Strategy {
19:
20: /**
21: * Your friendly neighborhood random number generator.
22: */
23: private static final Random RANDOM = new Random();
24:
25: /**
26: * The move factory.
27: */
28: private final IC4MoveFactory moveFactory;
29:
30: /**
31: * Creates a new random move strategy.
32: *
33: * @param moveFactory the move factory
34: */
35: public C4RandomMoveStrategy(final IC4MoveFactory moveFactory) {
36: this.moveFactory = moveFactory;
37: }
38:
39: @Override
40: public Optional<IC4Move> computeNextMove(final int gameId, final IC4Player player, final IC4State state)
41: throws GameException, InterruptedException {
42: // there can only be one move per column
43: // we could also cache and re-use this array in ThreadLocal storage in the future
44: final long[] legalPositions = new long[state.getBoard().getColumnCount()];
45: // avoid temporary object allocation by directly using the internal board
46: final int positionsWritten = state.getBoard()
47: .getInternalBoard()
48: .getLegalDematPositionsUnsafe(legalPositions);
49: if (positionsWritten == 0) {
50: return Optional.empty();
51: }
52: // pick a random legal position
53: final int randomIndex = RANDOM.nextInt(positionsWritten);
54: final long randomDematerializedPosition = legalPositions[randomIndex];
55: // rematerialize only that position into a position object
56: final IC4Position randomPosition = C4PositionMaterializer.rematerialize(randomDematerializedPosition);
57: // create the move
58: final IC4Move move = moveFactory.createMove(player, randomPosition);
59: // done :)
60: return Optional.of(move);
61: }
62:
63: @Override
64: public String toString() {
65: return C4RandomMoveStrategy.class.getSimpleName();
66: }
67: }