Serialize the Maze
00:00 Serialize the Maze. Unless you already have some data to work with, you are better off implementing the serialization code first, which will eventually write a file that you can later use to test the loading procedure.
Here you define the
serialize() function, which accepts an instance of the
Maze model that you implemented in part one of the course. This function produces a tuple consisting of the file header and body, which you’ll later dump into a binary file.
00:59 This prepares the file header by setting a known file format version based on a constant, as there’s only one version currently supported. Other header field values are copied from the maze object that was passed as an argument.
Here you populate the file body with binary values obtained by compressing the border patterns and square roles into a single byte for each square. Calling
map() on the maze instance implicitly iterates over it and applies the
compress() function on each square of the maze.
This should create a new file named
miniature.maze in your current working directory where you started your Python REPL session. If the file already exists, then it will be overwritten without any warning, so be careful!
The first thirteen bytes are the header, followed by twelve bytes corresponding to the twelve squares in the maze. If you have access to a hex editor or a tool like
hexdump, then you can inspect the file’s binary content, which should look as seen on-screen.
04:05 For example, the byte at offset zero is 4d16 hexadecimal or 77 in the decimal system. This corresponds to the uppercase letter M in ASCII. On the right, you see a text representation of the same data.
04:20 The dots represent non-printable characters. Other characters depict bytes that happen to have a visual representation in ASCII. If you discard the header, you’ll be left with the last twelve bytes of the file, which translate to the values seen on-screen.
The resulting sequence of numbers consists of bit fields that should match the squares in your miniature maze. The two outliers with noticeably higher values,
37, contain extra information about the special roles of these particular squares. In this case, one must be the entrance and the other the exit.
Become a Member to join the conversation.