I’m trying to figure out some OOP stuff with python and I’m running into a few problems. I’m trying to make a “game” that involves the player walking around a grid of rooms, with each room an instance of the Room class. If I wanted to make a big grid, instantiating each room would be a pain as I could potentially have to type in the same repetitive coordinate pattern for 64 different rooms, so I wanted to make a function that would do it for me, I’m running into problems figuring out how. Here’s the code I have:
class Room(object):
def __init__(self, x, y):
self.x = x
self.y = y
def generate_rooms():
names = [a,b,c,d]
locations = [[1,1],[1,2],[2,1],[2,2]] #this line could be a few for loops
for x in range(0,4):
names[x] = Room(locations[x][0],locations[x][1])
The idea was that this would create 4 Rooms named a, b, c, and d with the coordinates specified in locations. Python won’t let me do this because a, b, c, and d aren’t defined. In any implementation I’ve tried I’ve run into the problem that naming instances needs to be done with variable names, and I wouldn’t know how to generate those dynamically.
I’ve searched around a lot and it doesn’t really seem like automation of instantiation is really something people would want to do, which confuses me because it seems like it would really make sense in situations like this.
Any help on how to fix this or on how to accomplish this task in a better way is greatly appreciated!
You’re very close! The usual approach is to use a dictionary, and to use the names you want as dictionary keys. For example:
This way you can iterate over the rooms in several ways, for example: