Reputation: 75
I am working with two ranges to place tiles in a 2d game, so I've created a 'tilemap'...
tilemap = [ [TILE for w in range(MAPWIDTH)] for h in range(MAPWIDTH)]
this works... now I want to attach instances of a class called 'piecemap' that corresponds to the tilemap. To do this I have a class called Piece that looks like this...
class Piece():
otherstuff = "string"
location = [0,0]
My question is how can I load the "w" in width range and the "h" in height range into the "location" attribute using list comprehension? Currently my effort (that doesn't work) looks like this...
piecemap = [[Piece.location[0] for w in range(MAPWIDTH)],[Piece.location[1] for h in range(MAPHEIGHT)]
I know it's wrong but no idea how to make it right! any help?
Upvotes: 3
Views: 873
Reputation: 11590
From what I read, I assume the location is an attribute of each Piece instance
(not a class attribute). The same goes for the name
attribute (maybe).
Therefore, I would set the location when creating such objects:
class Piece():
otherstuff = "string"
def __init__(self,x,y):
self.location = [x, y]
# self.otherstuff = name # add it to the parameters if that's the case
piecemap = [[Piece(w,h) for h in range(MAPWIDTH)] for w in range(MAPHEIGHT)]
Upvotes: 2
Reputation: 10135
I don't know for what you need Piece class, but you can retrieve all locations using zip
function:
piecemap = zip(range(MAPWIDTH), range(MAPHEIGHT))
Upvotes: 1
Reputation: 168616
class Piece():
otherstuff = "string"
location = [0,0]
That is a very odd-looking class. You have class attributes otherstuff
and location
, as if every Piece
ever created would occupy the same location.
Rather, you probably want instance attributes, like so:
class Piece:
def __init__(self, x, y, name="Unspecified"):
self.location = [x,y]
self.otherstuff = name
Then your list comprehension looks like:
tilemap = [ [Piece(w, h) for w in range(MAPWIDTH)] for h in range(MAPWIDTH)]
Upvotes: 5
Reputation: 11267
Don't you want something like this:
tilemap = [ (w, h) for w in range(MAPWIDTH) for h in range(MAPWIDTH)]
MAPWIDTH = 3
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)
Then you can create your "Piece" objects?
Upvotes: 1
Reputation: 986
You need something like this:
>>> [[x,y] for x in range(3) for y in range(2)]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]
In your case it probably:
piecemap = [[Piece.location[0], Piece.location[1]] for w in range(MAPWIDTH)] for h in range(MAPHEIGHT)]
But I'm not sure what you're really expecting
Upvotes: 1