Jump to content

  • Log In with Google      Sign In   
  • Create Account

Attempting a "Simple" Vector-Based Inventory Test


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
17 replies to this topic

#1 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 13 November 2012 - 06:50 AM

I am having an issue getting a vector-based inventory system to work. I am able to list the items in the inventory, but not able to allow a user-selected item to be accessed. Here is the code:

struct aItem
{
	string  itemName;
	int	 damage;
	bool operator==(aItem other)
	{
		if (itemName == other.itemName)
			return true;
		else
			return false;
	}
};
int main()
{
	int selection = 0;

	aItem healingPotion;
	healingPotion.itemName = "Healing Potion";
	healingPotion.damage= 6;
	aItem fireballPotion;
	fireballPotion.itemName = "Potion of Fiery Balls";
	fireballPotion.damage = -2;
	aItem testPotion;
	testPotion.itemName = "I R NOT HERE";
	testPotion.damage = 9001;
	int choice = 0;
	vector<aItem> inventory;
	inventory.push_back(healingPotion);
	inventory.push_back(healingPotion);
	inventory.push_back(healingPotion);
	inventory.push_back(fireballPotion);
	cout << "This is a test game to use inventory items. Woo!" << endl;
	cout << "You're an injured fighter in a fight- real original, I know." << endl;
	cout << "1) Use an Item. 2) ...USE AN ITEM." << endl;
        cin >> selection;
switch (selection)
	{
	case 1:
		cout << "Which item would you like to use?" << endl;
		int a = 1;
		for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ )
		{
			cout << "Item " << a << ": " <<  inventory[index].itemName << endl;
			a+= 1;
		}
		cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
		cin >> choice;

^^^^ Everything above this line, works. I assume that my problem is the if statement, but I cannot figure out where I am going wrong in my syntax, or if there is a better way to do what I am doing.

if (find(inventory.begin(), inventory.at(choice), healingPotion.itemName) != inventory.end())
			cout << "You used a healing potion!";
		else
			cout << "FIERY BALLS OF JOY!";
		break;
	case 2:
		cout << "Such a jerk, you are." << endl;
			break;
	}

I need for the player's choice to affect the message displayed. Here's a sample output of the 1st snippet:

Item 1: Healing Potion
Item 2: Healing Potion
Item 3: Healing Potion
Item 4: Potion of Fiery Balls
MAKE YOUR CHOICE.
Choice:

From there, the player can type 1-4, and what I would like is for the number (minus 1, to reflect the vector starting at zero) to be passed to the find, which would then determine (in this small example) if the item at inventory[choice - 1] is a healing potion. If so, display "You used a healing potion!" and if it is not, to display "Fiery balls of joy". Obviously, to turn this into a "real" inventory system, it'll need much more tweaking- this excercise is to help me learn how to search vectors... next will be removing the item once it is used (really looking forward to that, too... )

Any advice you can offer would be awesome. Thanks for slogging through all this!

Edited by VladimirMarenus, 13 November 2012 - 07:32 AM.


Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 13368

Like
0Likes
Like

Posted 13 November 2012 - 07:28 AM

`selection' is set to 0 at the beginning of the code, and then you have a `switch(selection)'. That doesn't seem right... `selection' can only possibly 0 at that point.

#3 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 13 November 2012 - 07:31 AM

`selection' is set to 0 at the beginning of the code, and then you have a `switch(selection)'. That doesn't seem right... `selection' can only possibly 0 at that point.


Sorry, missed a line! see edit- "cin >> selection;"

#4 NightCreature83   Crossbones+   -  Reputation: 2833

Like
0Likes
Like

Posted 13 November 2012 - 09:10 AM

Right nevermind I have my python hat on today and not my C++ hat Posted Image

The problem you are having is that the iterator returned by inventory.at(choice) not necessarily needs to be inventory.end(), if you change the end into an inventory.at(choice) it should work. Be careful though as choice can index outside of your inventory vector as maximum choice is defined as inventory.size() + 1, see the output loop above in which you create the choice menu.

Also more info on find here

Edited by NightCreature83, 13 November 2012 - 09:15 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#5 KnolanCross   Members   -  Reputation: 1317

Like
0Likes
Like

