I'm programming the board game Monopoly in Python. Monopoly has three types of land that the player can buy: properties (like Boardwalk), railroads, and utilities. Properties have a variable purchase price and rents for 6 conditions (0-4 houses, or a hotel). Railroads and utilities have a fixed price and rents based on how many other railroads or utilities you own.
I have a Game() class that contains three dictionary attributes, all whose key is the land parcel's position on the board from 0-39:
I did this because at certain points I want to iterate over the appropriate dictionary to see if the player owns other parcels of land in that dictionary; and also because the number of values differs.
Game() also has a tuple called space_types, where each value is a number representing a type of space (property, railroad, utility, luxury tax, GO, etc.). To find out what kind of space_type my player is sitting on:
space_type = space_types[boardposition]
I also have a Player() class with a method buy_property(), which contains a print statement that should say:
"You bought PropertyName for $400."
where PropertyName is the name of the space. But right now I have to use an if/elif/else block like so, which seems ugly:
space_type = Game(space_types[board_position])
if space_type is "property":
# pull PropertyName from Game.properties
elif space_type is "railroad":
# pull PropertyName from Game.railroads
elif space_type is "utility":
# pull PropertyName from Game.utilities
else:
# error, something weird has happened
What I'd like to do is something like this:
dictname = "dictionary to pull from" # based on space_type
PropertyName = Game.dictname # except .dictname would be "dictionary to pull from"
Is it possible in Python to pass the value of a variable as the name of an attribute to be referenced? I will also appreciate someone telling me I'm approaching this fundamentally wrong and suggesting a better way to go about it.
Use the getattr built-in:
PropertyName = getattr(Game, dictname)
http://docs.python.org/2/library/functions.html#getattr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With