我正在用 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”是否正确?
我知道这是很多问题的综合体,但我对如何解决这个问题真的有点模糊。
Thanks.
Edit:
需要明确的是,我的目标是能够做类似的事情
int cost = cardDefinitions[cardNumber].cost;
or
int result = cardDefinitions[cardNumber].do_action(state, choice1, choice2);
而不是到处使用巨大的 switch 语句。