Sign in to follow this  
MatiasMunk

Classes and Objects

Recommended Posts

MatiasMunk    114

Hey, I'm all new to classes, and I've done the best I could.

 

How could I go by making this code better?

 

Main.cpp:

http://pastebin.com/JX2HPXtG

 

itemClass.cpp:

http://pastebin.com/2qZDZtit

 

itemClass.h:

http://pastebin.com/Hhd9PziW

 

monsterClass.cpp:

http://pastebin.com/ZVJ2KDbV

 

monsterClass.h:

http://pastebin.com/3wbXkb61

 

playerClass.cpp:

http://pastebin.com/cdhFhyA4

 

playerClass.h:

http://pastebin.com/Tk1B5aJr

 

Any help is much appreciated !

 

Regards,

Matias.

Share this post


Link to post
Share on other sites
MatiasMunk    114

Those classes looks like a good start.

 

The first thing I'd ask you to think about is the class suffix. For example, std::string is a class but it isn't called std::stringClass. Consider simple class names like "player", "monster" and "item". A common convention is to use Uppercase for class names, so Player - and lowercase for function and variable names, so "Player player" or "Monster pig".

 

The next thing to think about is maybe using constructors instead of having setters for all the fields. One problem with adding setters is that it can break encapsulation and defeat the purpose of making all the fields private.

 

Also, consider adding member functions for interesting properties that aren't exactly fields. For example, you're checking if a monster is alive by testing whether it's HP is greater than zero.  You can encapsulate this logic by adding a member function, bool isAlive(), and then the client code doesn't need to worry about the Monster's HP directly.

Thank you so much for the advice.

 

I would think that the function bool isAlive is really useful, but how would I go by adding it to the program? Perhaps in the monster class? Or what would be better?

 

Also what exactly do you mean by constructors?

Share this post


Link to post
Share on other sites
alvaro    21246
I am not going to read a whole bunch of beginner's code just for fun, but I did look at your Main.cpp. The obvious thing that can be improved is readability. You have a bunch of comments that would not be needed if your variables had descriptive names. So instead of
        //Temporary Name Holder
        string x;
        //Choice
        int c;
        //Random Monster Selection
        int v;
        //Temporary damage
        int attack;
you could have
  string tmp_name_holder;
  int choice;
  int random_monster_selection;
  int tmp_damage_from_attack;
More things:
* It's best to declare variables at the first point where they are needed. That will provide the reader the context to understand what the descriptive name means. And yes, you should think of your code as something that people read.
* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables.
* Including a file called "Includes.h" is a generally a bad idea. It won't matter for a program of this size, but the point of this exercise is learning good practices. So think of what dependencies you really have and include those. Otherwise, all of your code will depend on all of your other code and you will have to recompile all of your code whenever anything changes. In my project at work, full recompilation takes 15 minutes, and that's with a parallel compilation that devotes 10 processes to it.

OK, I did look through some of the other files. Your classes are mostly just holders for data, which probably means you are not thinking in terms of what operations you want to support on them, kind of missing the point of objects and classes. Also, some of your methods have surprising semantics:
void playerClass::setGold(int gold)
{
        playerClass::gold += gold;
}
Why does `setGold' add to the amount of gold instead of setting it to the value I just passed? How about calling it `addGold' instead?

Share this post


Link to post
Share on other sites
MatiasMunk    114

I am not going to read a whole bunch of beginner's code just for fun, but I did look at your Main.cpp. The obvious thing that can be improved is readability. You have a bunch of comments that would not be needed if your variables had descriptive names. So instead of

        //Temporary Name Holder
        string x;
        //Choice
        int c;
        //Random Monster Selection
        int v;
        //Temporary damage
        int attack;
you could have
  string tmp_name_holder;
  int choice;
  int random_monster_selection;
  int tmp_damage_from_attack;
