Deserialize the Maze
00:31 You open the file for reading in binary mode, obtain the file header, and then check the file’s format version before attempting to read its body. If the file format is unsupported, you raise an exception.
00:51 Otherwise, you pass the header and body to another function, which can create a new maze object based on the information provided. In the future, you could branch this code to read the file body differently depending on the detected version. The deserializing function is the next thing to code.
First, you create an empty list, which you then populate with
Square instances by looping over the square values in the file body. To keep track of the current square index, you enumerate the values and calculate their row and column based on metadata in the header.
Finally, you pass the squares as a tuple to the
Maze constructor. The decompression of a single square value follows the principles outlined earlier in the course when you were choosing how to pack your data into a single byte.
02:54 The bitmask and bit shifting allow you to separate the two pieces of data from a single number. Your enumerations can be seeded with these two numbers, while their resulting members can be wrapped in a tuple and returned.
There’s one last detail to improve in your current implementation of the maze serialization. Notice that in order to load or dump the maze to a file, you need to import both the
Maze model and the relevant function from the
Become a Member to join the conversation.