// Square implementation #include "grid.h" #include "square.h" Square::Square() { } // new square at grid position (x,y) Square::Square(GP142Display *display, Grid *grid, int x, int y) { squareInit(display,grid,x,y); } // copy constructor Square::Square(const Square &source) { squareInit(source.display, source.grid, source.x, source.y); } // initialize or assign the square the values passed void Square::squareInit(GP142Display *display, Grid *grid, int x, int y) { this->display = display; this->grid = grid; this->x = x; this->y = y; ableToMove = true; } // operator= make square a copy of other Square & Square::operator=(const Square &other) { if (this == &other) return *this; x = other.x; y = other.y; display = other.display; grid = other.grid; return *this; } // draw rectangle of pixels corresponding to square at // grid location (x,y) void Square::Draw(GP142Color color) { display->drawRectangle(GRID_LEFT+x*SQUARE_WIDTH,GRID_BOTTOM+y*SQUARE_HEIGHT, GRID_LEFT+(x+1)*SQUARE_WIDTH, GRID_BOTTOM+(y+1)*SQUARE_HEIGHT, color,FILL); } // get x coordinate of square int Square::getX() const { return x; } // get y coordinate of square int Square::getY() const { return y; } // move square in direction d if possible // if the square can move in direction d then change its coordinates // to reflect the move // if we try to move DOWN and can't then the block becomes frozen void Square::Move(Direction d) { if (canMove(d)) { switch (d) { case DOWN: y = y - 1; break; // other cases needed case ERROR: default: // this shouldn't happen break; } } // freeze if we land on another block if (d == DOWN && !canMove(DOWN)) ableToMove = false; } // return if the square can move in direction d // (we can't move below the grid or outside the boundaries) bool Square::canMove(Direction d) const{ if (!ableToMove) return false; bool move = true; switch(d) { case DOWN: if (y == 0 || grid->IsSet(x,y-1)) move = false; break; case LEFT: if (x == 0 || grid->IsSet(x-1,y)) move = false; break; case RIGHT: if (x == GRID_WIDTH-1 || grid->IsSet(x+1,y)) move = false; break; case ERROR: default: move = false; break; } return move; }