Posted 13 November 2012 - 09:37 AM

I don't really understand why you are trying to use "find" in there, the best approach would be adding a itemType on the "aItem" struct/class and look directly at the choice - 1 (don't forget to check if choice is > 1 and <= inventory.size()) to check if itemType == SOME_POTION_IDENTIFIER.

If you really want to use the find, the first thing that I see that I believe is wrong is that the search range of find doesn't include de second argument, and this second argument is returned in case of a search failure. So you should replace the != inventory.end() by inventory.at(choice).
Also, I do not think find will be able to compare the value the way you are passing to it.
How is the aItem struct/class implemented?


Edited by KnolanCross, 13 November 2012 - 09:39 AM.

Currently working on a scene editor for ORX (http://orx-project.org), using kivy (http://kivy.org).


#6 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 13 November 2012 - 11:25 AM

How is the aItem struct/class implemented?


The implementation is mostly to teach myself vectors. At the end of it all, I want a simple program that will add an item to a vector, show a list of items, allow the player to pick one, execute the correct code for the item selected (not simply by looking at the choice, as these items are consumable- choice 3 won't always be a healing potion, for example), and then delete the item after it is used. I am attempting a larger project, but didn’t want my difficulties with this bit of code muddling up with difficulties from the rest of the code! So I have this running as a self-contained solution. Once I’m comfortable with managing vectors, I’ll design a couple more “simulations”, and then hold my breath and pray as I turn it into actual game code and merge it with my tiny project!

I realize that I'm probably making a mountain range out of a molehill... but I'm trying to learn as I go!

#7 KnolanCross   Members   -  Reputation: 1317

Like
1Likes
Like

Posted 13 November 2012 - 11:39 AM

Well, as I said, comparing by name is a bad idea, it is slow and prone to error. If you using char* of char[], they won't compare as you may want. For instance:
[source lang="cpp"] char* a = "hello world"; char b[] = "hello world"; if (a == b){ printf("Ok"); } else{ printf("Nope."); }[/source]
Will print "Nope.", which is not intuitive at all (it has to do with memory areas used by a and b).

Using find is also not needed as you know which item you need to check, even if you get it working (I believe that if you use Strings, aItem is a struct and they are the first element declared in the struct it will work as intended), you will be tossing away processing (as you need to find the element in the array).

I keep my opinion of adding an itemType, each type is an ID that represents the item type (armor, potion, quest item and so on). So you just check if the item at that point have the potion id. The main advantage of a vector over a list is that you can directly accesss an item... take advantage of it =D

Edited by KnolanCross, 13 November 2012 - 11:40 AM.

Currently working on a scene editor for ORX (http://orx-project.org), using kivy (http://kivy.org).


#8 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 13 November 2012 - 12:10 PM

I think I see what you mean about the ItemType- going to give that a whirl! I'll let you know how it goes.

#9 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 13 November 2012 - 01:04 PM

...The main advantage of a vector over a list is that you can directly accesss an item... take advantage of it =D


Oh, my God. That made it so much easier. I ended up with:

cout << "This is a test game to use inventory items. Woo!" << endl;
cout << "You're an injured fighter in a fight- real original, I know." << endl;
cout << "1) Use an Item. 2)  ...USE AN ITEM." << endl;
cin >> selection;
int a = 1;
switch (selection)
{

case 1:
  cout << "Which item would you like to use?" << endl;

  for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ )
  {
  
   cout << "Item " << a << ": " <<  inventory[index].itemName << endl;
   a+= 1;
  }
  cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
 
  cin >> choice;
  //This checks for an invalid response. Add in non-int
  if ((choice - 1) >= inventory.size())
  {
   cout << "Choice out of bounds. Stop being a dick." << endl;
  }
  else
  {
 
   if(inventory[choice - 1].itemType == 01)
   {
    cout << "You used a healing potion!" << endl;
   }
 
   else if(inventory[choice-1].itemType == 02)
   {
    cout << "FIERY BALLS OF JOY!" << endl;
   }
 
   else
   {
    cout << "Invalid Item type" << endl;
   }
  }
  break;
case 2:
  cout << "Why do you have to be so difficult? Pick 1!" << endl;
  break;

This code compiles and runs- but is it good code, in your opinion?

My next task is to figure out how to delete the item from the vector and move everything up to fill the spot. -_- That'll come later, I am still basking in the delight of this working. Thanks!

#10 Yrjö P.   Crossbones+   -  Reputation: 1412

Like
0Likes
Like

Posted 13 November 2012 - 07:00 PM

The code is artificial, and more importantly, it doesn't do anything (except printing stuff). Thus there's very little that could be wrong with it on low level, and in the absence of context it's hard to say anything about design issues.

Just some cosmetic things I'd point out to a student:
- "a" is useless because you could be printing "index+1" instead
- any variables like "choice" should be defined as close as possible to where you actually use them for the first time
- instead of writing "choice-1" everywhere, sanitize the number once to the value you actually want (-=1)
- finally, magic numbers like "01" and "02" are generally bad; in a real program you would likely use an enum and descriptive labels like ITEM_HEALTHPOT or ITEM_FIREPOT

Which compiler are you using? If it's new enough to have some C++11 features, they can make your life easier in small (and occasionally big) ways.

#11 NightCreature83   Crossbones+   -  Reputation: 2833

Like
0Likes
Like

Posted 14 November 2012 - 03:03 AM

Using find is also not needed as you know which item you need to check, even if you get it working (I believe that if you use Strings, aItem is a struct and they are the first element declared in the struct it will work as intended), you will be tossing away processing (as you need to find the element in the array).

Actually his implementation will always work regardless of where the string is stored in the same struct as he is providing an == operator which find will call for the data type you give it.

Also another tip: instead of doing index++, try to use ++index. In this case it doesn't matter but it is a good habit to have, so when you only want to increment and decrement a variable by 1 ever and nothing else write ++var or --var. The reason behind this is that the ++operator or --operator(both pre and post increment or decrement) can be overloaded and do a lot of work that is unnecessary in that particular case.

Edited by NightCreature83, 14 November 2012 - 03:04 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#12 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 14 November 2012 - 03:28 AM

The code is artificial, and more importantly, it doesn't do anything (except printing stuff). Thus there's very little that could be wrong with it on low level, and in the absence of context it's hard to say anything about design issues.

Just some cosmetic things I'd point out to a student:
- "a" is useless because you could be printing "index+1" instead
- any variables like "choice" should be defined as close as possible to where you actually use them for the first time
- instead of writing "choice-1" everywhere, sanitize the number once to the value you actually want (-=1)
- finally, magic numbers like "01" and "02" are generally bad; in a real program you would likely use an enum and descriptive labels like ITEM_HEALTHPOT or ITEM_FIREPOT

Which compiler are you using? If it's new enough to have some C++11 features, they can make your life easier in small (and occasionally big) ways.


Thank you very much. I realize the artificial nature. This is a glorified snippet that is mostly designed to teach me how to use and modify vectors. The suggestions I was looking for are exactly the ones you mentioned- just good housekeeping and dev habits in general. I'm learning this myself, so I'm not able to get the benefit of a teacher standing over me going "No- that won't work in six months when you're doing something better."

I'm using Microsoft VS 2012- I'm not sure what "C++11 features" are, but if they make my life easier, I'd certainly be interested in hearing about them!

EDIT: I've applied the changes you suggested, and the code reads much better.

EDIT 2: The next step for me is to turn this into a class, I suppose!

Edited by VladimirMarenus, 14 November 2012 - 04:00 AM.


#13 Khatharr   Crossbones+   -  Reputation: 3007

Like
0Likes
Like

Posted 14 November 2012 - 04:23 AM

What do you mean by turning it into a class?

Also, please don't place extended logic inside switch statements. It's a nightmare to read. Check this out:

[source lang="cpp"]void processItemSelect() { int choice = -1; while(choice == -1) { cout << "Which item would you like to use?" << endl; for(vector<aItem>::size_type index = 0; index < inventory.size(); ++index) { cout << "Item " << index + 1 << ": " << inventory[index].itemName << endl; } cout << "MAKE YOUR CHOICE." << endl << "Choice: "; cin >> choice; --choice; if((choice >= inventory.size()) || (choice < 0)) { choice = -1; cout << "Choice out of bounds. Stop being a dick." << endl << endl; } } switch(inventory[choice].itemType) { case ITEM_POTION: cout << "You used a healing potion!" << endl; break; case ITEM_BALLS: cout << "FIERY BALLS OF JOY!" << endl; break; default: cout << "Invalid Item type" << endl; break; }}int main() { int selection = 0; cout << "This is a test game to use inventory items. Woo!" << endl << "You're an injured fighter in a fight- real original, I know." << endl << "1) Use an Item. 2) ...USE AN ITEM." << endl; cin >> selection; switch (selection) { case 1: processItemSelect(); break; case 2: cout << "Why do you have to be so difficult? Pick 1!" << endl; break; } return 0;}[/source]

Finally, do not prefix numeric literals with a zero. That's the notation for the octal numbering system:

10 is 10.
010 is 8.

Edited by Khatharr, 14 November 2012 - 05:10 AM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#14 Yrjö P.   Crossbones+   -  Reputation: 1412

Like
0Likes
Like

Posted 14 November 2012 - 04:31 AM

I'm using Microsoft VS 2012- I'm not sure what "C++11 features" are, but if they make my life easier, I'd certainly be interested in hearing about them!

C++11 is the newest C++ standard. VS2012 supports about half of the new features. Most of the features are not relevant to a beginner, but some of them are seriously worth learning immediately. Together, they almost feel like you are writing in a different language.

The auto keyword (lets you type "auto" in many situations where you'd otherwise have to type something painful like "std::vector<std::pair<int, myType>>::iterator_type")
http://en.wikipedia....#Type_inference
Range-based for loop (use whenever you can):
http://en.wikipedia....-based_for-loop
nullptr (use whenever you can):
http://en.wikipedia....ointer_constant

Lambdas are a bit more obscure than the above, but not actually hard. If you have the capacity, check them out. Standard containers like vector, standard algorithms and lambdas together are magic.
http://en.wikipedia....and_expressions

Smart pointers, unique_ptr and smart_ptr: you *have to* eventually learn these or you won't be coding good C++11. However, you don't need to touch them at all until you start using "new" and start seeing naked pointers like int* or SomeType* in your code. Naked pointers are evil. Smart pointers get rid of them.
http://en.wikipedia....i/Smart_pointer

The biggest thing that you unfortunately don't have yet in VS2012 is uniform initialization.

#15 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 14 November 2012 - 04:47 AM

What do you mean by turning it into a class?


Well, this standalone exercise was standalone because I realized that I had no idea how to create an inventory system- this is all written from scratch (I'm still enough of a beginner to feel like a "Master Programmer" for getting it to work Posted Image ). I actually have a very basic text RPG with some functional abilities, and wanted to isolate this painful learning experience from the working code! The end result of this is to create a class with functions that I can call from within the game code, in order to perform inventory functions without cluttering up the main .cpp.

#16 Khatharr   Crossbones+   -  Reputation: 3007

Like
0Likes
Like

Posted 14 November 2012 - 04:48 AM

Gaah, 2 posts while I was editing. Derp.

Ah, I see. You just mean implementing it. I'm glad to hear the you're enjoying your successes. Posted Image

Edit - Occurred to mention it while I was outside - You would probably be better off placing the usage message in the item's effect processing. That way you just have to proc the item effect of the selected item instead of switching to print the usage message.

Edited by Khatharr, 14 November 2012 - 05:03 AM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#17 VladimirMarenus   Members   -  Reputation: 107

Like
0Likes
Like

Posted 14 November 2012 - 05:05 AM

Gaah, 2 posts while I was editing. Derp.

Ah, I see. You just mean implementing it. I'm glad to hear the you're enjoying your successes. Posted Image

Edit - Occurred to mention it while I was outside - You would probably be better off placing the usage message in the item's effect processing. That way you just have to proc the item effect of the selected item instead of switching to print the usage message.


Thank you! :)

I see... and thank you for your code example- that looks much more friendly than what I'm hacking together! Got a lot to learn, but getting there...

#18 Khatharr   Crossbones+   -  Reputation: 3007

Like
1Likes
Like

Posted 14 November 2012 - 05:08 AM

As long as you keep going you get 'there' in the end. ;)
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS