(Python) Generating 2d list (map) from file

So I'm trying to get my program to read the elements of a text file and then create a 2d list with 20x30 with the elements of the text file. My expected output is essentially a game map in which I can find certain elements and move them around as needed.

The two functions I am still trying to do are as follows, but I cannot get it to do what I want to do, and I am a little shy, why can I?

def create_level(level):
     """ Create the level based off of reading positions of agents, player, buildings
water, etc..."""

     a_maze = []

     level_data = level.read()
     for r in range (0, ROWS, 1):
        a_maze.append ([])
        for c in range (0, COLUMNS, 1):
             a_maze[r].append (level_data)
     print(a_maze)



def load_level():
     while True:
          print("Enter the name/directory of the level file you wish to load\
     .txt or .lvl are the only accepted formats")

          level_in = input(">>: ")
          if (level_in.endswith(".txt") or level_in.endswith(".lvl")):
               try:
                    level = open(level_in, "r")

               except IOError:
                    print("Not a valid file")
          else:
               print("Not a suitable format for level")

          return level

      

+3


source to share


1 answer


What you are missing is file parsing. Everything open

in python creates a file object (in this case a text file object) that you can read or write. Assuming each slice in the map is a separate character and each line represents the full width of the map, here's how you can build the map line by line:

your_map = []
with open(level_in, 'r') as level:
    for line in level:
        your_map.append([a for a in line.split()])

      

Edit: If your map file has no delimiters between the fragments, just change the add line to:

your_map.append(list(line))

      

Padraic Cunningham also suggests that the assignment your_map

can be further condensed like this, with delimiters:

your_map = [line.split(your_delimiters) for line in level]

      

or so, without separators:

your_map = [list(line) for line in level]

      



Both of these will completely eliminate the need for a loop for

.

A few notes:

The keyword is with

used to automatically destroy objects such as file objects when you're done with them - much easier and safer than forgetting to call level.close () after you're done.

for line in level

iterates over the file object in stages, which will automatically terminate when the end of the file is reached.

[a for a in line.split]

is a list comprehension, but this is what you are creating a new list in which each index is one of the non-class tokens in your string.

This code I wrote above makes several assumptions - first, that your text file has the same number of chunks on each line, and second, that each chunk is separated from the previous tile by a space. Here's an example of what I imagine:

` ` ` o # ` . . .
` ` o # # # . . .
` o # # # # # . .

      

where any given character matches, for example, desert, water, etc.

+2


source







All Articles