More things:
* It's best to declare variables at the first point where they are needed. That will provide the reader the context to understand what the descriptive name means. And yes, you should think of your code as something that people read.
* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables.
* Including a file called "Includes.h" is a generally a bad idea. It won't matter for a program of this size, but the point of this exercise is learning good practices. So think of what dependencies you really have and include those. Otherwise, all of your code will depend on all of your other code and you will have to recompile all of your code whenever anything changes. In my project at work, full recompilation takes 15 minutes, and that's with a parallel compilation that devotes 10 processes to it.

OK, I did look through some of the other files. Your classes are mostly just holders for data, which probably means you are not thinking in terms of what operations you want to support on them, kind of missing the point of objects and classes. Also, some of your methods have surprising semantics:
void playerClass::setGold(int gold)
{
        playerClass::gold += gold;
}
Why does `setGold' add to the amount of gold instead of setting it to the value I just passed? How about calling it `addGold' instead?

 

Hello, first I would like to thank you, for your advice on the variable names and positions.

 

I don't really know how to work arrays, I can't seem to get it working, but perhaps you or someone on here could give me a general idea on how to place it all in one block instead of 4?

 

Yeah, I've heard that Includes.h is a bad idea, it was also just something I added to make it a little easier while practising ;)

 

About the setGold, at the time of creation I couldn't put my tongue on the word "add" for some reason ;P (I'm Danish)

Changed it to addGold. Thank you;)

 

 

 

 

 

Those classes looks like a good start.

 

The first thing I'd ask you to think about is the class suffix. For example, std::string is a class but it isn't called std::stringClass. Consider simple class names like "player", "monster" and "item". A common convention is to use Uppercase for class names, so Player - and lowercase for function and variable names, so "Player player" or "Monster pig".

 

The next thing to think about is maybe using constructors instead of having setters for all the fields. One problem with adding setters is that it can break encapsulation and defeat the purpose of making all the fields private.

 

Also, consider adding member functions for interesting properties that aren't exactly fields. For example, you're checking if a monster is alive by testing whether it's HP is greater than zero.  You can encapsulate this logic by adding a member function, bool isAlive(), and then the client code doesn't need to worry about the Monster's HP directly.

Thank you so much for the advice.

 

I would think that the function bool isAlive is really useful, but how would I go by adding it to the program? Perhaps in the monster class? Or what would be better?

 

Also what exactly do you mean by constructors?

 

Edited by MatiasMunk

Share this post


Link to post
Share on other sites
Buckeye    10747

In a couple places (e.g., monsterClass), you have empty constructors, and an instance is initialized by (e.g.) setMonster.

 

You may want to consider setting default values in the constructor. Otherwise, if you create a monster and either forget to initialize it, or  access it before it's initialized, you may get some strange behavior: e.g., you call getHP before hitpoints has been set. Don't assume that all values will be initialized to 0 (or to any particular value).

 

// Constructor - set default parameters
monsterClass::monsterClass(void)
{
    monsterClass::name = "<unnamed>";
    monsterClass::hitpoints = 20;
    monsterClass::experience = 10;
    monsterClass::gold = 10;
    monsterClass::damage = 0;
}


Seconding Alvaro's suggestion to name variables with descriptive names: it may seem like you're going to be doing a lot of typing, but, if you use an IDE like Visual Studio with intellisense, as you begin typing a variable name, a dropdown list of possible completions will shorten the process AND, by selecting from the dropdown, you'll ensure the spelling is correct. It will be worth the effort.

Edited by Buckeye

Share this post


Link to post
Share on other sites
MatiasMunk    114

In a couple places (e.g., monsterClass), you have empty constructors, and an instance is initialized by (e.g.) setMonster.

 

You may want to consider setting default values in the constructor. Otherwise, if you create a monster and either forget to initialize it, or  access it before it's initialized, you may get some strange behavior: e.g., you call getHP before hitpoints has been set. Don't assume that all values will be initialized to 0 (or to any particular value).

 

// Constructor - set default parameters
monsterClass::monsterClass(void)
{
    monsterClass::name = "<unnamed>";
    monsterClass::hitpoints = 20;
    monsterClass::experience = 10;
    monsterClass::gold = 10;
    monsterClass::damage = 0;
}

