I'm not sure why I'm getting a seg fault with this code. It happens in the main() file when I call this line:
mapobject.grid[i][j]->act(i, j);
I am trying to make the ants and doodlebugs move around the grid randomly up, right, down, or left. The ants.txt and dbs.txt contain coordinates in the grid.
CODE
//this is the header file
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Organism;
class Map
{
public:
Map();
void printGrid();
Organism *grid[20][20];
};
class Organism
{
public:
virtual void print()=0;
virtual int type()= 0;
void move(int,int);
virtual void act(int, int) = 0;
};
class Ant: public Organism
{
public:
int type(){return 0;}
void print(){cout<<'O';}
void act(int, int);
};
class Doodlebug: public Organism
{
public:
int type(){return 1;}
void print(){cout<< 'X';}
void act(int, int);
};
//this is the member function definition file
#include "organism.h"
void Map::gridMap()
{
fstream fin;
int next, r, c;
for(int i = 0; i < 20; i++){
for(int j = 0; j<20; j++){
grid[i][j] = NULL;
}
}
fin.open("ants.txt");
if(fin.fail()){
cout << "Input file opening failed.\n";
exit(1);
}
while(fin>>next){
r = next;
fin>>next;
c = next;
Ant *ant = new Ant;
grid[c][r] = ant;
}
fin.close();
fin.open("dbs.txt");
if(fin.fail()){
cout << "Input file opening failed.\n";
exit(1);
}
while(fin>>next){
r = next;
fin>>next;
c = next;
Doodlebug *db = new Doodlebug;
grid[c][r] = db;
}
fin.close();
}
void Map::printGrid()
{
for(int i = 19; i >= 0; i--){
for(int j=0;j < 20; j++){
if(grid[i][j] == NULL){
cout << ' ';
}
else
grid[i][j]->print();
}
cout<<endl;
}
}
void Ant::act(int i, int j)
{
move(i, j);
}
void Doodlebug::act(int i, int j)
{
move(i, j);
}
void Organism::move(int i, int j)
{
Organism *org[20][20];
Map temp;
int direction = rand()%4;
switch(direction){
case 0:
if(i > 0 && (temp.grid[i-1][j] == NULL)){
delete temp.grid[i][j];
temp.grid[i-1][j] = new Ant;
temp.grid[i][j] = NULL;
}
break;
case 1:
if(j < 20 && temp.grid[i][j+1] == NULL){
delete temp.grid[i][j];
temp.grid[i][j+1] = new Ant;
temp.grid[i][j] = NULL;
}
break;
case 2:
if(j < 20 && temp.grid[i+1][j] == NULL){
delete temp.grid[i][j];
temp.grid[i+1][j] = new Ant;
temp.grid[i][j] = NULL;
}
break;
case 3:
if(i > 0 && temp.grid[i][j-1] == NULL){
delete temp.grid[i][j];
temp.grid[i][j-1] = new Ant;
temp.grid[i][j] = NULL;
}
break;
default:
break;
}
}
//this is the main() file
#include "organism.h"
int main()
{
srand(1);
Map mapobject;
string input;
int i, j;
mapobject.gridMap();
while(intput[0] != 'q'){
mapobject.printGrid();
for( i = 0; i < 20; i++){
for( j = 0; j < 20; j++){
mapobject.grid[i][j]->act(i, j);
}
}
cout << ">";
getline(cin,input);
}
}