Skip to content
Advertisement

How to correctly parse a tiled map in a text file?

I’m making a RPG with Python and pygame for a school project. In order to create the few maps, I have chosen the Tile Mapping techniques I have seen in some tutorials, using a *.txt file.

However, I have to cut some sprites (trees, houses, …) into several pieces. The problem is that I’m running out of characters to represent them all!

I also remember that it’s possible to take several characters as one (ex : take "100" as one an not as one "1" and two "0"s) and/or to put spaces between characters in the file (e.g. "170 0 2 5 12 48" which is read as six sprites).

But I really don’t know how to adapt my program to do this way. I’m pretty sure that I need to modify the way the file is read, but how?

Here’s the reading function :

JavaScript

Advertisement

Answer

I think what you want is str.split():

JavaScript

split without any arguments will join all consecutive whitespace (including tabs 't' and newlines 'n') into a single split. For example:

JavaScript

Note that the “sprites” don’t have to be the same length, so there’s no need for fill characters like extra 0s or *s. You can also simplify using a list comprehension:

JavaScript

Alternatively, consider using a comma-separated value format – Python has a whole module (csv) for that:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement