我正在使用C语言实现一个纸牌游戏。有许多类型的纸牌,每种纸牌都有很多信息,包括需要与之相关联的一些单独脚本化的操作。
假设有以下这样一个结构体(我不确定函数指针的语法是否正确)
struct CARD {
int value;
int cost;
// This is a pointer to a function that carries out actions unique
// to this card
int (*do_actions) (struct GAME_STATE *state, int choice1, int choice2);
};
我希望能够初始化一个静态数组,其中每个元素都是这个对象的一个实例。我猜应该是这样的:
int do_card0(struct GAME_STATE *state, int choice1, int choice2)
{
// Operate on state here
}
int do_card1(struct GAME_STATE *state, int choice1, int choice2)
{
// Operate on state here
}
extern static struct cardDefinitions[] = {
{0, 1, do_card0},
{1, 3, do_card1}
};
这种做法可行吗?我尝试避免使用大量的switch语句。
在结构体初始化时,我需要预先定义'do_cardN'函数吗?还是有一种内联定义它们的方法(类似于Python中的lambda函数)?
我需要从另一个文件以只读方式访问cardDefinitions - 对于这个问题,'extern static'是否正确?
我知道这是一个涉及多个问题的问题,但我确实对如何处理此事有些模糊。
谢谢。
编辑:
明确一下,我的目标是能够像这样进行操作:
int cost = cardDefinitions[cardNumber].cost;
或者int result = cardDefinitions[cardNumber].do_action(state, choice1, choice2);
可以避免到处使用庞大的switch语句。