/*
Evolution by Dale Swanson September 30th, 2007
Simulates evolution, sort of.
*/

using namespace std;
#include <iostream>
#include <fstream>
#include <math.h>

char basen[100] = "V"; //needed for fnamecomb
char ext[10] = ".csv"; //needed for fnamecomb
char fname[100]; //needed for fnamecomb

int pop[100000][20]; //main array to store population, see below for explanation
int poptot; //total population
int turns; //number of turns (days)
int popnum; //the number of the population you are on (will be used for the first index of pop[][]
int matureage; //the age needed to be considered mature, set in setup() below
int ssex, sreq, sfood, sspeed, ssize, sage, spreg, senergy, sid, senviro; //constants to be used to access second index in pop.
int sim; //how simular another animal needs to be to be considered same species,, what to divide by, set below
int needfood; //how much food needed daily
int foodsun; //how much food plants can get from the sun
int fert; //odds 1 in fert of getting pregnant
int litter; //average size of litter
int mutrate; //rate of mutation
int displayrate; //rate to display results
int foodpenalty; //penalty for being a omnivore
int sexpenalty; //penalty for being a hemaphidite
int environment; //varible to represent the environment, the closer to this the animal is the better of it'll be, it'll change with time.
int disasterodds; //odds of a disaster
int minplant; //min ammount of plant that is left
int asexpenalty; //penalty for being asexual
int displaymode; //how to display results

int debug[100][10]; //debug, will store the ammount of time spent in each part


/*
Things to do:
increase speed, reduce loops in loops.  Mate, and death.  Preg check.
why do plants grow so big, speed and size have equal value right?
why is male 1, favored with almost no 2's?
make plants more resilent to being eating to death, animal can only eat to his daily requirment, and can't eat a plant with less than 10%
cap the ammount of energy a plant can store
population totals for each trait
stats[20][5] first index would go with the second index in pop, and you use the same ssex to use it.  The second would store specfic stats, stats[1][1] would store total number of males, stats[3][2] would store total carnivores
small size, fast speed dominates

lack of diveristy in species is due to a lack of diversity in enviroment,  As annoying as it'll be you have to add locations.  A simple 2 dimensionaly grid will work.  have them move around, based on speed.  can only interact with animals they meet.  You also need to have the enviroment vary.  I say just make a layor to go over the allready exsisting varibles, keep the global varibles and keep the varying like they do now, but also let the layor on top equal the plus and minuses to that global varible.
Layor on top (need to think of a name, like net, or sheild).  Let the individual cells be effected by near by cells (similar to pirate2), but probably not worth letting it be globally effected, too much of a slow down, and not needed,  Each cell is effected by a 10 cell radius.  On each turn let each cell move towards the average of that 10 cell radius, by a bit.  Then obviously make random things occur to bring them back.  The key I suppose would be to have certain areas that pretty much remain constant.  Maybe a third layor that dosen't change (or only changes very slowly).  Possible name is offset.  Constant offset, and enviromental offset.  Array like this offset[3][10000][10000], representing the number of the offset then the x y grid.  A question is how many animals can one cell support.  Perhaps lots, and then perhaps that would be a better way to limit the population.  The less animals can live in a cell the more cells you'll need.  I think way less than 10000x10000 might work, like 100 by 100 = 10000, possibly even less than that.  It's going to make reproduction more complicated, although it's allready shitty, and needs to be fixed.  I guess an animal stays with mom until it is mature, then it's independent.
The animals stats will describle x and y, it'll only migrate if it's hungry.  You can't do 1 cell per speed, that's too fast, but then how to handle low speeds.  Figure some sort of desire to move * speed, if random numer 1-1000 is < that that then they move 1 cell.

Also need to limit speed and size, somehow.  You can't let them just grow endlessly.  There are some practical limits to size/speed benifits.  Let the food needed grow as the cube of size and speed, but some how make it so the effect isn't really bad until around 500 or so.

I think one of the main problems is simply scale, there are trillions of species, each millions or billions or members.  There's simply too many to simulate.  Then the order of time, again billions of years, lastly the ammount of info stored in DNA, which is absurb.

You really need to add mutation rate as a stat and make it inherited.

Try starting them all out from a single organism, just for fun

*/

