Refactor multibyte text code to use a TextMapper

This commit is contained in:
Kevin Cathcart 2018-03-10 11:57:04 -05:00
parent ed6d66acd9
commit 93f77ddde3
1 changed files with 205 additions and 210 deletions

63
Text.py
View File

@ -504,14 +504,14 @@ def string_to_alttp_core(s, pause=True, wrap=14):
words.insert(0, word_rest) words.insert(0, word_rest)
lines.insert(0, ' '.join(words)) lines.insert(0, ' '.join(words))
write_word(outbuf, word_first) outbuf.extend(RawMBTextMapper.convert(word_first))
break break
if wordlen(word) <= (linespace if linespace == wrap else linespace - 1): if wordlen(word) <= (linespace if linespace == wrap else linespace - 1):
if linespace < wrap: if linespace < wrap:
word = ' ' + word word = ' ' + word
linespace -= wordlen(word) linespace -= wordlen(word)
write_word(outbuf, word) outbuf.extend(RawMBTextMapper.convert(word))
else: else:
# ran out of space, push word and lines back and continue with next line # ran out of space, push word and lines back and continue with next line
words.insert(0, word) words.insert(0, word)
@ -607,16 +607,28 @@ def charlen(word, offset):
return (2, offset+1) return (2, offset+1)
return (1, offset+1) return (1, offset+1)
def write_word(buf, word): class TextMapper(object):
for char in word: number_offset = None
res = char_to_alttp_char(char) alpha_offset = 0
if isinstance(res, int): char_map = {}
buf.extend([0x00, res]) @classmethod
else: def map_char(cls, char):
buf.extend(res) if cls.number_offset is not None:
if 0x30 <= ord(char) <= 0x39:
return ord(char) + cls.number_offset
if 0x61 <= ord(char) <= 0x7A:
return ord(char) + cls.alpha_offset
return cls.char_map.get(char, cls.char_map[' '])
@classmethod
def convert(cls, text):
buf = bytearray()
for char in text.lower():
buf.append(cls.map_char(char))
return buf
char_map = {' ': 0xFF, class RawMBTextMapper(TextMapper):
char_map = {' ': 0xFF,
'?': 0xC6, '?': 0xC6,
'!': 0xC7, '!': 0xC7,
',': 0xC8, ',': 0xC8,
@ -804,35 +816,18 @@ char_map = {' ': 0xFF,
'': 0x9D, '': 0x9D,
'': 0x9E, '': 0x9E,
'': 0x9F} '': 0x9F}
alpha_offset = 0x69
number_offset = 0x70
def char_to_alttp_char(char):
if 0x30 <= ord(char) <= 0x39:
return ord(char) + 0x70
if 0x41 <= ord(char) <= 0x5A:
return ord(char) + 0x69
return char_map.get(char, 0xFF)
class TextMapper(object):
number_offset = None
alpha_offset = 0
char_map = {}
@classmethod
def map_char(cls, char):
if cls.number_offset is not None:
if 0x30 <= ord(char) <= 0x39:
return ord(char) + cls.number_offset
if 0x61 <= ord(char) <= 0x7A:
return ord(char) + cls.alpha_offset
return cls.char_map.get(char, cls.char_map[' '])
@classmethod @classmethod
def convert(cls, text): def convert(cls, text):
buf = bytearray() buf = bytearray()
for char in text.lower(): for char in text.lower():
buf.append(cls.map_char(char)) res = cls.map_char(char)
if isinstance(res, int):
buf.extend([0x00, res])
else:
buf.extend(res)
return buf return buf