• 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
thor6136

[C++] Help me with basic organism simulation

5 posts in this topic

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: [url="http://www.mediafire.com/?8056mx4bru873vf"]http://www.mediafire...8056mx4bru873vf[/url]

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

[CODE]
#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[i].x < xOrganism+20+100 && foodPlaces[i].x > xOrganism-100 && foodPlaces[i].y < yOrganism+20+100 && foodPlaces[i].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[i].x)
{
xVel = 1;
}
if(xOrganism > foodPlaces[i].x)
{
xVel = - 1;
}
if(xOrganism == foodPlaces[i].x)
{
xVel = 0;
}
if(yOrganism < foodPlaces[i].y)
{
yVel = 1;
}
if(yOrganism > foodPlaces[i].y)
{
yVel = - 1;
}
if(yOrganism == foodPlaces[i].y)
{
yVel = 0;
}
xOrganism += xVel;
yOrganism += yVel;
}
}
void Organism::show()
{
apply_surface(xOrganism, yOrganism, organism, screen);
}
void Organism::eat()
{
Food foodObj;
if(xOrganism == foodPlaces[i].x && yOrganism == foodPlaces[i].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[i].x, foodPlaces[i].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;
}
[/CODE]

I am sorry if a code is too long, i hope you read it through :S
0

Share this post


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

Share this post


Link to post
Share on other sites
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 :)
0

Share this post


Link to post
Share on other sites
I have another questions, lets say we have a code like this

[CODE]
#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;
}
[/CODE]

How do you save an object into a vector and then use it through vector to call a function?
0

Share this post


Link to post
Share on other sites
Your vector stores pointers, so you'd have to pass the address of a ClassA object. For instance:
[code]

int main(void)
{
ClassA classAObj;
vector < ClassA* > myvector;
myvector.push_back( &classAObj );
myvector[ 0 ] -> function_a();
return 0;
}
[/code]
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:
[code]
std::vector<Food> food;
std::vector<Organism> colony;

food.push_back(Food());
colony.push_back(Organism());
colony.push_back(Organism());
[/code]
1

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