/*
populations will be stored in pop array.  Each pop has a number, and then the value of his stats are stored in the next index.  Each turn go through and 
Stats:
ssex = 1;
senviro = 2;
sfood = 3;
sspeed = 4;
ssize = 5;
sage = 6;
spreg = 7;
senergy = 8;
sid = 9;
sreq = 10;
1 sex, 1-male, 2-female, 3-asexual, 4-hermaphrodite
2 enviromental constant, the closer the animal's eviro const is the the global eniro const (int environment), the better it'll be
3 food source, 1-sun, 2-plants, 3-animals, 4-either (more energy in animals than plants.  Not sure if speed should raise energy)
4 speed/metabolism rate
5 size
6 age
7 preg, 0 for no, any number is how many kids it has
8 energy, how much food it has inside it for it to use
9 id of parent, used to deduct food from the parent, and whatever else needed
10 required energy daily
(speed/metobolism rate will determine how well animals kill, but also how fast plants repair/heal. 

How will you classify species, and handle mutations?  Can any animal reproduce with any other, if not at what point can they not?  Maybe they can with any animal within certain ranges:
sex = opposite
type = same
food source = same
speed = +/- 10%
size = +/- 10%
As for mutations let any offspring have the following chances:
sex 50/50
type 1/10000 different
food source 1/10000
size +/- 1%
speed +/- 1%

Perhaps intelligence should be another stat, to go with speed/size.  Problem being how to simulate it.  I suppose a slow but large and smart animal (us), should be pretty well off.
Will each animal keep his ID number, or give it up upon death?  If he gives it up you'll have to move them all when one dies, although that shouldn't be too hard, also you can write it to a history file on the disk each time.  Maybe a buffer array, then output that when it start to fill, to speed things up.
every turn (day) have each animal meet another at random, if it's mateable then they can mate, if not then maybe one eats the other.  The animal who's turn it is will have the upper hand, which means runing away or something.  If they are immobile (plant) then they will meet others based on speed still, simulating spores or something, but they won't have any effect if the other animal isn't a possible mate.

Radically different approach to all this:
give each animal a whole string of DNA, that is stored in the second index.  Like real DNA allow 4 values, give each value different functions, sometimes multiple functions.  Allow new DNA spots, with whatever effects.  Need big book of what each spot does.  Example:
DNA:
1 3
2 2
3 1
4 3
5 4
6 1
Book:
book[x][y] x - spot, y - value
spot 1, value 1, stat 4 + 10, stat 5 + 2
spot 1, value 2 stat 4 + 4, stat 5 - 10
spot 1, value 3 stat 4 -3, stat 5 + 15
spot 1, value 4 stat 4 -10, stat 5 +10

spot 1 would probably be sex, with no other effects.  You could only mate with animals with same number of spots, or maybe very close (otherwise how would new ones be able to mate).  Maybe 100 or so could just be gen'd at the start, and then each animal at start would only use first 10 or so, but then the ability to use new ones or stop using old ones would mutate.
*/

int ran(int min, int max)
{
	int k; //used for killing some random numbers (k is a random letter I picked, but let's pretend I picked it to stand for kill)
	int range; //range from you min and max
	int result = 0; //this is your real random number that will be used to return
	range = (max - min) + 1;
	if (rand() == 138) srand(rand() + clock()); 
	//1 in 32k odds to reseed the RNG uses both a rand number and the clock (clock isn't seconds, it's system ticks, faster than seconds) 
	if (rand() == 138) 
	//basicly 1 in 50 chance of looping a wasting some random numbers
	{
		for (k = rand() - rand(); k < rand(); k++)//comes up with a number to loop from about 9 to 35 times
		{
			rand(); //wastes some random numbers
		}
	}
	result = min + int(range * rand() / (RAND_MAX + 1));
   return result;
}

void fnamecomb() //combines basen + the time + ext into fname
{//requires the global char's basen, ext, fname
	time_t tsec; //sets time to tsec
	time(&tsec);
	int tnum;
	char sttim[100];
	tnum = int(tsec);
	
	itoa(tnum, sttim, 10); //sets the string sttime to the value of the current time
	strcpy (fname, basen); //combines the 3
	strcat (fname, sttim);
	strcat (fname, ext);
	return;
}

void display()
{//displays the population
	int displayodds; //odds that each animal will get displayed
	int x;
	cout<<"\nDay - "<<turns;
	cout<<"\nStats:";
	cout<<"\nmature - "<<matureage<<", sim - "<<sim<<", food - "<<needfood<<", sun - "<<foodsun<<", fert - "<<fert<<", litter - "<<litter<<", dis - "<<disasterodds;
	cout<<"\nmutrate - "<<mutrate<<", display - "<<displayrate<<", foodpenalty - "<<foodpenalty<<", sexpenalty - "<<sexpenalty<<", environment - "<<environment;	
	cout<<"\npopnum,  sex,  food,  speed,  size,  age,   preg,  req,   energy, enviro, id";
	
	if (displaymode == 0) displayodds = 900; //display odds is how many on average to display
	if (displaymode == 1) displayodds = 25;
	for (popnum = 1; popnum <= poptot; popnum++)
	{//go through each animal, and do what needs to be done
		if (poptot > displayodds && ran(1, poptot / displayodds) > 1) continue;
		printf("%s %5d, %2d, %3d, %6d, %6d, %6d, %4d, %6d, %9d, %4d, %5d", "\nA#", popnum, pop[popnum][ssex], pop[popnum][sfood], pop[popnum][sspeed], pop[popnum][ssize], pop[popnum][sage], pop[popnum][spreg], pop[popnum][sreq], pop[popnum][senergy], pop[popnum][senviro], pop[popnum][sid]);
	}
	cout<<"\npopnum,  sex,  food,  speed,  size,  age,   preg,  req,   energy, enviro, id";
	cout<<"\nmature - "<<matureage<<", sim - "<<sim<<", food - "<<needfood<<", sun - "<<foodsun<<", fert - "<<fert<<", litter - "<<litter<<", dis - "<<disasterodds;
	cout<<"\nmutrate - "<<mutrate<<", display - "<<displayrate<<", foodpenalty - "<<foodpenalty<<", sexpenalty - "<<sexpenalty<<", environment - "<<environment;	
}

void spawn(int mom, int dad)
{//creates a new animal
	int statnum; //to go through each stat
	int momdad; //who they will inheirt the trait from
	poptot++;
	for (statnum = 1; statnum <= 5; statnum++)
	{//go through the first 5 stats and give it it's mom's or dad's stat
		momdad = ran(1, 2); //decide mom or dad
		if (momdad == 1)
		{// mom
			pop[poptot][statnum] = pop[mom][statnum]; //get the stat from mom
		}
		else
		{//dad
			pop[poptot][statnum] = pop[dad][statnum]; //get the stat from dad
		}
	}
	//variate the  size/speed/enviro by mutrate
	//add or subtract random ammount of current ammount/mutrate
	pop[poptot][ssize] += ran(-1 * ((pop[poptot][ssize] / mutrate) + 1), ((pop[poptot][ssize] / mutrate) + 1));
	pop[poptot][sspeed] += ran(-1 * ((pop[poptot][sspeed] / mutrate) + 1), ((pop[poptot][sspeed] / mutrate) + 1));
	pop[poptot][senviro] += ran(-1 * ((pop[poptot][senviro] / mutrate) + 1), ((pop[poptot][senviro] / mutrate) + 1));
	
	//set the stuff that dosen't variate, age, preg, inital energy, mom
	pop[poptot][sage] = 0;
	pop[poptot][spreg] = 0;
	pop[poptot][senergy] = ((pop[poptot][ssize] * pop[poptot][sspeed]) / needfood); //one days worth food for free
	pop[poptot][sid] = mom;
	
	if (ran(1, mutrate * 100) == 1)
	{//mutation sex
		pop[poptot][ssex] = ran(1, 4);
	}
	if (ran(1, mutrate * 100) == 1)
	{//mutation environment
		pop[poptot][senviro] += ran(-1 * pop[poptot][senviro], pop[poptot][senviro]);
	}
	if (ran(1, mutrate * 100) == 1)
	{//mutation food
		pop[poptot][sfood] = ran(1, 4);
	}
	if (ran(1, mutrate * 100) == 1)
	{//mutation size
		pop[poptot][ssize] += ran(-1 * pop[poptot][ssize], pop[poptot][ssize]);
	}
	if (ran(1, mutrate * 100) == 1)
	{//mutation speed
		pop[poptot][sspeed] += ran(-1 * pop[poptot][sspeed], pop[poptot][sspeed]);
	}
	//make sure speed, size, or enviro aren't negatives
	if (pop[poptot][sspeed] < 1) pop[poptot][sspeed] = 1;
	if (pop[poptot][ssize] < 1) pop[poptot][ssize] = 1;
	if (pop[poptot][senviro] < 1) pop[poptot][senviro] = 1;
}

