I decided that before I would actually write the code for my planned inventory system in a game I am writing I would test it out in a small project first to make sure I know what needs to be done and if I needed to change anything. So I coded the new program and this is where I ended up at:
Main:
#include "player.h"
#include "item.h"
int main()
{
Item item;
Player player;
player.pMenu(item);
}
Player Class:
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
#include <vector>
#include "item.h"
using std::string;
using std::vector;
class Player
{
public:
Player(); //constructor
void pMenu(Item& item);
void addItem(unsigned int i);
void printInv(Item& item);
protected:
vector<int> pInv;
private:
int pISlots;
};
#endif
Player Imp:
#include <iostream>
#include <vector>
#include <string>
#include <conio.h>
#include "player.h"
#include "item.h"
using namespace std;
Player::Player()
{
pISlots = 5;
for (int i = 0; i < pISlots; i++)
{
pInv.push_back(0);
}
}
void Player::pMenu(Item& item)
{
bool quit = false;
unsigned int pChoice = 0;
while (!quit)
{
cout << "1) Add new item" << endl;
cout << "2) View inventory" << endl;
cout << "3) Quit" << endl;
cout << ">";
cin >> pChoice;
switch(pChoice)
{
case 1:
{
cout << endl;
cout << endl;
cout << "Please choose an item:" << endl;
for (int i = 1; i <= 5; i++)
{
cout << i << ") " << item.iGetName(i) << endl; //print item names
}
cout << ">";
cin >> pChoice;
addItem(pChoice);
cout << endl;
break;
}
case 2:
{
printInv(item);
break;
}
case 3:
{
quit = true;
break;
}
default:
{
cout << "invalid choice..." << endl;
break;
}
}
}
}
//Problem is in here
void Player::addItem(int i)
{
for (unsigned int i2 = 0; i2 < pInv.size(); i2++)
{
if (pInv[i2] != 0)
{
pInv.at(i2) = i;
break;
}
else if (i2 == pInv.size())
{
cout << "Player inventory is full!" << endl;
break;
}
}
}
void Player::printInv(Item& item)
{
for (unsigned int i = 0,i2 = 0; i < pInv.size(); i++,i2++)
{
cout << (i2+1) << ") " << item.iGetName(pInv.at(i)) << endl;
cout << (i2+1) << ") " << pInv.at(i) << endl; //print only vector element contents for debugging
}
_getch();
}
Item Class:
#ifndef ITEM_H
#define ITEM_H
#include <string>
using std::string;
class Item
{
public:
Item(); //constructor
string iGetName(unsigned int i);
};
#endif
Item Imp:
#include <string>
#include "item.h"
using std::string;
static string itemDB[6][2] =
{
{"0"," "},
{"1","Potion"},
{"2","Ale"},
{"3","Sword"},
{"4","Staff"},
{"5","Mace"}
};
Item::Item()
{
}
string Item::iGetName(unsigned int i)
{
return itemDB[i][1];
}
The problem I am having is that the item names are never printed when printInv() is called. I have not done much debugging, but what I have done points to my addItem() function not correctly setting the vector elements to the correct value and I am not sure why.
Edit:
Nevermind I found it. Should have been == 0 in the addItem function and not !=....