#include "grid.h" Grid::Grid(int r, int c) { rowSize = r; colSize = c; grid = new char*[rowSize]; for(int i = 0; i < rowSize; i++) grid[i] = new char[colSize]; clear(); } Grid& Grid::operator=(const Grid& g) { if (this != &g) { free(); copy(g); } return *this; } void Grid::clear(char c /* = ' ' */) { for(int i = 0; i < rowSize; i++) for(int j = 0; j < colSize; j++) grid[i][j] = c; } // horizontal plot void Grid::hPlot(int row, int col, const string& s) { for(int i = 0; i < s.size(); i++) plot(row, col++, s[i]); } // vertical plot void Grid::vPlot(int row, int col, const string& s) { for(int i = 0; i < s.size(); i++) plot(row++, col, s[i]); } void Grid::free() { if (grid) { for(int i = 0; i < rowSize; i++) delete[] grid[i]; // delete[][] grid doesn't work delete[] grid; } } void Grid::copy(const Grid& g) { rowSize = g.rowSize; colSize = g.colSize; grid = new char*[rowSize]; for(int i = 0; i < rowSize; i++) grid[i] = new char[colSize]; for(i = 0; i < rowSize; i++) for(int j = 0; j < colSize; j++) grid[i][j] = g.grid[i][j]; } // Stolen from Horstmann's book. //(He got it from Foley & Van Dam's book) void Grid::plotLine(int xstart, int ystart, int xend, int yend, char c) { int dx = xend - xstart; // run int dy = yend - ystart; // rise if (abs(dy) < abs(dx)) // |slope| < 1 { if (dx < 0) // xend < xstart { plotLine(xend, yend, xstart, ystart, c); return; } // plot (x, y) for increments of x & y double y = ystart + 0.5; double m = double(dy)/double(dx); // = slope for(int x = xstart; x != xend; x++, y += m) plot(int(y), x, c); } else // 1 <= |slope| { if (dy < 0) // yend < ytart { plotLine(xend, yend, xstart, ystart, c); return; } // plot (x, y) for increments of x & y double x = xstart + 0.5; double m = double(dx)/double(dy); // = slope for(int y = ystart; y != yend; y++, x += m) plot(int(y), x, c); } plot(yend, xend, c); } void Grid::show(ostream& os) { for(int i = 0; i < getRowGetSize(); i++) { for(int j = 0; j < getColGetSize(); j++) os << getChar(i, j); os << '\n'; } }