我对c++编码相当陌生,我正在为我正在开发的文本RPG开发菜单系统。您可以查看统计信息、查看库存、查看物品统计信息和丢弃物品。但是,在丢弃物品后,丢弃的物品所在的插槽仍然是空的,并且在游戏中,丢弃对象 2 是没有意义的,然后对象编号 3 仍然是对象 3。对象 3 应变为 2。所以我想知道如何使用我当前的代码来做到这一点。
#include <iostream>
#include <string>
using namespace std;
bool running = 1;
void titleFunc();
void newGameFunc();
void menuFuncNav();
void menuFuncInfo();
void menuFuncItems();
string itemNames[] = {"Iron Short Sword", "Iron Long Sword", "Iron Two-Handed Sword", "Iron War Hammer", "Iron Mace", "Iron Dagger", "Wooden Staff", "Wooden Shield", "Oak Shortbow", "Oak Longbow", "Oak Crossbow", "Hard Leather Chest-Piece", "Hard Leather Leggings", "Soft Leather Chest-Piece", "Soft Leather Leggings", "Cloak"};
short playerItemCount = 0;
int userInput = 0;
int talkInput = 0;
int playerInfo[3];
int playerLocation = 0;
const int MAX_ITEMS = 100;
int playerItems[MAX_ITEMS][11];
void menuFuncItems()
{
int i = 0;
for( int i = 0; i < playerItemCount; i++ )
{
cout << i+1 << ": ";
cout << itemNames[playerItems[i][0]];
cout << endl;
}
cin >> i;
if( playerItems[i - 1][1] == 1 )
{
cout << "Press 1 to view stats." << endl;
cout << "Press 2 to equip." << endl;
cout << "Press 3 to discard." << endl;
cin >> userInput;
cout << endl;
if( userInput == 1 )
{
cout << "Name: " << itemNames[playerItems[i - 1][0]] << endl;
cout << "Physical Attack:" << playerItems[i - 1][2] << endl;
}
else if( userInput == 2 )
{
}
else
{
playerItems[i - 1][0]--;
playerItems[i - 1][0]--;
cout << "Item discarded." << endl;
}
}
因此,在此代码中,玩家丢弃第一个物品栏栏中的物品。
- 铁长剑
- 木盾
- 硬质皮革胸件
- 硬皮紧身裤
第 1 项后,应变为:
- 木盾
- 硬质皮革胸件
- 硬皮紧身裤
对不起,如果我在帖子中做错了什么。这是我在这个网站上的第一篇文章。:)谢谢。
您可以执行以下操作
for ( int ( *p )[11] = playerItems + i; p != playerItems + playerItemCount; ++p )
{
std::copy( *p, *p + 11, *( p - 1 ) );
}
--playerItemCount;
如果替换
int playerItems[MAX_ITEMS][11];
跟
std::vector<int> playerItems; // assuming you store all the items for a given player here
或
std::vector<std::vector<int>> playerItems; // if you want the 2D array for whatever implementation you have
然后,擦除元素就像调用playerItems.erase(it);
一样简单(其中it
是一个迭代器"指向"要删除的元素。
或者,如果您想要更快的插入/删除(但更慢的随机访问),您可以使用 std::list
。 如果你真的想玩得开心,你可以将它们存储在一个std::map
中,并将项目的名称作为键(而不是使用索引在另一个数组中对项目名称字符串进行)。