void mate(int mateone, int matetwo)
{//two animals mate
	int numkids; //how many kids
	int temppop; //to go through the population
	bool pregcheck = 0; //check if animals are pregnate
	
	for (temppop = 1; temppop <= poptot; temppop++)
	{//go through each animal, check to see if they are the one of the mates kids, and if the mates are pregnate with them
		if ((pop[temppop][sid] == mateone || pop[temppop][sid] == matetwo) && pop[temppop][sage] <= (matureage / pop[temppop][sspeed]) + 1) pregcheck = 1; 
		if (pregcheck == 1) temppop = poptot;
	}
	
	if (pregcheck == 0) 
	{//if neither are pregnate, make sure their stats show that
		pop[mateone][spreg] = 0;
		pop[matetwo][spreg] = 0;
	}
	
	if (pop[mateone][spreg] + pop[matetwo][spreg] == 0)
	{//if neither are pregnate now, then they can get pregnant
		if (ran(1, fert) == 1)
		{//if they get pregnant, now we have to figure out which one gets pregnant, remember one or both could be a hermaphadite
			if (pop[mateone][ssex] >= 2 && pop[mateone][ssex] <= 3)
			{//if the first mate is female or herm then they'll get pregnant
				numkids = ran(1, litter * 2);
				pop[mateone][spreg] = numkids;
				spawn(mateone, matetwo);//this is only being called once regaurdless of how many kids they are supposed to have, fix it
			}
			else if (pop[matetwo][ssex] >= 2 && pop[matetwo][ssex] <= 3)
			{//if the first mate isn't female or herm and the second is then they'll get pregnant
				numkids = ran(1, litter * 2);
				pop[matetwo][spreg] = numkids;
				spawn(matetwo, mateone);//this is only being called once regaurdless of how many kids they are supposed to have, fix it
			}
		}
	}
}

void die(int dead)
{//an animal dies, we have to remove it from the list
	int temppop; //tempary pop num to be used when interacting with other animals
	
	for (temppop = 1; temppop <= poptot; temppop++)
	{//go through each spot, starting at dead animal, move the info from above spot down to it, since last spot will take info from the blank spot above it should be 0'd out
		if (pop[temppop][sid] == dead) 
		{//if the animals parent is the one that died then his new parent will be 0
			pop[temppop][sid] = 0;
		}
		else if (pop[temppop][sid] >= dead) 
		{//if the animals parent is above the one that died then move it down one
			pop[temppop][sid]--;
		}
		
		if (temppop >= dead)
		{//if the animal is higher than the one that died then move all the states down
			pop[temppop][ssex] = pop[temppop + 1][ssex];
			pop[temppop][sfood] = pop[temppop + 1][sfood];
			pop[temppop][sreq] = pop[temppop + 1][sreq];
			pop[temppop][sspeed] = pop[temppop + 1][sspeed];
			pop[temppop][ssize] = pop[temppop + 1][ssize];
			pop[temppop][sage] = pop[temppop + 1][sage];
			pop[temppop][spreg] = pop[temppop + 1][spreg];
			pop[temppop][senergy] = pop[temppop + 1][senergy];
			pop[temppop][sid] = pop[temppop + 1][sid];
			pop[temppop][15] = pop[temppop + 1][15];
		}
	}
	poptot--; //decrease total population by 1
}

void attack(int predator, int prey)
{//animal attacks another
	int planteat; //how much of a plant an animal can eat
	
	/*
	cout<<"\nAttack! Pred - "<<predator<<", food - "<<pop[predator][sfood]<<", prey - "<<prey<<", food - "<<pop[prey][sfood];
	cout<<"\nStats:\n";
	cout<<"Popnum, sex, food, speed, size, age, preg, energy, id";
	printf("%s %5d, %1d, %1d, %3d, %3d, %4d, %2d, %4d, %5d", "\nA#", predator, pop[predator][ssex], pop[predator][sfood], pop[predator][sspeed], pop[predator][ssize], pop[predator][sage], pop[predator][spreg], pop[predator][senergy], pop[predator][sid]);
	printf("%s %5d, %1d, %1d, %3d, %3d, %4d, %2d, %4d, %5d", "\nA#", prey, pop[prey][ssex], pop[prey][sfood], pop[prey][sspeed], pop[prey][ssize], pop[prey][sage], pop[prey][spreg], pop[prey][senergy], pop[prey][sid]);
	*/
	
	if (pop[prey][sfood] == 1)
	{//if it's a plant, then it loses
		planteat = (pop[predator][sreq] * 2) - pop[prey][senergy]; //find out how much the animal can eat
		if (pop[prey][senergy] - planteat < pop[prey][sreq] / minplant) planteat = pop[prey][senergy] - (pop[prey][sreq] / minplant); //make sure it's not eating whole plant
		if (planteat < 1) planteat = 0;
		
		pop[predator][senergy] += planteat; //animal eats part of plant
		pop[prey][senergy] -= planteat; //plant loses that energy
	}
	else if (pop[prey][sfood] >= 2)
	{// if the prey is an animal
		if (pop[prey][sage] > (matureage / pop[prey][sspeed]) + 1)
		{//if the prey is mature
			if (ran(1, pop[predator][sspeed] + pop[predator][ssize] + (pop[predator][senergy] / pop[predator][sspeed]) - (pop[predator][sage] / pop[predator][sspeed])) > pop[prey][sspeed] + pop[prey][ssize] + (pop[prey][senergy] / pop[prey][sspeed]) - (pop[prey][sage] / pop[prey][sspeed]))
			{//pred win
				pop[predator][senergy] += pop[prey][senergy]; //pred gets prey's energy
				die(prey);
			}
			else
			{// pred lose
				pop[predator][senergy] -= ran(1, (pop[predator][senergy] / 10)); //both lose some energy in the battle
				pop[prey][senergy] -= ran(1, (pop[prey][senergy] / 10));
			}
		}
		else
		{//prey is not grown up
			if (ran(1, pop[predator][sspeed] + pop[predator][ssize] + (pop[predator][senergy] / pop[predator][sspeed]) - (pop[predator][sage] / pop[predator][sspeed])) > (pop[prey][sspeed] + pop[prey][ssize] + (pop[prey][senergy] / pop[prey][sspeed])) * ((matureage / pop[prey][sspeed]) + 1))
			{//pred win
				pop[predator][senergy] += pop[prey][senergy]; //pred gets prey's energy
				die(prey);
			}
			else
			{// pred lose
				pop[predator][senergy] -= ran(1, (pop[predator][senergy] / 10)); //both lose some energy in the battle
				pop[prey][senergy] -= ran(1, (pop[prey][senergy] / 10));
			}
		}
	}
}

void changes()
{//change the varibles that change daily
	if (ran(1, 50) == 1) 
	{//slight change to the varibles, drift
		environment += ran(-1, 1);
		foodsun += ran(-10, 10);
		needfood += ran(-5, 5);
	}
	if (ran(1, disasterodds) == 1)
	{//massive change, disaster
		cout<<"\n***DISASTER***\n";
		environment = ran(10, 200);
		foodsun = ran(500, 5000);
		needfood = ran(100, 2000);
		cout<<"\nmature - "<<matureage<<", sim - "<<sim<<", food - "<<needfood<<", sun - "<<foodsun<<", fert - "<<fert<<", litter - "<<litter<<", dis - "<<disasterodds;
		cout<<"\nmutrate - "<<mutrate<<", display - "<<displayrate<<", foodpenalty - "<<foodpenalty<<", sexpenalty - "<<sexpenalty<<", environment - "<<environment;	
		if (displaymode == 0) system("PAUSE");
	}
}

int calcenergy (int temppop)
{//calculate the energy required for the animal passed
	int reqenergy;
	//((sfood + ssize)^2 + (sfood * ssize)) / 100
	if (pop[temppop][sage] > (matureage / pop[temppop][sspeed]) + 1)
	{//if they are mature
		//reqenergy = ((pop[temppop][ssize] * pop[popnum][sspeed]) / needfood); //base energy required
		reqenergy = (((pop[temppop][ssize] + pop[popnum][sspeed]) * (pop[temppop][ssize] + pop[popnum][sspeed])) + (pop[temppop][ssize] * pop[popnum][sspeed])) / needfood; //base energy required
		reqenergy += pow(pop[temppop][sage], 2) / ((matureage / pop[temppop][sspeed]) + 1); //more food required for age
	}
		
	else if (pop[temppop][sage] <= (matureage / pop[temppop][sspeed]) + 1)
	{//not mature
		reqenergy = ((((pop[temppop][ssize] + pop[popnum][sspeed]) * (pop[temppop][ssize] + pop[popnum][sspeed])) + (pop[temppop][ssize] * pop[popnum][sspeed])) / needfood) * (pop[temppop][sage] / ((matureage / pop[temppop][sspeed]) + 1));
		reqenergy++;
	}
	
	if (pop[temppop][ssex] == 3) reqenergy += pow(sexpenalty, 2); //penelty for hermaphodite
	if (pop[temppop][sfood] == 4) reqenergy += pow(foodpenalty, 2); //penelty for omnivore
	if (pop[temppop][ssex] == 4) reqenergy += asexpenalty * pop[temppop][ssize]; //penelty for asexual reproduction, and large size
	reqenergy += pow(abs(pop[temppop][senviro] - environment), 2);// penelty for distance from enviromental varible
	
	if (reqenergy < 1)
	{//check for negative energy
		cout<<"\n\nNEG\n";
		display();
		cout<<"\nreqenergy - "<<reqenergy<<", sage - "<<pop[temppop][sage]<<", sspeed - "<<pop[temppop][sspeed];
		system("PAUSE");
	}
	
	return reqenergy;
}

void day()
{//main loop to handle each day
	int temppop; //tempary pop num to be used when interacting with other animals
	int speedpop; //count how many population gone through so far
	
	changes();
	for (popnum = 1; popnum <= poptot; popnum++)
	{//go through each animal, and do what needs to be done
		pop[popnum][sage]++; //grow one day
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		
		if (pop[popnum][sage] > (matureage / pop[popnum][sspeed]) + 1)
		{//if they age is more than the mature age, divided by speed they are mature, so we'll send them out to meet another animal
			for (speedpop = 1; speedpop <= pop[popnum][sspeed]; speedpop++)
			{//for each speed point we'll go through one other animal and interact
				if (temppop == popnum) continue; //if it picked itself then skip it
				temppop = 1 + int(poptot * rand() / (RAND_MAX + 1)); //pick a random other animal from the population, note this is called very often, thus we are speeding up by not using the normal ran function		
				if (pop[popnum][sfood] == pop[temppop][sfood] && abs(pop[popnum][sspeed] - pop[temppop][sspeed]) <= (pop[popnum][sspeed] / sim) + 2 && abs(pop[popnum][ssize] - pop[temppop][ssize]) <= (pop[popnum][ssize] / sim) + 2)
				{//tests to see if the other animal is same species
					if (pop[popnum][ssex] < 4 && pop[temppop][ssex] < 4 )
					{//if the animals reproduce sexually
						if (pop[popnum][ssex] != pop[temppop][ssex] || pop[popnum][ssex] == 3|| pop[temppop][ssex] == 3)
						{//if they are opposite sex, or if they are both hermaphodites (or one is), then they can mate if the other is mature too
							if (pop[temppop][sage] > (matureage / pop[temppop][sspeed]) + 1)
							{//testing to see if they other animal is mature enough to mate, if so then we can finally mate
								mate(popnum, temppop);
							}
						}
					}
				}
				else if (pop[popnum][sreq] * 2 > pop[popnum][senergy])
				{//not the same species
					if (pop[popnum][sfood] >= 3 && pop[temppop][sfood] >= 2)
					{//if the animal eats meat, and other animal is meat
						if (pop[popnum][senergy] > 0 && pop[popnum][senergy] < (pop[popnum][ssize] * pop[popnum][sspeed]) && (pop[popnum][ssize] * pop[popnum][sspeed]) / pop[popnum][senergy] > pow(pop[temppop][ssize], 2))
						{// if we are hungry/fast/biger attack
							attack(popnum, temppop);
						}
					}
					else if ((pop[popnum][sfood] == 2 || pop[popnum][sfood] == 4) && pop[temppop][sfood] == 1 && pop[popnum][senergy] < pop[popnum][sreq] * 2)
					{//if animal eats plants, and other animal is plant
						attack(popnum, temppop);
					}
				}
			}
		}
		
		else if (pop[popnum][sage] <= (matureage / pop[popnum][sspeed]) + 1)
		{//if they aren't mature then we'll get food from parent, note plants are here too, they get food as a fruit, although that is really before birth, all that will have to be sorted out
			if (pop[popnum][sid] > 0 && pop[pop[popnum][sid]][senergy] > pop[popnum][sreq] + pop[pop[popnum][sid]][sreq])
			{//if parent can spare food, then we'll feed the kid
				pop[pop[popnum][sid]][senergy] -= pop[popnum][sreq];
				pop[popnum][senergy] += pop[popnum][sreq];
			}
		}
		
		if (pop[popnum][sfood] == 1)
		{//if they are a plant, age doesn't matter, once they are born (planted) they are on their own
			if (pop[popnum][sage] > (matureage / pop[popnum][sspeed]) + 1) pop[popnum][senergy] += ((pop[popnum][ssize] + pop[popnum][sspeed]) * foodsun) / (poptot * 2); //gives them the ammount of food they get from they sun
			if (pop[popnum][sage] <= (matureage / pop[popnum][sspeed]) + 1) pop[popnum][senergy] += (((pop[popnum][ssize] * (pop[popnum][sage] / ((matureage / pop[popnum][sspeed]) + 1))) + pop[popnum][sspeed]) * foodsun) / (poptot * 2); //gives them the ammount of food they get from they sun
			if (pop[popnum][senergy] > pop[popnum][sreq] * 10) pop[popnum][senergy] = pop[popnum][sreq] * 10;
		}
		
		if (pop[popnum][sage] / 10 > (matureage / pop[popnum][sspeed]) + 1) pop[pop[popnum][sid]][spreg] = 0;//check to see if it's mom is still preg
		
		if (pop[popnum][ssex] == 4 && pop[popnum][sage] > (matureage / pop[popnum][sspeed]) + 1)
		{//asexual reproduction
			if (pop[popnum][senergy] > pop[popnum][sreq] * 2)
			{//if it has twice the energy it needs
				spawn(popnum, popnum); //spawn a new animal, this one is it's mom and dad since it's asexual
			}
		}
		if (pop[popnum][spreg] > 0)
		{//if pregnate
			//not sure if needed, since giving birth is pointless, still taking care of it, whether inside or not until mature
			//yeah you need it, other wise they stay pregnate and then can't get pregnate.
			//well dont need it for now, we check in mate to see if they are preg, although that is very wasteful of cycles, so it would be better to put something here
		}
		
		if (pop[popnum][sreq] < 1)
		{//negative required energy
			cout<<"\nneg";
			display();
			
			system("PAUSE");
		}
		
		pop[popnum][senergy] -= pop[popnum][sreq]; //takes away the ammount of energy they need to live for the day
		pop[popnum][senergy]--; //to ensure nothing can hang out with low speed/size forever
		if (pop[popnum][senergy] <= 0 && popnum <= poptot)
		{//if they don't have enough energy at the end of the day they die
			die(popnum);
			popnum--;
		}
	}
}