Seconding Alvaro's suggestion to name variables with descriptive names: it may seem like you're going to be doing a lot of typing, but, if you use an IDE like Visual Studio with intellisense, as you begin typing a variable name, a dropdown list of possible completions will shorten the process AND, by selecting from the dropdown, you'll ensure the spelling is correct. It will be worth the effort.

 

Oh yes, I see. I will start doing this.

However, like Alvaro said

"* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables."

 

How can I go by doing this?

Share this post


Link to post
Share on other sites
Buckeye    10747

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...

void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}


Then:

 

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

Edited by Buckeye

Share this post


Link to post
Share on other sites
MatiasMunk    114

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...

void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}

Then:

 

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

 

So I should be creating an attackMonster class and make a function that I can call in main like attackMonster(pig) and it would attack the pig?

Share this post


Link to post
Share on other sites
alvaro    21246

 

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...

void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}

Then:

 

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

 

So I should be creating an attackMonster class and make a function that I can call in main like attackMonster(pig) and it would attack the pig?

 

 

No, attackMonster is a function, not a class. Different concepts.

 

About the idea of using an array of monsters, first I have to understand what your code is doing. You have a notion of what a pig is, which is something with 5 hit points, 5 for stamina, an amount of gold between 1 and 5 and a random damage between 0 and 0 (???). If that's the case, I would create a class MonsterType which contains those parameters that can be used to create a specific pig. Then you can have an array of MonsterType objects, which I would call `bestiary'.

 

int random_in_range(int min, int max) {
  return min + std::rand() % (max - min + 1);
}

class MonsterType {
  std::string name;
  int hitpoints;
  int experience;
  int min_gold;
  int max_gold;
  int min_damage;
  int max_damage;

  MonsterType(std::string name, int hitpoints, int experience, int min_gold, int max_gold, int min_damage, int max_damage)
    : name(name),
      hitpoints(hitpoints),
      experience(experience),
      min_gold(min_gold),
      max_gold(max_gold),
      min_damage(min_damage),
      max_damage(max_damage) {
  }

  Monster create_instance() const {
    return Monster(name,
                   hitpoints,
                   experience,
                   random_in_range(min_gold, max_gold),
                   random_in_range(min_damage, max_damage));
  }
};

// [...] somewhere in Main.cpp                                                                                                        
  MonsterType const bestiary[4] = {
    MonsterType("Pig", 5, 5, 1, 5, 0, 0),
    MonsterType("Blob", 7, 5, 4, 15, 0, 1),
    MonsterType("Goat", 10, 7, 4, 18, 0, 2),
    MonsterType("Sheep", 20, 22, 7, 26, 0, 3)
  };
 
  // [...]
 
  int random_bestiary_index = std::rand() % 4;
  Monster monster = bestiary[random_bestiary_index].create_instance();
  while (monster.isAlive() && player.isAlive()) {
    // Here goes your single copy of the loop
    // [...]
  }
 

Share this post


Link to post
Share on other sites
jHaskell    1856

This isn't complete code, but it should get you pointed in the right direction.  If you're still having trouble working with arrays, post the code you're trying to get working with a description of the problems you're having.

//Best to declare the size of your arrays for a variety of reasons
//This size will get used in a variety of locations, as you'll see
const int numMonsters = 4;
monsterClass monsters[numMonsters];

//Initialize all monsters
monsters[0].setMonster("Pig", 5, 5, rand() % 5 + 1, rand() % 1);
...
monsters[numMonsters-1].setMonster...


//No adding 1 here.  Arrays are zero based
//An array of 4 monsters will have indices 0, 1, 2, and 3
int randomMonster = rand() % numMonsters;

//Now combat can commence on monsters[randomMonster]
//And you have only one block of code for fighting monsters
//This can be pushed to a separate function as well
while(monsters[randomMonster].isAlive() && player.isAlive())
{


}

Share this post


Link to post
Share on other sites
alvaro    21246

I originally had in mind code like jHaskell's when I mentioned arrays. But then I read the code more carefully and realized that he doesn't have four monsters that the player is fighting: There seem to be 4 monster types, and a new instance of the monster is created in each attack. That's why my code is more involved.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this