aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/client/GameStateDeserializer.java
blob: e2039ed8f7f2ad774a00da6c59937ce9c9160087 (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
package ch.epfl.xblast.client;

import ch.epfl.xblast.*;
import ch.epfl.xblast.client.GameState.Player;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * The client game state deserializer.
 *
 * @author Pacien TRAN-GIRARD (261948)
 * @author Timothée FLOURE (257420)
 */
public final class GameStateDeserializer {

    private static final int SERIALIZED_PLAYER_LENGTH = 4;
    private static final int SERIALIZED_PLAYERS_LENGTH = PlayerID.values().length * SERIALIZED_PLAYER_LENGTH;
    private static final int SERIALIZED_TICKS_LENGTH = 1;

    /**
     * Represents a length-prefixed chunk of byte-encoded data.
     */
    private static class VariableLengthChunk {

        private static final int PREFIX_SHIFT = 1;

        private final List<Byte> bytes;

        /**
         * Instantiates a VariableLengthChunk from a byte sequence.
         *
         * @param l the byte sequence
         */
        public VariableLengthChunk(List<Byte> l) {
            this.bytes = Lists.immutableList(l);
        }

        /**
         * Returns the length of the chunk given by its prefix.
         *
         * @return the length of the chunk
         */
        public int length() {
            if (this.bytes.isEmpty())
                return 0;
            else
                return Byte.toUnsignedInt(this.bytes.get(0));
        }

        /**
         * Returns the head of the desired length of the chunk.
         *
         * @param takeFirst the desired length
         * @return the head
         */
        public List<Byte> head(int takeFirst) {
            return this.bytes.subList(0, takeFirst);
        }

        /**
         * Returns the head of the size-prefixed chunk.
         *
         * @return the head
         */
        public List<Byte> head() {
            if (this.length() < 1)
                return Collections.emptyList();
            else
                return this.bytes.subList(PREFIX_SHIFT, this.length() + PREFIX_SHIFT);
        }

        /**
         * Returns the tail of the chunk, with the head of the given length dropped.
         *
         * @param dropFirst the length to drop
         * @return the tail
         */
        public VariableLengthChunk tail(int dropFirst) {
            return new VariableLengthChunk(
                    this.bytes.subList(dropFirst, this.bytes.size()));
        }

        /**
         * Returns the tail of the size-prefixed chunk.
         *
         * @return the tail
         */
        public VariableLengthChunk tail() {
            return new VariableLengthChunk(
                    this.bytes.subList(this.length() + PREFIX_SHIFT, this.bytes.size()));
        }

    }

    private GameStateDeserializer() {
        // Static class
    }

    /**
     * Deserialize an encoded chunk of data and link it to images.
     *
     * @param data            serialized data
     * @param imageCollection ImageCollection related to the type of data
     * @return a list of Images corresponding to the serialized element
     */
    private static List<Image> deserializeImageChunk(List<Byte> data, ImageCollection imageCollection) {
        return Collections.unmodifiableList(RunLengthEncoder.decode(data).stream()
                .map(Byte::toUnsignedInt)
                .map(imageCollection::imageOrNull)
                .collect(Collectors.toList()));
    }

    /**
     * Unserializes a spiral-ordered byte representation of a board.
     *
     * @param serializedBoard the run-length-compressed, serialized spiral ordered board
     * @return the row-major-ordered board
     * @throws IllegalArgumentException if the length of the serialized board is invalid
     */
    private static List<Image> deserializeBoard(List<Byte> serializedBoard) {
        List<Image> spiralOrdered = deserializeImageChunk(serializedBoard, ImageCollection.BOARD_IMAGES);

        if (spiralOrdered.size() != Cell.SPIRAL_ORDER.size())
            throw new IllegalArgumentException();

        Map<Cell, Image> imageMap = IntStream
                .range(0, Cell.SPIRAL_ORDER.size()).mapToObj(i -> i)
                .collect(Collectors.toMap(Cell.SPIRAL_ORDER::get, spiralOrdered::get));

        return Collections.unmodifiableList(Cell.ROW_MAJOR_ORDER.stream()
                .map(imageMap::get)
                .collect(Collectors.toList()));
    }

    /**
     * Unserializes a byte representation of explosions and bombs.
     *
     * @param serializedExplosions the run-length-compressed, serialized explosions
     * @return the explosions
     */
    private static List<Image> deserializeExplosions(List<Byte> serializedExplosions) {
        return deserializeImageChunk(serializedExplosions, ImageCollection.EXPLOSIONS_IMAGES);
    }

    /**
     * Unserializes a byte representation of a Player.
     *
     * @param id               the PlayerID
     * @param serializedPlayer the serialized player
     * @return the player
     * @throws IllegalArgumentException if the byte chunk is invalid.
     */
    private static Player deserializePlayer(PlayerID id, List<Byte> serializedPlayer) {
        if (Objects.isNull(serializedPlayer) || serializedPlayer.size() != SERIALIZED_PLAYER_LENGTH)
            throw new IllegalArgumentException();

        List<Integer> intPlayerData = serializedPlayer.stream()
                .map(Byte::toUnsignedInt)
                .collect(Collectors.toList());

        Integer lives = intPlayerData.get(0);
        SubCell pos = new SubCell(intPlayerData.get(1), intPlayerData.get(2));
        Image img = ImageCollection.PLAYERS_IMAGES.imageOrNull(intPlayerData.get(3));
        return new Player(id, lives, pos, img);
    }

    /**
     * Unserializes a byte representation of players.
     *
     * @param serializedPlayers the serialized players
     * @return the list of deserialized players
     * @throws IllegalArgumentException if the byte chunk is invalid.
     */
    private static List<Player> deserializePlayers(List<Byte> serializedPlayers) {
        if (Objects.isNull(serializedPlayers) || serializedPlayers.size() != SERIALIZED_PLAYERS_LENGTH)
            throw new IllegalArgumentException();

        return Collections.unmodifiableList(Arrays.stream(PlayerID.values())
                .map(pid -> {
                    List<Byte> chunk = serializedPlayers.subList(
                            pid.ordinal() * SERIALIZED_PLAYER_LENGTH,
                            (pid.ordinal() + 1) * SERIALIZED_PLAYER_LENGTH);
                    return new AbstractMap.SimpleImmutableEntry<>(pid, chunk);
                })
                .map(e -> deserializePlayer(e.getKey(), e.getValue()))
                .collect(Collectors.toList()));
    }

    /**
     * Unserializes a byte representation of the ticks.
     *
     * @param serializedTicks the serialized ticks
     * @return the ticks
     * @throws IllegalArgumentException if the byte chunk is invalid.
     */
    private static int deserializeTicks(List<Byte> serializedTicks) {
        if (Objects.isNull(serializedTicks) || serializedTicks.size() != SERIALIZED_TICKS_LENGTH)
            throw new IllegalArgumentException();

        return Byte.toUnsignedInt(serializedTicks.get(0));
    }

    /**
     * Deserialize an incoming GameState.
     *
     * @param serializedData the serialized gameState
     * @return a new GameState build from the serialized data.
     */
    public static GameState deserialize(List<Byte> serializedData) {
        VariableLengthChunk chunks = new VariableLengthChunk(serializedData);

        List<Image> board = deserializeBoard(chunks.head());
        chunks = chunks.tail();

        List<Image> explosions = deserializeExplosions(chunks.head());
        chunks = chunks.tail();

        List<Player> players = deserializePlayers(chunks.head(SERIALIZED_PLAYERS_LENGTH));
        chunks = chunks.tail(SERIALIZED_PLAYERS_LENGTH);

        int ticks = deserializeTicks(chunks.head(SERIALIZED_TICKS_LENGTH));

        return new GameState(players, board, explosions, ticks);
    }

}