[C++] Help me with basic organism simulation

Started by
4 comments, last by thor6136 12 years ago
Hi guys, i hope someone can help me here, i started programming few weeks ago so i am not that good, i know my code could be a lot better but i don't know enough. Only with time i will learn. So now as you know my little background lets go on problem. This is programmed in c++ with SDL api, but don't get confused by it, the problem does not lie in api but in c++.

So as you can see, i have a class organism and a class child. Child is born when organism eats one food (when coordinates are the same as foods coordinates function eat gets called) but before that happens, organism has to sense food, i do this with explaining how far he can sense (coordinates). Now, one organism can move and eat with no problem, but it gets tricky when child is born. He can move around freely as organism does but he only eats the same food as organism does and vica versa. I think the problem is in the part where i inheritated from class organism all the functions. Movements works well, eating too, but sense is not working properly. It might had to do smomething with the variable i or with variable senseFood. But i don't know how to fix it.

Basically i would like to make child that will eat freely (movement already works) and i think the problem lies in sense part and it has some connection with int i or bool senseFood.

here is link to load VS project: http://www.mediafire...8056mx4bru873vf

EDIT: if mods want to move topic somewhere else please do so


#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <string>
#include <sstream>
#include <time.h>
////////////////////////////// VARIABLES //////////////////////////////
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int SCREEN_BPP = 32;
const int FRAMES_PER_SECOND = 200;
const int ORGANISM_WIDTH = 20;
const int ORGANISM_HEIGHT = 20;
SDL_Surface *food = NULL;
SDL_Surface *organism = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;
SDL_Event event;
SDL_Rect foodPlaces[6];
int i;
////////////////////////////// CLASSES //////////////////////////////
class Timer
{
private:
int startTicks;
int pausedTicks;
bool paused;
bool started;
public:
Timer();
void start();
void stop();
void pause();
void unpause();
int get_ticks();
bool is_started();
bool is_paused();
};
class Organism
{
private:
int xVel, yVel, xOrganism, yOrganism;
bool diffusion;
int diffusionDowntime;
int diffusionStep;
bool senseFood;
public:
Organism();
void show();
void move();
void sense();
void eat();
void extract();
void grow();
void reproduct();
static bool makeChild;
};
class Food
{
private:
public:
bool startPosition;
static bool spawnNew;
static int xFood, yFood;
Food();
void show();
void spawnFood(int x);
};
class Child: public Organism
{
private:
int xVel, yVel, xOrganism, yOrganism;
bool diffusion;
int diffusionDowntime;
int diffusionStep;
bool senseFood;
public:
Child();
};
bool Organism::makeChild;
bool Food::spawnNew;
////////////////////////////// GENERAL //////////////////////////////
SDL_Surface *load_image(std::string filename)
{
SDL_Surface *loadedImage = NULL;
SDL_Surface *optimizedImage = NULL;
loadedImage = IMG_Load(filename.c_str());
if(loadedImage != NULL)
{
optimizedImage = SDL_DisplayFormat(loadedImage);
SDL_FreeSurface(loadedImage);
if(optimizedImage != NULL)
{
SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB(optimizedImage->format, 0, 0xFF, 0xFF));
}
}
return optimizedImage;
}
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, clip, destination, &offset );
}
bool init()
{
if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return false;
}
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
if(screen == NULL)
{
return false;
}
SDL_WM_SetCaption("KRNEKI", NULL);
return true;
}
bool load_files()
{
background = load_image("background.png");
food = load_image("food.png");
organism = load_image("organism.png");
if (background == NULL)
{
return false;
}
if (food == NULL)
{
return false;
}
if (organism == NULL)
{
return false;
}
return true;
}
void clean_up()
{
SDL_FreeSurface(background);
SDL_FreeSurface(organism);
SDL_FreeSurface(food);
SDL_Quit;
}
////////////////////////////// ORGANISM //////////////////////////////
Organism::Organism()
{
xOrganism = 380;
yOrganism = 280;
diffusionStep=0;
diffusion=true;
diffusionDowntime=40;
senseFood=false;
}
void Organism::sense()
{
if(foodPlaces.x < xOrganism+20+100 && foodPlaces.x > xOrganism-100 && foodPlaces.y < yOrganism+20+100 && foodPlaces.y > yOrganism-100)
{
senseFood=true;
}
else
{
senseFood=false;
i++;
if(i==6)
{
i=0;
}
}
}
void Organism::move()
{
if(senseFood==false)
{
if(diffusion==true)
{
xVel=(rand()%3)-1;
yVel=(rand()%3)-1;
diffusionStep=0;
diffusion=false;
}
if(diffusionStep < diffusionDowntime)
{
diffusionStep++;
}
if(diffusionStep==diffusionDowntime)
{
diffusion=true;
}
xOrganism += xVel;
yOrganism += yVel;
if(xOrganism + ORGANISM_WIDTH > SCREEN_WIDTH || xOrganism < 0)
{
xVel = - xVel;
}
if(yOrganism + ORGANISM_HEIGHT > SCREEN_HEIGHT || yOrganism < 0)
{
yVel = - yVel;
}
}
if(senseFood==true)
{
if(xOrganism < foodPlaces.x)
{
xVel = 1;
}
if(xOrganism > foodPlaces.x)
{
xVel = - 1;
}
if(xOrganism == foodPlaces.x)
{
xVel = 0;
}
if(yOrganism < foodPlaces.y)
{
yVel = 1;
}
if(yOrganism > foodPlaces.y)
{
yVel = - 1;
}
if(yOrganism == foodPlaces.y)
{
yVel = 0;
}
xOrganism += xVel;
yOrganism += yVel;
}
}
void Organism::show()
{
apply_surface(xOrganism, yOrganism, organism, screen);
}
void Organism::eat()
{
Food foodObj;
if(xOrganism == foodPlaces.x && yOrganism == foodPlaces.y)
{
foodObj.spawnNew=true;
makeChild=true;
}
else
{
foodObj.spawnNew=false;
}
}
////////////////////////////// FOOD //////////////////////////////
Food::Food()
{
spawnNew=false;
startPosition=true;
}
void Food::show()
{
Organism organismObj;
if(spawnNew==true)
{
spawnFood(i);
apply_surface(foodPlaces.x, foodPlaces.y, food, screen);
spawnNew=false;
}
if(startPosition==true)
{
spawnFood(0);
spawnFood(1);
spawnFood(2);
spawnFood(3);
spawnFood(4);
spawnFood(5);
startPosition=false;
}
apply_surface(foodPlaces[0].x, foodPlaces[0].y, food, screen);
apply_surface(foodPlaces[1].x, foodPlaces[1].y, food, screen);
apply_surface(foodPlaces[2].x, foodPlaces[2].y, food, screen);
apply_surface(foodPlaces[3].x, foodPlaces[3].y, food, screen);
apply_surface(foodPlaces[4].x, foodPlaces[4].y, food, screen);
apply_surface(foodPlaces[5].x, foodPlaces[5].y, food, screen);
}
void Food::spawnFood(int x)
{
foodPlaces[x].x=1+(rand()%600);
foodPlaces[x].y=1+(rand()%400);
foodPlaces[x].w=20;
foodPlaces[x].h=20;
}
////////////////////////////// CHILD //////////////////////////////
Child::Child()
{
diffusionStep=0;
diffusion=true;
diffusionDowntime=40;
}
////////////////////////////// TIMER //////////////////////////////
Timer::Timer()
{
startTicks = 0;
pausedTicks = 0;
paused = false;
started = false;
}
void Timer::start()
{
started = true;
paused = false;
startTicks = SDL_GetTicks();
}
void Timer::stop()
{
started = false;
paused = false;
}
void Timer::pause()
{
if((started == true) && (paused == false))
{
paused = true;
pausedTicks = SDL_GetTicks() - startTicks;
}
}
void Timer::unpause()
{
if(paused == true)
{
paused = false;
startTicks = SDL_GetTicks() - pausedTicks;
pausedTicks = 0;
}
}
int Timer::get_ticks()
{
if(started == true)
{
if(paused == true)
{
return pausedTicks;
}
else
{
return SDL_GetTicks() - startTicks;
}
}
return 0;
}
bool Timer::is_started()
{
return started;
}
bool Timer::is_paused()
{
return paused;
}
////////////////////////////// MAIN //////////////////////////////
int main(int argc, char *args[])
{
Timer fps;
Organism organismObj;
Food foodObj;
Child childObj;
srand(time(0));
bool quit = false;
if(init() == false)
{
return 1;
}
if(load_files() == false)
{
return 1;
}
while (quit == false)
{
fps.start();
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
{
quit = true;
}
}
apply_surface(0, 0, background, screen);
organismObj.move();
organismObj.sense();
organismObj.eat();
organismObj.show();
foodObj.show();
if(organismObj.makeChild==true)
{
childObj.move();
childObj.sense();
childObj.eat();
childObj.show();
}
if(SDL_Flip(screen) == -1)
{
return 1;
}
if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
{
SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
}
}
clean_up();
return 0;
}


