1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
#include <iostream>
class Critter
{
private:
char info;
public:
Critter(char someInfo = '*'){ info = someInfo;}
~Critter(){ };
char getInfo();
void setInfo( char someInfo){ info = someInfo; };
};
char Critter::getInfo(){ return info;}
class Grid
{
private:
int rows;
int cols;
Critter empty = Critter('*');
Critter* **matrix;
public:
Grid(const int rows = 1, const int cols = 1);
~Grid();
bool move( int aCurrentX, int aCurrentY, int aNewX, int aNewY );
void display();
bool isVacant(const int, const int);
void set(Critter*, int, int);
};
Grid::Grid(const int nRows, const int nCols)
{
rows = nRows;
cols = nCols;
matrix = new Critter* *[nRows];
for (int j=0; j < nRows; j++)
matrix[j] = new Critter*[nCols];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
matrix[i][j] = ∅
}
}
Grid::~Grid()
{
for(int i = 0; i < rows; i++ )
delete [] matrix[i];
delete [] matrix;
}
void Grid::set(Critter* aCritter, int aXpos, int aYpos)
{
matrix[aXpos][aYpos] = aCritter;
}
void Grid::display()
{
for( int i = 0; i < rows; i++ )
{
for( int j = 0; j < cols; j++ )
std::cout << matrix[i][j]->getInfo() << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
bool Grid::isVacant(int x, int y)
{
return matrix[x][y]->getInfo() == '*';
}
bool Grid::move(int aCurrentX, int aCurrentY, int aNewX, int aNewY)
{
if (isVacant(aNewX,aNewY))
{
matrix[aNewX][aNewY] = matrix[aCurrentX][aCurrentY];
matrix[aCurrentX][aCurrentY] = ∅
return true;
}
else
return false;
}
int main()
{
//Setup grid - populate with empty Critters
const int rows = 5;
const int cols = 7;
Grid grid(rows, cols);
grid.display();
// Add some random critters 50% coverage
for(int i = 0; i < rows * cols / 2; i++)
{
Critter* dummy = new Critter((char)(i % 26 + 'A'));
grid.set( dummy, rand() % rows, rand() % cols);
}
// Add just a single critter
Critter* Bill = new Critter('+');
grid.set( Bill, 4, 4);
grid.display();
// Move a Critter at selected grid to new position
grid.move(0,2,1,4);
grid.display();
// Move another Critter but output error message if collision occurs
if( !grid.move(1,4,2,3) )
std::cout << "Error: Can't move there.\n";
grid.display();
// Move 'Bill'
grid.move(4,4,1,1);
grid.display();
Bill -> setInfo('?');
grid.display();
std::cout << Bill -> getInfo() << '\n';
return 0;
}
|