aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/server/GameStateTransitioner.java
blob: 5c22f255d4c7484ac7121c99814afd16d9af5ee2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package ch.epfl.xblast.server;

import ch.epfl.cs108.Sq;
import ch.epfl.xblast.Cell;
import ch.epfl.xblast.Direction;
import ch.epfl.xblast.PlayerID;
import ch.epfl.xblast.SubCell;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * The game state transitioner providing methods for game state evolution.
 *
 * @author Pacien TRAN-GIRARD (261948)
 * @author Timothée FLOURE (257420)
 */
final class GameStateTransitioner {

    private GameStateTransitioner() {
        // Static class
    }

    /**
     * Maps bombs to their owning player ID.
     *
     * @param b the list of bombs
     * @return the mapping
     */
    private static Map<PlayerID, List<Bomb>> mapBombsToPlayers(List<Bomb> b) {
        return b.stream().collect(Collectors.groupingBy(Bomb::ownerId));
    }

    /**
     * Computes the next state of a blast.
     *
     * @param blasts0     existing particles
     * @param board0      the game's board
     * @param explosions0 active explosions
     * @return the position of the explosion's particles for the next state.
     */
    static List<Sq<Cell>> nextBlasts(List<Sq<Cell>> blasts0, Board board0, List<Sq<Sq<Cell>>> explosions0) {
        return Stream.concat(
                blasts0.stream()
                        .filter(b -> board0.blockAt(b.head()).isFree())
                        .map(Sq::tail),
                explosions0.stream()
                        .filter(e -> !e.isEmpty())
                        .map(Sq::head))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * Computes and returns the next board state of the given board according to the given events.
     *
     * @param board0          the previous board
     * @param consumedBonuses the set of consumed bonuses
     * @param blastedCells1   the set of newly blasted cells
     * @return the next board
     */
    static Board nextBoard(Board board0, Set<Cell> consumedBonuses, Set<Cell> blastedCells1) {
        return new Board(Cell.ROW_MAJOR_ORDER.stream()
                .map(c -> nextBlockSeq(c, board0.blocksAt(c), consumedBonuses, blastedCells1))
                .collect(Collectors.toList()));
    }

    /**
     * Returns the next Block sequence for the given cell according to the current state and given events.
     *
     * @param c               the Cell
     * @param bs0             the previous Block sequence
     * @param consumedBonuses the bonus consumption event
     * @param blastedCells1   the new Cell blast events
     * @return the new Block sequence
     */
    private static Sq<Block> nextBlockSeq(Cell c, Sq<Block> bs0, Set<Cell> consumedBonuses, Set<Cell> blastedCells1) {
        Block b = bs0.head();

        if (consumedBonuses.contains(c) && b.isBonus())
            return Sq.constant(Block.FREE);

        if (blastedCells1.contains(c))
            if (b == Block.DESTRUCTIBLE_WALL)
                return Sq.repeat(Ticks.WALL_CRUMBLING_TICKS, Block.CRUMBLING_WALL)
                        .concat(Sq.constant(Block.getRandomBonusBlock()));

            else if (b.isBonus())
                return bs0.limit(Ticks.BONUS_DISAPPEARING_TICKS)
                        .concat(Sq.constant(Block.FREE));

        return bs0.tail();
    }

    /**
     * Computes and returns the next player list given the current one and the given events and states.
     *
     * @param players0          the previous player list
     * @param playerBonuses     the map of player bonuses
     * @param bombedCells1      the set of newly bombed cells
     * @param board1            the newly updated board
     * @param blastedCells1     the set of newly blasted cells
     * @param speedChangeEvents the speed change events
     * @return the next player list
     */
    static List<Player> nextPlayers(List<Player> players0, Map<PlayerID, Bonus> playerBonuses,
                                    Set<Cell> bombedCells1, Board board1, Set<Cell> blastedCells1,
                                    Map<PlayerID, Optional<Direction>> speedChangeEvents) {

        return players0.stream()
                .map(p -> nextPlayer(
                        p, playerBonuses.get(p.id()),
                        bombedCells1, board1, blastedCells1,
                        speedChangeEvents.get(p.id())))
                .collect(Collectors.toList());
    }

    /**
     * Computes and returns the next State of a Player from the given events.
     *
     * @param player0            the Player
     * @param playerBonus        the optional Bonus to apply to the Player
     * @param bombedCells1       the Set of bombed Cells
     * @param board1             the updated Board
     * @param blastedCells1      the Set of blasted Cells
     * @param requestedDirection the Player's new requested Direction
     * @return the next state of the Player
     */
    private static Player nextPlayer(Player player0, Bonus playerBonus,
                                     Set<Cell> bombedCells1, Board board1, Set<Cell> blastedCells1,
                                     Optional<Direction> requestedDirection) {

        // 1. Compute the new path to follow
        Sq<Player.DirectedPosition> updatedPath = nextPath(player0.directedPositions(), requestedDirection);

        // 2. Follow the path if the Player can (moving life state and no collision)
        Sq<Player.DirectedPosition> directedPos1 = moveAhead(player0, updatedPath, board1, bombedCells1);

        // 3. Apply damages and generate a new LifeState Sequence
        Sq<Player.LifeState> lifeStates1 = nextLifeState(player0, directedPos1, blastedCells1);

        // 4. Create the new player given the new parameters
        Player p1 = new Player(player0.id(), lifeStates1, directedPos1, player0.maxBombs(), player0.bombRange());

        // 5. Update the capacities of the player given the possible bonus
        if (!Objects.isNull(playerBonus))
            p1 = playerBonus.applyTo(p1);

        return p1;
    }

    /**
     * Computes the new path to follow according to the Player's wishes and the Board constraints.
     *
     * @param p0     the current path
     * @param newDir the new requested Direction
     * @return the new path
     */
    private static Sq<Player.DirectedPosition> nextPath(Sq<Player.DirectedPosition> p0, Optional<Direction> newDir) {
        if (Objects.isNull(newDir))
            return p0;

        if (!newDir.isPresent())
            return stopPath(p0);

        if (p0.head().direction().isPerpendicularTo(newDir.get()))
            return pivotPath(Player.DirectedPosition.moving(p0.head()), newDir.get());

        return Player.DirectedPosition.moving(new Player.DirectedPosition(p0.head().position(), newDir.get()));
    }

    /**
     * Builds and returns a path stopping at the next central SubCell.
     *
     * @param p0 the current path
     * @return the stop path
     */
    private static Sq<Player.DirectedPosition> stopPath(Sq<Player.DirectedPosition> p0) {
        return pathToNextCentralPosition(p0)
                .concat(Player.DirectedPosition.stopped(nextCentral(p0)));
    }

    /**
     * Builds and returns a pivot path reaching the next pivot SubCell and then rotating to the given Direction.
     *
     * @param p0     the initial path
     * @param newDir the new Direction to follow when possible
     * @return the pivot path
     */
    private static Sq<Player.DirectedPosition> pivotPath(Sq<Player.DirectedPosition> p0, Direction newDir) {
        SubCell nextCentralPos = nextCentral(p0).position();

        return pathToNextCentralPosition(p0)
                .concat(Player.DirectedPosition.moving(new Player.DirectedPosition(nextCentralPos, newDir)));
    }

    /**
     * Returns the path to the next central SubCell.
     *
     * @param p the path to follow
     * @return the truncated path
     */
    private static Sq<Player.DirectedPosition> pathToNextCentralPosition(Sq<Player.DirectedPosition> p) {
        return p.takeWhile(dp -> !dp.position().isCentral());
    }

    /**
     * Searches for and returns the next central SubCell reachable following the given path.
     *
     * @param p the path to follow
     * @return the next central SubCell
     */
    private static Player.DirectedPosition nextCentral(Sq<Player.DirectedPosition> p) {
        return p.findFirst(dp -> dp.position().isCentral());
    }

    /**
     * Checks for possible collisions and update the path if necessary.
     *
     * @param path         the current path projection
     * @param board1       the updated Board
     * @param bombedCells1 the Set of bombed Cell-s
     * @return the corrected path
     */
    private static Sq<Player.DirectedPosition> moveAhead(Player player0,
                                                         Sq<Player.DirectedPosition> path,
                                                         Board board1, Set<Cell> bombedCells1) {

        if (!player0.lifeState().canMove())
            return path;

        if (isColliding(path, board1, bombedCells1))
            return path;

        return path.tail();
    }

    /**
     * Returns T(the player is colliding with an object).
     *
     * @param path         the path
     * @param board1       the updated Board
     * @param bombedCells1 the Set of bombed Cell-s
     * @return T(the player is colliding with an object)
     */
    private static boolean isColliding(Sq<Player.DirectedPosition> path, Board board1, Set<Cell> bombedCells1) {
        SubCell nextPos = path.tail().head().position();
        SubCell nextCentralPos = nextCentral(Player.DirectedPosition.moving(path.tail().head())).position();

        if (!board1.blockAt(nextCentralPos.containingCell()).canHostPlayer())
            return true;

        if (bombedCells1.contains(nextCentralPos.containingCell()))
            if (nextPos.distanceTo(nextCentralPos) == Board.BOMB_BLOCKING_DISTANCE - 1)
                return true;

        return false;
    }

    /**
     * Applies damages and generate a new LifeState sequence.
     *
     * @param player0            the Player
     * @param directedPositions1 the DirectedPosition sequence
     * @param blastedCells1      the Set of blasted Cell-s
     * @return the next LifeState sequence
     */
    private static Sq<Player.LifeState> nextLifeState(Player player0, Sq<Player.DirectedPosition> directedPositions1,
                                                      Set<Cell> blastedCells1) {

        Cell currentCell = directedPositions1.head().position().containingCell();

        if (player0.isVulnerable() && blastedCells1.contains(currentCell))
            return player0.statesForNextLife();
        else
            return player0.lifeStates().tail();
    }

    /**
     * Computes and returns the next state of the given explosion list.
     *
     * @param explosions0 the previous explosion state
     * @return the next explosion state
     */
    static List<Sq<Sq<Cell>>> nextExplosions(List<Sq<Sq<Cell>>> explosions0) {
        return explosions0.stream()
                .map(Sq::tail)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * Returns a list of exploding bombs (reached by a blast or consumed fuse).
     *
     * @param bombs        the list of bombs
     * @param blastedCells the set of blasted cells
     * @return the list of exploding bombs
     */
    static List<Bomb> explodingBombs(List<Bomb> bombs, Set<Cell> blastedCells) {
        return bombs.stream()
                .filter(b -> blastedCells.contains(b.position()) || b.fuseLengths().tail().isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * Computes the consumption of the bombs.
     *
     * @param bombs0         the list of bombs
     * @param explodingBombs the list of exploding bombs
     * @return the new bombs states
     */
    static List<Bomb> nextBombs(List<Bomb> bombs0, List<Bomb> explodingBombs) {
        return bombs0.stream()
                .filter(b -> !explodingBombs.contains(b))
                .map(b -> new Bomb(b.ownerId(), b.position(), b.fuseLengths().tail(), b.range()))
                .collect(Collectors.toList());
    }

    /**
     * Computes and returns the list of newly dropped bombs by players according to the given player states and events.
     * Given bomb drop events must be conflict-free.
     *
     * @param players0       the previous player states
     * @param bombDropEvents the bomb drop events
     * @param bombs0         the previous bomb state
     * @return the newly dropped bombs
     */
    static List<Bomb> newlyDroppedBombs(List<Player> players0, Set<PlayerID> bombDropEvents, List<Bomb> bombs0) {
        HashSet<Cell> bombedCells = new HashSet<>(GameState.bombedCells(bombs0).keySet());
        Map<PlayerID, List<Bomb>> bombOwnerMap = mapBombsToPlayers(bombs0);
        List<Bomb> bombs1 = new ArrayList<>(bombs0);

        for (Player p : players0) {
            if (!bombDropEvents.contains(p.id())) continue;
            if (bombedCells.contains(p.position().containingCell())) continue;

            List<Bomb> ownedBombs = bombOwnerMap.get(p.id());
            if (ownedBombs != null && ownedBombs.size() >= p.maxBombs()) continue;

            Bomb b = p.newBomb();
            bombedCells.add(b.position());
            bombs1.add(b);
        }

        return bombs1;
    }

}