【发布时间】:2015-08-23 01:05:23
【问题描述】:
最近我一直在为基于文本的游戏开发库存系统,该系统使用库存系统的全局数组和相应的函数来读取所述数组中的真假。我遇到的问题是这个,我用来修改数组的函数
void playerGet(bool items[], int itemNumber) //this function takes an assigned argument of the array indices variable, and changes that array indices from true, to false.
{
items[itemNumber] = true;
}
仅在其所在函数的范围内修改数组。该数组在 .cpp 文件中定义,如下所示:
void inventoryArray(bool items[]) //This function establishes all the items in the game, the true false statement expresses whether or not the item is in the player's inventory.
{
items[WEAPON_RELIC_RIFLE] = false;
items[WEAPON_SCALPEL] = false;
items[MISC_ACTION_FIGURE] = false;
items[MISC_FIRE_EXTINGUISHER] = false;
items[MISC_LIFE_RAFT] = false;
}
然后在 .h 文件中声明如下:
void inventoryArray(bool items[]);
数组中使用的枚举在头文件中定义,如下所示:
enum equipment //This declares a list of enums for each item in the game, consumables, not included.
{
WEAPON_RELIC_RIFLE, // = 0
WEAPON_SCALPEL, // = 1
MISC_ACTION_FIGURE, // = 2
MISC_FIRE_EXTINGUISHER, // = 3
MISC_LIFE_RAFT, // = 4
MAX_EQUIPMENT
};
读取库存数组的函数是这样的:
void twoScavengerCombat(bool items[])
{
for (int item = 0; item < MAX_EQUIPMENT; ++item)
{
if (items[item] == true) //if true proceed
{
switch (item)
{
case 0: //if array indices identifier = 0, print relic rifle
cout << "1: Use the Relic Rifle\n";
break;
case 1:
cout << "2: Use the Scalpel\n";
break;
case 2:
break;
case 3:
cout << "3: Use the Fire Extingusher\n";
break;
case 4:
cout << "4: Use the Life Raft\n";
break;
default:
cout << "Error";
break;
}
}
else
cout << "Option Unavailible\n"; //if false print Option Unavailible
}
编译后,声明了数组和枚举头文件,主文件如下所示:
int toolSearch()
{
bool items[MAX_EQUIPMENT];
inventoryArray(items);
playerGet(items, 0);
}
void twoScavengerCombat(bool items[])\\ declared in this file, but since its just above here i left it as a forward declaration to save space
int main()
{
toolSearch();
twoScavengerCombat(items);
return 0;
}
理想情况下,这会产生结果:使用遗物步枪 选项不可用 选项不可用 选项不可用 选项不可用
但它会产生 5 个选项不可用。我错过了什么?
【问题讨论】:
-
在
toolSearch()中声明的items是该函数的本地函数,将覆盖任何全局声明的数组。 -
@SawyerAdlaiVierra-Hatch
inventoryArray没有声明任何数组。尽管看起来确实如此,但事实并非如此。事实上,你的代码 sn-ps 都没有声明一个全局数组。 -
@SawyerAdlaiVierra-Hatch 因为除非我弄错了,否则函数定义了数组和其中的项目你错了。该函数在哪里声明了一个数组?您所做的只是传递一个指向
bool的指针,并给定该指针,访问该指针的偏移量。同样,没有进行数组声明。 -
很抱歉不得不告诉你这个,但你似乎在尝试一些超出你能力范围的事情。我尊重你挑战自己的愿望,但你不会因为太过分而学到任何东西。您必须先尝试一些更简单的东西。我建议您从玩弄您可以设计的最简单的代码开始,它可以对全局数组执行任何操作。一旦你完美地工作,你就可以在游戏中添加使用你学到的东西。
-
@SawyerAdlaiVierra-Hatch 见这里:ideone.com/1ilFKW 这演示了一个全局数组的声明,并有一个设置前两个条目的函数。