• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
MatiasMunk

Classes and Objects

11 posts in this topic

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.

0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites
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?
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites

 

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
    // [...]
  }
 
0

Share this post


Link to post
Share on other sites

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())
{


}
0

Share this post


Link to post
Share on other sites

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.

0

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  
Followers 0