我是一个过时游戏《帝国时代II》(AoE)的粉丝。我想使用Python编写一个AoE游戏记录(.mgx文件)的解析器。
我在GitHub上进行了一些搜索,发现很少有相关项目,其中最有用的是aoc-mgx-format,它提供了.mgx游戏记录文件的一些细节。
这里有个问题:
根据参考资料,.mgx文件的结构如下:
| header_len(4字节整数) | next_pos(4字节整数) | header_data | ... ... |
mgx格式中十六进制数据的字节顺序为小端。
header_len
存储头部部分(header_len
+ next_post
+ header_data
)的数据长度。
header_data
存储了我需要的有用信息,但它使用 zlib 进行了压缩。
我尝试使用 zlib 模块解压 header_data
中的数据,代码如下:
import struct
import zlib
with open('test.mgx', "rb") as fp:
# read the header_len bytes and covert it to a int reprents length of Header part
header_len = struct.unpack("<i", fp.read(4))[0]
# read next_pos (this is not important for me)
next_pos = struct.unpack("<i", fp.read(4))[0]
# then I can get data length of header_data part(compressed with zlib)
header_data_len = header_len - 8
compressed_data = fp.read(header_data_len)[::-1] # need to be reversed because byte order is little endian?
try:
zlib.decompress(compressed_data)
print "can be decompressed!"
except zlib.error as e:
print e.message
但我运行程序后得到了以下内容:
解压数据时出错,错误代码为-3:头文件检查不正确
PS:可在此处找到示例.mgx文件:https://github.com/stefan-kolb/aoc-mgx-format/tree/master/parser/recs
zlib.decompress(compressed_data, -zlib.MAX_WBITS)
会起作用。 - lichifeng