我正在编写一个简单的游戏来学习获得更多的C++经验,我有一个想法,我觉得多态几乎可以工作,但没有.在这个游戏中,Party
移动相当线性地通过一个Map
,但偶尔可以Fork
在路上遇到一个.fork(基本上)是一个std::vector
.Originally我打算在Party
成员函数中编写如下代码:
if(!CurrLocation->fork_.empty()) // Loop through forks and show options to the player, go where s/he wants else (CurrLocation++)
但我想知道以下某些变体是否会更好:
CurrLocation = CurrLocation->getNext();
使用Fork实际上是从Location派生的,并且重载了一些新功能getNext()
.但在后一种情况下,在location
(低层次结构)将不得不提出的信息给用户,而不是"通过这个备份",我不觉得是优雅的,因为它夫妻一个location
来UserInterface::*
.
你的意见?
通过添加一个间接级别可以解决所有问题.我将使用您建议的变体,并通过允许getNext接受解析方向选择的对象来将Party与Party分离.这是一个例子(未经测试):
class Location; class IDirectionChooser { public: virtual bool ShouldIGoThisWay(Location & way) = 0; }; class Location { public: virtual Location * GetNext(IDirectionChooser & chooser) { return nextLocation; } virtual Describe(); private: Location * nextLocation; }; class Fork : public Location { public: virtual Location * GetNext(IDirectionChooser & chooser) { for (int i = 0; i < locations.size(); i++) if (chooser.ShouldIGoThisWay(*locations[i])) return locations[i]; } virtual Describe(); private: vectorlocations; }; class Party : public IDirectionChooser { public: void Move() { currentLocation = currentLocation->GetNext(GetDirectionChooser()); } virtual IDirectionChooser & GetDirectionChooser() { return *this; } virtual bool ShouldIGoThisWay(Location & way) { way.Describe(); cout << "Do you want to go that way? y/n" << endl; char ans; cin >> ans; return ans == 'y'; } };