我在用Python编写棋盘游戏专卖版。垄断有三种类型的土地,玩家可以购买:财产(如木板路),铁路和公用事业。房产的购买价格和租金在6种情况下都是可变的(0-4套房子或一家酒店)。铁路和公用事业有一个固定的价格和租金根据多少其他铁路或公用事业你拥有。
我有一个Game()类,它包含三个字典属性,所有这些属性的键都是从0到39的地块在板上的位置:
我这样做是因为在某些时候,我想遍历适当的字典,看看玩家是否拥有字典中的其他地块;同时也是因为值的数量不同。
Game()还有一个名为space-types的元组,其中每个值都是表示空间类型(property、railway、utility、luxury tax、GO等)的数字。要了解我的播放器所处的空间类型:
space_type = space_types[boardposition]
我还有一个Player()类,它有一个buy_property()方法,其中包含一个print语句,应该是:
"You bought PropertyName for $400."
其中PropertyName是空间的名称。但现在我必须使用这样的if/elif/else块,看起来很难看:
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
我想这样做:
dictname = "dictionary to pull from" # based on space_type
PropertyName = Game.dictname # except .dictname would be "dictionary to pull from"
在Python中,是否可以将变量的值作为要引用的属性的名称传递?我也会感谢有人告诉我,我正在接近这个根本错误,并建议一个更好的方式去做。
目前没有回答
相关问题 更多 >
编程相关推荐