YAML maps can now be loaded, and they work well.

This commit is contained in:
Patrick Marsee 2019-03-09 19:50:31 -05:00
parent adfb6b83f4
commit eeab517213
5 changed files with 46 additions and 53 deletions

View file

@ -289,7 +289,7 @@ class Door(Thing):
locked, description, key, graphic) locked, description, key, graphic)
class MapExit(Thing): class MapExit(Thing):
yaml_flag = u'!Exit' yaml_flag = u'!MapExit'
defaultGraphic = ('clear', '#FF0000', 'x') defaultGraphic = ('clear', '#FF0000', 'x')
def __init__(self, name, x: int, y: int, exitid: int, destination: str, prefix: None, graphic = defaultGraphic): def __init__(self, name, x: int, y: int, exitid: int, destination: str, prefix: None, graphic = defaultGraphic):
@ -326,9 +326,9 @@ class MapExit(Thing):
constructor.construct_mapping(node, parts, True) constructor.construct_mapping(node, parts, True)
# set default values for optional arguments # set default values for optional arguments
prefix = None prefix = None
bgc = Door.defaultGraphic[0] bgc = MapExit.defaultGraphic[0]
fgc = Door.defaultGraphic[1] fgc = MapExit.defaultGraphic[1]
shape = Door.defaultGraphic[2] shape = MapExit.defaultGraphic[2]
# load graphic # load graphic
if 'graphic' in parts: if 'graphic' in parts:
if 'bgc' in parts['graphic']: if 'bgc' in parts['graphic']:
@ -474,12 +474,17 @@ class GameMap(object):
"""Read map data and return a Map object. If infile is not provided, then """Read map data and return a Map object. If infile is not provided, then
it will read from stdin. Otherwise, it should be a valid file name. it will read from stdin. Otherwise, it should be a valid file name.
Entering a map through stdin will be obsolete once testing is over.""" Entering a map through stdin will be obsolete once testing is over."""
data = None info = None
tryToRead = True tryToRead = True
yaml = ruamel.yaml.YAML()
yaml.register_class(Item)
yaml.register_class(Useable)
yaml.register_class(Door)
yaml.register_class(MapExit)
if infile != None: if infile != None:
try: try:
with open(infile, 'r') as f: with open(infile, 'r') as f:
data = f.read() info = yaml.load(f)
except OSError as e: except OSError as e:
print("The file could not be read.") print("The file could not be read.")
return None return None
@ -492,12 +497,13 @@ Entering a map through stdin will be obsolete once testing is over."""
tryToRead = False tryToRead = False
# Now what we do with the data # Now what we do with the data
info = ET.fromstring(data)
mat = None mat = None
layout = info.find('layout') if 'layout' not in info:
raise MapError('No layout in {0}.'.format(infile))
layout = info['layout']
if layout != None: if layout != None:
#print(layout.text) #print(layout.text)
match = GameMap.matrixRegex.match(layout.text.lstrip()) match = GameMap.matrixRegex.match(layout.lstrip())
if match == None: if match == None:
raise RuntimeError('Map read a file without a map matrix.') raise RuntimeError('Map read a file without a map matrix.')
mat = match.group() mat = match.group()
@ -550,7 +556,7 @@ list of lists of tuples."""
matrixStr = '' matrixStr = ''
else: else:
matrixStr = matrixStr[i:] matrixStr = matrixStr[i:]
else: # This shouldn't happen, so if it does, there was an error. else: # This should happen when it finishes?
raise RuntimeError("Unexpected token in map matrix: '{0}'".format(matrixStr)) raise RuntimeError("Unexpected token in map matrix: '{0}'".format(matrixStr))
y = len(mat) - 1 y = len(mat) - 1
@ -577,47 +583,34 @@ list of lists of tuples."""
@staticmethod @staticmethod
def loadThings(level, info, prevMap = None, preLoaded = False): def loadThings(level, info, prevMap = None, preLoaded = False):
"""load the things from the xml part of the map file.""" """load the things from the xml part of the map file."""
if 'openingText' in info.attrib: if 'openingText' in info:
level.openingText = info.attrib['openingText'] level.openingText = info['openingText']
if 'playerStart' in info.attrib: if 'playerStart' in info:
ps = info.attrib['playerStart'].split(',') level.playerStart = info['playerStart']
level.playerStart = (int(ps[0]), int(ps[1])) if 'description' in info:
if info.text != None: level.description = info['description']
level.description = info.text
# get map colors # get map colors
floorColors = info.find('floorColors') if 'floorColors' in info:
if floorColors != None: level.floorColors = info['floorColors']
level.floorColors = floorColors.text.lstrip().split() if 'wallColors' in info:
level.wallColors = info['wallColors']
if len(level.floorColors) == 0: if len(level.floorColors) == 0:
level.floorColors.append('#9F7F5F') level.floorColors.append('#9F7F5F')
wallColors = info.find('wallColors')
if wallColors != None:
level.wallColors = wallColors.text.lstrip().split()
if len(level.wallColors) == 0: if len(level.wallColors) == 0:
level.wallColors.append('#7F3F0F') level.wallColors.append('#7F3F0F')
# get things # get things
for node in info: if 'loadOnce' in info and not preLoaded:
if node.tag == 'loadOnce': for thing in info['loadOnce']:
# Things in the load-once section are only loaded the first #print(type(thing))
# time that the map is loaded, and saved in the player's level.addThing(thing, True)
# save file. if 'loadAlways' in info:
if preLoaded: for thing in info['loadAlways']:
continue #print(type(thing))
for node1 in node: level.addThing(thing)
if node1.tag == 'door': if thing.thingType == 'x' and prevMap == thing.exitid:
level.addThing(GameMap.__loadDoor(node1), True) level.playerStart = (thing.x, thing.y)
elif node1.tag == 'useable':
level.addThing(GameMap.__loadUseable(node1), True)
elif node1.tag == 'item':
level.addThing(GameMap.__loadItem(node1), True)
elif node.tag == 'exit':
level.addThing(GameMap.__loadExit(level, node, prevMap))
elif node.tag == 'door':
level.addThing(GameMap.__loadDoor(node))
elif node.tag == 'useable':
level.addThing(GameMap.__loadUseable(node))
@staticmethod @staticmethod
def __loadExit(level, node, prevMap): def __loadExit(level, node, prevMap):

View file

@ -32,12 +32,12 @@ layout: |
w w w w w w0 w w w w w w0
w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w0 w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w0
loadAlways: loadAlways:
- !Exit - !MapExit
id: 1 id: 1
location: [5, 10] location: [5, 10]
destination: testing/test2.yml destination: testing/test2.yml
name: upstairs name: upstairs
- !Exit - !MapExit
id: 2 id: 2
location: [21, 23] location: [21, 23]
destination: testing/test4.yml destination: testing/test4.yml

View file

@ -35,25 +35,25 @@ description: ''
floorColors: ['#9F7F5F'] floorColors: ['#9F7F5F']
wallColors: ['#7F3F0F'] wallColors: ['#7F3F0F']
loadAlways: loadAlways:
- !Exit - !MapExit
name: downstairs name: downstairs
location: [5, 10] location: [5, 10]
id: 1 id: 1
destination: testing/test1.yml destination: testing/test1.yml
graphic: {fgc: '#7F7F7F', shape: '#'} graphic: {fgc: '#7F7F7F', shape: '#'}
- !Exit - !MapExit
name: upstairs name: upstairs
location: [7, 10] location: [7, 10]
id: 2 id: 2
destination: testing/test3.yml destination: testing/test3.yml
graphic: {fgc: '#7F7F7F', shape: '#'} graphic: {fgc: '#7F7F7F', shape: '#'}
- !Exit - !MapExit
name: north name: north
location: [6, 1] location: [6, 1]
id: 3 id: 3
destination: testing/test3.yml destination: testing/test3.yml
graphic: {fgc: '#7F7F7F', shape: '#'} graphic: {fgc: '#7F7F7F', shape: '#'}
- !Exit - !MapExit
name: east name: east
location: [25, 14] location: [25, 14]
id: 4 id: 4

View file

@ -25,19 +25,19 @@ description: ''
floorColors: ['#9F7F5F'] floorColors: ['#9F7F5F']
wallColors: ['#7F3F0F'] wallColors: ['#7F3F0F']
loadAlways: loadAlways:
- !Exit - !MapExit
name: downstairs name: downstairs
location: [7, 10] location: [7, 10]
id: 2 id: 2
destination: testing/test2.yml destination: testing/test2.yml
graphic: {fgc: '#7F7F7F', shape: '#'} graphic: {fgc: '#7F7F7F', shape: '#'}
- !Exit - !MapExit
name: north name: north
location: [6, 1] location: [6, 1]
id: 3 id: 3
destination: testing/test2.yml destination: testing/test2.yml
graphic: {fgc: '#7F7F7F', shape: '#'} graphic: {fgc: '#7F7F7F', shape: '#'}
- !Exit - !MapExit
name: east name: east
location: [25, 14] location: [25, 14]
id: 4 id: 4

View file

@ -35,7 +35,7 @@ description: ''
floorColors: ['#9F7F5F'] floorColors: ['#9F7F5F']
wallColors: ['#7F3F0F'] wallColors: ['#7F3F0F']
loadAlways: loadAlways:
- !Exit - !MapExit
name: upstairs name: upstairs
location: [23, 22] location: [23, 22]
id: 2 id: 2