使用复合图案制作游戏菜单



我正在使用复合模式制作游戏菜单。我想实现一个树状结构的游戏菜单,其中一些叶子在我的状态机顶部推动新的状态,另一个在选项中应该显示滑块,例如在不创建新状态的情况下更改音量,另一种(退出(应该通过运行sfml方法关闭游戏。

有人能给我一个比使用if/switch中的值将字符串或枚举by operation((方法返回到菜单状态以运行预期操作更好的主意吗?

下面是一个使用struct:的菜单状态表示例

typedef void (*Function_Pointer)(); // Declares a synonym for Function_Pointer
struct Table_Entry
{
char  expected_selection;
char  * prompt;
Function_Ptr processing_function;
};
// Forward declarations
void Turn_On_Lights();
void Turn_Right();
void Open_Treasure();
// State table
static const Table_Entry menu1[] = 
{
{'1', "Turn on lights", Turn_On_Lights},
{'2', "Turn right (pivot)", Turn_Right},
{'3', "Open Treasure", Open_Treasure},
};
static size_t menu_entry_quantity = 
sizeof(menu1) / sizeof(menu1[0]);
void Display_Menu()
{
for (unsigned int i = 0, i < menu_entry_quantity; ++i)
{
std::cout << menu1[i].expected_selection
<< ". "
<< menu1[i].prompt
<< "n";
}
std::cout << "Enter selection: ";
}
void Execute_Menu_Selection(char selection)
{
for (unsigned int i = 0, i < menu_entry_quantity; ++i)
{
if (selection == menu1[i].expected_selection)
{
(*menu1[i].processing_function)();
break;
}
}
}

上述代码允许您更改条目数量或条目内容,而无需重新测试功能。(不错(

由于数据是静态常量,因此可以直接访问,并且在程序启动前不需要初始化。

您可以使用";过渡";列或成员。例如,当给定转换ID时,列出要转换到的下一个状态(或菜单(。

最新更新