void help()
{
	cout<<"\nEvolution by Dale Swanson September 30th, 2007";
	cout<<"\nThis is supposed to simulate evolution, kind of";
	cout<<"\nHere's an explanation of the names:";
	cout<<"\nmature - higher this is the longer it takes to become mature";
	cout<<"\nsim - higher this is the less similar two animals need to be to be able to mate";
	cout<<"\nfood - the higher this is the more food is needed";
	cout<<"\nsun - the higher this is the more energy plants get from the sun";
	cout<<"\nfert - the higher this is the less likely sex will result in pregnancy";
	cout<<"\nlitter - average litter size";
	cout<<"\ndis - odds per day of a disaster";
	cout<<"\nmutrate - the higher this is the less likely mutation will be";
	cout<<"\ndisplay - how often in days to display";
	cout<<"\nfoodpenalty - the higher this is the higher the penalty for being an omnivore";
	cout<<"\nsexpenalty - the higher this is the higher the penalty for being hermaphrodite";
	cout<<"\nenvironment - general variable to represent the environment, the closer the animal is to this the better off it'll be";
	cout<<"\npopnum - ID number of each animal";
	cout<<"\nsex - sex of animal, 1-male, 2-female, 3-asexual, 4-hermaphrodite";
	cout<<"\nfood - food source of animal, 1-sun, 2-plants, 3-animals, 4-either";
	cout<<"\nspeed - general speed stat, higher = faster";
	cout<<"\nsize - general size stat, higher = larger";
	cout<<"\nage - stat for age, in days";
	cout<<"\npreg - how many kids the animal is pregnant with";
	cout<<"\nreq - how much energy is required every day";
	cout<<"\nenergy - how much energy reserves the animal has";
	cout<<"\nenviro - animals environmental variable, the closer this is to the global environmental variable the better the animal will do";
	cout<<"\nid - ID number of the animal's parent";
	cout<<"\n\n";
	
	cout<<"\nEnter the display mode, 0 displays the results at the display rate, 1 shows it every turn, and clears the last turns results? ";
	cin>>displaymode;
	if (displaymode == 0)
	{//get the display mode
		cout<<"\nEnter the display rate, in days? ";
		cin>>displayrate;
	}
	else
	{//anything other than 0 for a display mode, and we make sure it's 1
		displaymode = 1;
	}
	
}

