einstein/einsteingame/formatter.py

108 lines
2.8 KiB
Python

import struct
from enum import Enum
class Formatter(object):
class CmdType(Enum):
EMPTY_CMD = 0
TEXT_COMMAND = 1
INT_ARG = 2
STRING_ARG = 3
DOUBLE_ARG = 4
FLOAT_ARG = 5
def __init__(self, data, offset):
cnt = struct.unpack('i', data[offset:offset + 4])[0]
if cnt == 0:
commandsCnt = argsCnt = 0
commands = NULL
args = NULL
offset += 4
commands = []
commandsCnt = 0
maxArg = 0
argNo = None
for i in range(0, cnt):
typ = data[offset]
offset += 1
size = struct.unpack('i', data[offset:offset + 4])[0]
offset += 4
if typ == 1:
commands.append({
"type": self.CmdType.TEXT_COMMAND,
"data": data[offset:offset + size].decode('utf-8'),
})
elif typ == 2:
argNo = struct.unapack('i', data[offset:offset + 4])[0]
if argNo > maxArg:
maxArg = argNo
commands.append({
"type": self.CmdType.INT_ARG,
"data": argNo,
})
elif typ == 3:
argNo = struct.unapack('i', data[offset:offset + 4])[0]
if argNo > maxArg:
maxArg = argNo
commands.append({
"type": self.CmdType.STRING_ARG,
"data": argNo,
})
elif typ == 3:
argNo = struct.unapack('i', data[offset:offset + 4])[0]
if argNo > maxArg:
maxArg = argNo
commands.append({
"type": self.CmdType.FLOAT_ARG,
"data": argNo,
})
elif typ == 3:
argNo = struct.unapack('i', data[offset:offset + 4])[0]
if argNo > maxArg:
maxArg = argNo
commands.append({
"type": self.CmdType.DOUBLE_ARG,
"data": argNo,
})
offset += size;
argsCnt = maxArg
if argsCnt == 0:
args = None
else:
args = []
for i in range(0, len(commands)):
args.append[0]
for i in range(0, len(commands)):
c = commands[i]
if c.type == INT_ARG or c.type == STRING_ARG or c.type == FLOAT_ARG or c.type == DOUBLE_ARG:
no = c.data
args[no - 1] = c.type
self.__commands = commands
def getMessage(self):
ret = ''
for command in self.__commands:
ret += command['data']
return repr(ret)