I am sorry if a code is too long, i hope you read it through :S
Advertisement
I did not take the time to analyze the code completely or the logic behind it, but a few things poped in my head while scanning it.

First is that you have a kind of mix between basic procedural code (C, global functions/variables) for the "main game structure" and object-oriented code (C++) with classes and such for your objects.
Second is that you have a derived class (Child) with the same member variable name as the base class (Organism). It's valid in C++ if you would actually cast a derived class pointer as a base class and wanted to use a different variables in this case, but usually it's a very bad idea. You don't need to redefine a second copy of the variables in the derived class, simply keep using those of the base class (as you did with the methods). Looking more carefully, I see your Child class actually don't have ANY different variable defined, and not a single member function added or redefined except the constructor. Why are you using inheritance in this case instead of just creating a second instance of the Organism class with different values (that could be passed in the constructor parameters or something)?
Finally, I really don't like your use of "static" member variables. Are you aware doing this means each instance of the class will use the same variable? In other word, every "Organisms" will sense food all together when only one sense it? Usually if you want to do this, it's gonna be a variable that would be handled not by the class itself, but on a previous level by what is using your class like your main game. You could simply define this variable globally or in your case on the start of the main() function. Anyway, what is sure is that this is wrong:
Food foodObj;
foodObj.spawnNew=true;