void setup()
{//set the inital varibles	
	// universal/environmental constants
	matureage = 100; //how old before it's mature. if age > (matureage / speed) + 1
	sim = 10; //how simular it has to be to be same species
	needfood = 1000; //how much food they need.  reqenergy = ((size * speed) / needfood), higher needfood = less food needed
	foodsun = 2000; //how much food the sun provides
	fert = 10; //odds that mating will produce kids
	litter = 2; //average size of a litter
	mutrate = 10; //mutation rate
	//displayrate = 10; //display rate (per turns)
	foodpenalty = 10; //penalty for being a omnivore
	sexpenalty = 10; //penalty for being a hemaphidite
	environment = 100; //varible to represent the environment, the closer to this the animal is the better of it'll be, it'll change with time.
	disasterodds = 1000; //odd of a disaster per day
	minplant = 10; //minimum ammount of plant left after eaten
	asexpenalty = 10; //penalty for being asexual
	//displaymode = 1; //diplaymode 0 will display the results at the display rate, 1 will show it every turn, and clear the last turns results
	
	
	//constants for use in the pop array index
	ssex = 1;
	senviro = 2;
	sfood = 3;
	sspeed = 4;
	ssize = 5;
	sage = 6;
	spreg = 7;
	senergy = 8;
	sid = 9;
	sreq = 10;
	
	for(popnum = 1; popnum <= 100; popnum++)
	{//set up initial population
		pop[popnum][ssex] = 4;
		pop[popnum][sfood] = 1;
		pop[popnum][sspeed] = 10 + ran (-3, 3);
		pop[popnum][ssize] = 10 + ran (-3, 3);
		pop[popnum][sage] = 50;
		pop[popnum][spreg] = 0;
		pop[popnum][senviro] = 85 + ran (-10, 10);
		poptot++;
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		pop[popnum][senergy] = pop[popnum][sreq] * 2;
	}
	
	for(popnum = 101; popnum <= 200; popnum++)
	{//set up initial population
		pop[popnum][ssex] = 3;
		pop[popnum][sfood] = 1;
		pop[popnum][sspeed] = 10 + ran (-3, 3);
		pop[popnum][ssize] = 10 + ran (-3, 3);
		pop[popnum][sage] = 50;
		pop[popnum][spreg] = 0;
		pop[popnum][senergy] = pop[popnum][5] * pop[popnum][4];
		pop[popnum][senviro] = 95 + ran (-10, 10);
		poptot++;
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		pop[popnum][senergy] = pop[popnum][sreq] * 2;
	}
	
	for(popnum = 201; popnum <= 300; popnum++)
	{//set up initial population
		pop[popnum][ssex] = 3;
		pop[popnum][sfood] = 1;
		pop[popnum][sspeed] = 100 + ran (-10, 10);
		pop[popnum][ssize] = 1000 + ran (-300, 300);
		pop[popnum][sage] = 50;
		pop[popnum][spreg] = 0;
		pop[popnum][senergy] = pop[popnum][5] * pop[popnum][4];
		pop[popnum][senviro] = 95 + ran (-10, 10);
		poptot++;
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		pop[popnum][senergy] = pop[popnum][sreq] * 2;
	}
	
	for(popnum = 301; popnum <= 400; popnum++)
	{//set up initial population
		pop[popnum][ssex] = 3;
		pop[popnum][sfood] = 4;
		pop[popnum][sspeed] = 100 + ran (-10, 10);
		pop[popnum][ssize] = 100 + ran (-30, 30);
		pop[popnum][sage] = 50;
		pop[popnum][spreg] = 0;
		pop[popnum][senergy] = pop[popnum][5] * pop[popnum][4];
		pop[popnum][senviro] = 95 + ran (-10, 10);
		poptot++;
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		pop[popnum][senergy] = pop[popnum][sreq] * 2;
	}
	
	for(popnum = 401; popnum <= 500; popnum++)
	{//second initial pop
		pop[popnum][ssex] = 4;
		pop[popnum][sfood] = 4;
		pop[popnum][sspeed] = 10 + ran (-3, 3);
		pop[popnum][ssize] = 10 + ran (-3, 3);
		pop[popnum][sage] = 50;
		pop[popnum][spreg] = 0;
		pop[popnum][senviro] = 90 + ran (-10, 10);
		pop[popnum][senergy] = pop[popnum][5] * pop[popnum][4];
		poptot++;
		pop[popnum][sreq] = calcenergy(popnum); //fine energy requirment
		pop[popnum][senergy] = pop[popnum][sreq] * 2;
	}
}


int main()
{
    time_t sseconds; //start seconds, will be used to seed the rng
	time_t cseconds; //current seconds
	time_t dseconds; //last display seconds
    time(&sseconds); //get our seed for rng
    srand((unsigned int) sseconds); //seed rng
	fnamecomb();
	int temppop;
	help();
	setup();
	
	for (temppop = 1; temppop <= poptot; temppop++)
	{
		pop[temppop][sreq] = calcenergy(temppop);
		pop[temppop][senergy] = pop[temppop][sreq] * 2;
	}
	
	time(&dseconds);
	do 
	{
		day();
		turns++;
		if (displaymode == 0) cout<<"\nDay - "<<turns<<", enviro - "<<environment<<", sun - "<<foodsun<<", food - "<<needfood<<", pop - "<<poptot;
		time(&cseconds);
		if (displaymode == 0 && (turns % displayrate == 0 || cseconds - dseconds > 15))
		{//display every 100 turns, keep history
			display();
			cout<<"\n";
			system("PAUSE");
			time(&dseconds);
		}
		if (displaymode == 1 && (turns % 10 == 0 || cseconds - dseconds > 1))
		{//display every second, clear screen
			system("CLS");
			cout<<"\nDay - "<<turns<<", enviro - "<<environment<<", sun - "<<foodsun<<", food - "<<needfood<<", pop - "<<poptot;
			display();
			time(&dseconds);
		}
	} while (poptot > 0);
	
	cout<<"\nDone...\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}
