Skip to content

Instantly share code, notes, and snippets.

@sidke sidke/npp.py
Created Sep 13, 2016

Embed
What would you like to do?
#!/usr/bin/env python3
import argparse
import json
from struct import calcsize, unpack
class bytestream:
def __init__(self, data):
self.data = data
self.cursor = 0
def read(self, fmt, count=1):
cfmt = fmt * count
size = calcsize(cfmt)
value = unpack(cfmt, self.data[self.cursor:self.cursor + size])
self.cursor += size
return value[0] if len(value) == 1 else value
@property
def eof(self):
return self.cursor >= len(self.data)
class Level:
@staticmethod
def from_binary(binary):
stream = bytestream(binary)
metadata = stream.read('B', 38)
title = b''.join(stream.read('c', 128)).decode('utf-8').strip('\u0000')
metadata = stream.read('B', 18)
tiles = stream.read('B', 966)
counts = stream.read('B', 80)
objects = []
while not stream.eof:
objects.append(stream.read('B', 5))
return Level(title, tiles, objects)
def __init__(self, title, tiles, objects):
self.title = title
self.tiles = tiles
self.objects = objects
def to_json(self):
return json.dumps({
'title': self.title,
'tiles': self.tiles,
'objects': self.objects,
}, sort_keys=True)
parser = argparse.ArgumentParser()
parser.add_argument('file')
args = parser.parse_args()
level = Level.from_binary(open(args.file, 'rb').read())
print(level.to_json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.