Since spawnNew is a static member, you are not forced to create a instance of Food to use it. You could simply do Food::spawnNew = true;

edit:
In Food::show, why do you create an instance of Organism if you don't actually use it afterward? Your next step is probably to turn your project into dynamic allocation with new/delete and containers instead of having every objects static. It work for now, but you won't be able to keep at it like this for long.
Thank you for your answer, i have still so much to learn, i will reorganise my code tomorrow and read more tutorials on dynamic allocation, thanks again!

Oh and btw, the problem is not in not compiling, it compiles fine. I should explain it more. It's just that both child and organism can eat only the same food, if for example child is away from food and organism is in the zone where he can sense food and wants to eat it (it should go to food coordinates) but he doesn't want to, something bugs him, he starts twitching madly, but when both child and organism are in the same zone when they can sense food, than both can eat but only the same food. They can move around independently but they cannot eat independently. Maybe i should take a little bit different approach to writing this.

Edit: ok, i fixed that, thanks to you :)
I have another questions, lets say we have a code like this


#include <iostream>
#include <vector>

using namespace std;

class ClassA
{
public:
void function_a();
};


int main(void)
{
ClassA classAObj;
vector < ClassA* > myvector;
myvector.push_back( classAObj ); // this part doesn't work

myvector[ 0 ] -> function_a();

return 0;
}


How do you save an object into a vector and then use it through vector to call a function?
Your vector stores pointers, so you'd have to pass the address of a ClassA object. For instance:


int main(void)
{
ClassA classAObj;
vector < ClassA* > myvector;
myvector.push_back( &classAObj );
myvector[ 0 ] -> function_a();
return 0;
}

However, storing raw pointers in a container is an advanced technique, it is easy to cause undefined behaviour unless you know how to correctly manage pointers. The code above stores a pointer to a local object in the container. If the container outlives the local (it doesn't in that last example) then you could easily corrupt memory by writing to data members of the pointer.

Looking at your original post, once we remove the unnecessary child class your classes can be treated as "value objects". That is they have simple copying semantics. So I would store them in containers by value:

std::vector<Food> food;
std::vector<Organism> colony;

food.push_back(Food());
colony.push_back(Organism());
colony.push_back(Organism());
Thank you very much rip-off, this opened up a little bit different perspective :>

This topic is closed to new replies.

Advertisement