最近,我一直在为一个基于文本的游戏开发一个库存系统,它使用全局数组作为库存系统,并使用相应的函数在所述数组中读取真假。我遇到的问题是,我用来修改数组的函数
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个不可用的选项。我遗漏了什么?
发布于 2015-08-22 18:01:41
你会想要
//bunch of #include<> directives
bool items[MAX_EQUIPMENT];
int toolSearch()
{
inventoryArray();
playerGet( 0);
}
void twoScavengerCombat()
...
// other functions here
int main()
{
toolSearch();
twoScavengerCombat();
return 0;
}
注意,bool items[MAX_EQUIPMENT];
不是在函数中定义的。它在文件的顶部是独立的,在它下面定义的任何东西都是纯视图的。这就是全球化的含义。任何人和每个人都可以访问它,如果他们知道它在哪里,或者你用extern
语句告诉他们它在哪里。它是在程序启动时创建的(即使在main之前也是如此,如果变量的初始化逻辑有问题,这会导致一些非常有趣的调试),并且只有在程序运行时才会死掉。
Lightness Races in Orbit delves a bit deeper here,但更关心的是使全局变量扩展到单个文件之后。
没有必要将项目传递到任何函数中,因为每个人都可以看到items
,缺点是只有一个items
,所以如果有多个玩家拥有不同的项目列表,您就会遇到问题。
您可能需要查看std::vector (可调整大小的数组)和std::map (这将允许您按名称items["sword"].attackFoe(foe);
查找项目)和std::set (这使得查看播放器拥有的内容(if (items.find("Vorpal Hand Grenade") != items.end()) BlowStuffUp();
)非常容易,而不必每次搜索每个项目。
https://stackoverflow.com/questions/32162236
复制相似问题