使用复合模式制作游戏菜单
Using Composite Pattern to make game menu
我正在使用复合模式制作游戏菜单。我想实现一个树结构的游戏菜单,其中一些树叶在我的状态机顶部推送新状态,另一个选项应该显示例如滑块来改变音量而不产生新状态,另一个(退出)应该关闭游戏通过 运行宁 sfml 方法。
有人能给我一个比使用 if/switch 中的值通过 operation() 方法将字符串或枚举返回到菜单状态到 运行 预期操作更好的主意吗?
这是使用 struct
:
的菜单状态示例 table
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 后要转换到的下一个状态(或菜单)。
我正在使用复合模式制作游戏菜单。我想实现一个树结构的游戏菜单,其中一些树叶在我的状态机顶部推送新状态,另一个选项应该显示例如滑块来改变音量而不产生新状态,另一个(退出)应该关闭游戏通过 运行宁 sfml 方法。
有人能给我一个比使用 if/switch 中的值通过 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 后要转换到的下一个状态(或菜单)。