Skip to content
Advertisement

Setting the contents of one parameter of an object array equal to a string array in Python?

I’m making a grid-based game in which each tile and all of its associated information (collision, state, coordinates, etc.) are stored in a 2D list of Tiles. Tiles are the object I am using to store all of these parameters. I have a separate array of strings that stores what each tile is, for example “W” for wall or “F” for floor. I want to set the image parameter for each Tile to be equal to the string in the string array for that spot. This is the code I have so far:

#the code to put the strings from a text file into the first 2D list (strings)
with open("testtextfile.txt") as words:
    strings = [line.split() for line in words]

#the Tile class that stores all of the information about each tile.
class Tile:
    def __init__(self):
        self.x = x
        self.y = y
        self.image = "F"
        self.collision = "Open"

#creating the second 2D list (board) to store each tile
board = ([[Tile()] for y in range(levelheight)] for x in range (levelwidth))

#trying to set the image parameter of board equal to strings of the same x and y coordinates.
for x in range(levelwidth):
    for y in range(levelheight):
        board[x][y].image = strings[x][y]

I am currently getting an error on the last line that a “generator” object is not subscriptable. I know from other Stack Overflow threads that means I’m accidentally calling either x or y rather than the list of that index, but I don’t know why that is happening.

I basically have two questions:

How do I fix the generator error and set the image parameter equal to the equivalent object in strings?

and is this the best way to go about this in the first place? Is there a way to input the text file strings directly into the Tile list, without having to make a strings list at all?

Thank you for your help!

Advertisement

Answer

To your first question: bracketing issue – you need the square brackets on the outside of the list comprehension, like so board = list(([[Tile() for y in range(3)] for x in range (4)])). You will then be getting an error that ‘x’ is not defined. This is because you do not pass x or y to the Tile constructor. This can be done like so:

class Tile:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.image = "F"
        self.collision = "Open"

board = list(([[Tile(x, y) for y in range(3)] for x in range (4)]))

To your second question: I don’t believe your current approach is best practice (ideally, you would want to read through the input file once and fill your Tile array as you read through), but I also don’t think this will impact performance negatively in a meaningful way.

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