Esempio n. 1
0
// ----------------------------------------------------------------------------
int main(int argc, char** argv) {
  DBG("[Lesson 5]: C Style 5");

  Square square;
  SquareCtor(&square, 10, 10);
  square.print();
  WRN("Square area: %.2f", square.area(&square));

  /**
   * What we want to happen is that the print() activation of the Shape pointer 
   * will activate the print() function of the Square object which its pointing to.
   */
  Shape* ptr = reinterpret_cast<Shape*>(&square);
  ptr->print();  // expected polymorphism

  DBG("[Lesson 5]: C Style 5 [END]");
  return 0;
}
Esempio n. 2
0
//Referenced brinkmwj's update method to create mine, modified it to work with mouse input
void HW_02App::update()
{
	Square* cur = mSquare_;
	Vec2f center = kUnitX*width/2.0 + kUnitY*height/2.0;

	if(mIsPressed){
		cur->update(mMouseLoc, width/4.0);
	}

	if(cur != NULL && mIsPressed){
		do {
			cur->update(mMouseLoc, width/4.0);
			cur = cur->next_;
		} while (cur != mSquare_);
	}

	frame_number_++;
}
Esempio n. 3
0
int main() {
	Square square;
	square.draw();
	square.virtual_draw();
	std::cout << std::endl;

	Shape* triangle = new Triangle();
	triangle->draw();
	triangle->virtual_draw();
	std::cout << std::endl;

	WeirdShape weird;
	weird.virtual_draw();


	system("PAUSE");
	return EXIT_SUCCESS;
}
Esempio n. 4
0
int main()
{
	Rectangle r (5,3);
	cout << "Width is " ;
	cout << r.get_width() << endl;
	cout << "Length is ";
	cout << r.get_length() << endl;
	cout << "Area is ";
	cout << r.get_area() << endl;
	return 1;

	Square s (5);
	cout << "Square Length is ";
	cout << s.get_length() << endl;
	cout << "Square Area is ";
	cout << s.get_area() << endl;
	return 1;
}
Esempio n. 5
0
void Grid::printGrid()
{
    for(int yPos = 0; yPos < height ; yPos++)
    {
        for(int xPos = 0; xPos < width ; xPos++)
        {
            Square* testSquare = grid[xPos + (yPos * width)];
            if(testSquare->getCurrentState())
            {
                std::cout << "█" ;
            }
            else
            {
                std::cout << "•";
            }
        }
        std::cout << std::endl;
    }
}
Esempio n. 6
0
/// Calls rollDice() and calculates the destination square
/// Passes these too executeMove().
bool SnakesAndLadders::getMove() {
  // Setup a pointer to the current player and the square they are on.
  SLPlayer* player = dynamic_cast<SLPlayer*>(players[currentPlayer]);
  Coord current = dynamic_cast<SrcPiece&>(player->getPiece(0)).getSource();
  Square* srcSquare = &grid[current.y][current.x];

  // Prompt the user to roll.
  cout << "Press enter to roll a dice and make your move\n";
  cin.get();
  int roll = rollDice();
  int total=roll;

  // Unsuspend the player if they roll a 6.
  if(roll == 6) {
    player->suspended = false;
  }

  // Roll again if a 6 is rolled.
  while((roll % 6 == 0) && (total != 6*3)) {
    cout << "You rolled a " << roll << " go again\n";
    cin.get();
    roll = rollDice();
    total += roll;
  }
  if(roll != 6) cout << "You rolled a " << roll << "\n";

  if(total == 6*3) {
    player->suspended = true;
    executeMove(srcSquare, squareRefs[0]);
    cout << "You rolled 3 sucessive 6s.\n";
  } else if(!player->suspended) {
    total = total + srcSquare->getIdentifier()-1;
    total = total > 100 ? 100 - (total % 100) : total;
    this->executeMove(srcSquare, squareRefs[total-1]);
  } else {
    cout << "You are suspended until you roll a 6\n";
  }

  // Switch Player.
  currentPlayer=(currentPlayer+1)%(amountOfPlayers);

  return true;
}
Esempio n. 7
0
void ChessBoard::initializeBoard() {

  for( int i = 0; i < BOARD_WIDTH_HEIGHT; ++i ) {
    for( int j = 0; j < BOARD_WIDTH_HEIGHT; ++j ) {

      PieceColor squareColor;
      if( (i+j) % 2 == 0 ) squareColor = WHITE;
      else squareColor = BLACK;

      Square* sq = &board[i][j];
      sq->color = squareColor;

      if( i < 2 || i > 5 ) {

	PieceColor color;
	if( i < 2 ) color = BLACK;
	else color = WHITE;

	PieceType type;
	if( i == 0 || i == 7 ) type = getPieceType( j );
	else type = PAWN;

	Piece* piece = new Piece( type, color, true );
	piece->x = j;
	piece->y = i;

	sq->setPiece( piece );
	if( i < 2 ) blackPieces.push_back( piece );
	else whitePieces.push_back( piece );

      } else {

	sq->setPiece(NULL);
      }

      sq->x = j;
      sq->y = i;


    }
  }
}
Esempio n. 8
0
int main(int argc, char* argv[])
{
	double l,l2;
	cout << "Length=";
	cin >> l;
	Square p1(l);
	Cube p2(l);
	Square *pp;
	pp = &p1;
	pp->print();
	pp->Space(l);
	pp = &p2;
	pp->print();
	pp->Space(l);
	Cube p3(1);
	p2 = p3;
	p2.print();
	system("pause");
	return 0;
}
void Board::print_board()
{
  printf("\nPlayer to move: %s\n", current_player == Square::BLACK ? "BLACK" : "WHITE");

  const char* hyphens = std::string(SQUARE_DIMENSION * 6 - 1, '-').c_str();
  printf(" %s\n", hyphens);

  for (int y = SQUARE_DIMENSION - 1; y >= 0; --y)
  {
    for (int x = 0; x < SQUARE_DIMENSION; ++x)
    {
      Square* sq = (*board)[x][y];
      printf("| %s%-2d ", sq->get_occupant() == Square::BLACK ? "B" : (sq->get_occupant() == Square::WHITE ? "W" : "E"), sq->get_num_stones());
    }

    printf("|\n");
  }

  printf(" %s\n", hyphens);
}
Esempio n. 10
0
void HW_02App::draw()
{
	gl::clear( Color( 0, 0, 0 ), true );
	
	if((frame_number_ <=1) || mDrawImage){
		mDrawImage = true;
		gl::clear( Color( 0, 0, 0 ), true );
		gl::drawString("Welcome to The Royal Society for Putting Things on Top of Other Things", Vec2f (20,200), Color(0.0f,1.0f,0.0f), *f);				
		gl::drawString("Press '?' to continue...", Vec2f (20,230), Color(0.0f,1.0f,0.0f), *f);			
	
	}
	else{
		Square* cur = mSquare_;		
		if(cur != NULL){
			do {
				cur->draw();
				cur = cur->next_;
			} while (cur != mSquare_);
		}
	}
}
Esempio n. 11
0
void Grid::updateLoop()
{
    for(int yPos = 0; yPos < height ; yPos++)
    {
        for(int xPos = 0; xPos < width ; xPos++)
        {
            Square* testSquare = getSquareByXY(xPos, yPos);
            int indexNum = testSquare->getIndexNum();
            int neighbours = findNeighbours(indexNum);
            bool alive = testSquare->getCurrentState();
            if (alive && (neighbours < 2 || neighbours > 3))
            {
                testSquare->setShouldFlip();
            }
            else if (!alive && neighbours == 3)
            {
                testSquare->setShouldFlip();
            }
        }
    }
}
Esempio n. 12
0
bool Shot::willCollid(Square square, int x, int y) {
    if ((box.x + x == square.getx()) or ((box.x + x > square.getx()) and (box.x + x < (square.getx() + square.getw())))
            or ((square.getx() > box.x + x) and (square.getx() < (box.x + x + box.w))))
        if ((box.y + y <= square.gety()) and (box.y + y + box.h >= square.gety()))
            return true;
    return false;
};
Esempio n. 13
0
bool AttackCommand::undo(Chessboard &board)
{
    Square *to = board.squareAt(fromSquare());
    Square *from = board.squareAt(toSquare());

    if (!to->isEmpty())
    {
        qCritical() << "Runtime error: square is not empty";
        return false;
    }

    if (from->isEmpty())
    {
        qCritical() << "Runtime error: square is empty";
        return false;
    }

    Piece* movedePiece = from->piece();
    undoMarkingAsMoved(*movedePiece);
    board.removePiece(movedePiece);
    board.putPiece(to, movedePiece);

    board.putPiece(from, m_killedPiece);
    m_killedPiece = nullptr;

    qDebug() << "Attack (Undo): " << Chess::toString(movedePiece->type()) << " " << from->toStr() << ":" << to->toStr();

    return true;
}
Esempio n. 14
0
int main(){
	
	Rectangle R;
	R.set_Length(5);
	R.set_Width(6);
	cout<<"Rectangle :";
	R.get_Length();
	cout<<"Rectangle :";
	R.get_Width();
	R.cal_Area();
	
	Square S;
	S.set_Length(8);
	cout<<"Square :";
	S.get_Length();
	S.cal_Area();
	
	Parellelogram P;
	P.set_Length(4);
	cout<<"Parellolgram :";
	P.get_Length();
	P.set_Height(3);
	cout<<"Parellolgram :";
	P.get_Height();
	P.cal_Area();
	
	Trapezoid T;
	T.set_Base1(3);
	cout<<"Trapezoid :";
	T.get_Base1();
	T.set_Base2(4);
	cout<<"Trapezoid :";
	T.get_Base2();
	T.set_Height(2);
	cout<<"Trapezoid :";
	T.get_Height();
	T.cal_Area();
	return 0;
}
Esempio n. 15
0
bool Square::intersects(Square square, vector<Coordinate> & pos){
	vector<double> boundingRectanglePoints;
	Square boundingRectangle = getBoundingRectangle(square, boundingRectanglePoints);

	if ((boundingRectangle.getWidth() < getWidth() + square.getWidth())
		&& (boundingRectangle.getHeight() < getHeight() + square.getHeight())){

		pos.push_back(Coordinate(max(LB.getX(), square.getLB().getX()), max(LB.getY(), square.getLB().getY())));
		pos.push_back(Coordinate(min(RA.getX(), square.getRA().getX()), min(RA.getY(), square.getRA().getY())));
		//cout << "height bounding rectangle: " << abs(pos[1].getY() - pos[0].getY()) << endl;
		//cout << "height first rectangle: " << getHeight() << endl;
		if (abs(pos[1].getY() - pos[0].getY()) >= getHeight() || abs(pos[1].getY() - pos[0].getY()) >= square.getHeight()){
			pos.push_back(Coordinate(pos[0].getX(), pos[0].getY() + boundingRectangle.getHeight()));
			pos.push_back(Coordinate(pos[1].getX(), pos[1].getY() - boundingRectangle.getHeight()));

		}
		return true;
	}
	else {
		return false;
	}
}
void MainWindowController::slotClickDefSquare(SquareScene* square) {
    Square* selectedSq = grid.getSquare(square->getX(),square->getY());
    switch(selectedSq->getWordCount()) {
    case 0:
        if(selected != QPoint(-1,-1))
            nextSquare();
        break;
    case 1:
    case 2:
        if(selected == QPoint(-1,-1)) {
            select(square->getX(),square->getY(), selectedSq, square->getLower());
        }
        else {
            int x1 = selected.x();
            int x2 = selected.y();
            bool lower2 = selectedLower;
            unselect();
            if( x1 != square->getX() || x2 != square->getY() || square->getLower() != lower2)
                select(square->getX(),square->getY(), selectedSq, square->getLower());
        }
        break;
    }
}
Esempio n. 17
0
int Grid::findNeighbours(int indexNum)
{
    int x,y;
    getXYofSquare(&x, &y, indexNum);
    int totalNeighbours = 0;
    Square* neighbour;
    for(int yPos=std::max(0, y - 1); yPos <= y + 1 && yPos < height; yPos++)
    {
        for(int xPos=std::max(0, x - 1); xPos <= x + 1 && xPos < width; xPos++)
        {
            if (xPos == x && yPos == y)
            {
                continue;
            }
            neighbour = getSquareByXY(xPos, yPos);
            if (neighbour->getCurrentState())
            {
                totalNeighbours++;
            }
        }
    }
    return totalNeighbours;
}
Esempio n. 18
0
int main()
{
    Square box;  // box is defined as an object of the Square class
    float  size; // size contains the length of a side of the square

   // FILL IN THE CLIENT CODE THAT WILL ASK THE USER FOR THE LENGTH OF THE SIDE
   // OF THE SQUARE.  (This is stored in size)
   cout << "Please input the length of the side of the square\n";
   cin >> size;

   // FILL IN THE CODE THAT CALLS SetSide.
   box.setSide(size);

   // FILL IN THE CODE THAT WILL RETURN THE AREA FROM A CALL TO A FUNCTION
   // AND PRINT OUT THE AREA TO THE SCREEN
   cout << "The area of the square is " << box.findArea() << '\n';

   // FILL IN THE CODE THAT WILL RETURN THE PERIMETER FROM A CALL TO A
   // FUNCTION AND PRINT OUT THAT VALUE TO THE SCREEN
   cout << "The perimeter of the square is " << box.findPerimeter() << '\n';

	return 0;
}
Esempio n. 19
0
//Move squares that falls after deletion of an other squares.
//These squares are added into a list of lists (squares) by a GameBoard object after deleting a square.
//If the first square of each list hits something, the complete list is added to the gameboard and deleted from squares
void Game::moveOtherSquares(GameBoard *board)
{
	int pos = 0;
	std::vector<int> delvec;
	if (!this->squares->empty())
	{
		//Move the square one position down
		for (auto list = this->squares->begin(); list != this->squares->end(); list++)
		{
			Square *fall = (*list)->at(0);

			//If collision then add to the gameboard and delete it from the vector
			if (DetectCollision(fall, board).Down)
			{
				delvec.push_back(pos);
				for (auto i = (*list)->begin(); i != (*list)->end(); i++)
				{
					board->addToBoard(*i);
				}
			}
			else
			{
				for (auto i = (*list)->begin(); i != (*list)->end(); i++)
				{
					Square *s = *i;
					s->SetY(s->GetY() + s->GetSize());
				}
			}
			pos++;
		}
		//Delete the once added to the board
		for (auto i = delvec.rbegin(); i != delvec.rend(); i++)
		{
			this->squares->erase(this->squares->begin() + *i);
		}
	}
}
Esempio n. 20
0
//------------------------------------------------------------------------------
// RUSR (user rebus grid)
//------------------------------------------------------------------------------
bool LoadRUSR(Puzzle * puz, const std::string & data)
{
    // RUSR is a series of strings (each nul-terminated) that represent any
    // user grid rebus entries.  If the rebus is a symbol, it is enclosed
    // in '[' ']'.

    std::istringstream stream(data);
    istream_wrapper f(stream);

    for (Square * square = puz->GetGrid().First();
         square != NULL;
         square = square->Next())
    {
        std::string str = f.ReadString();

        if (str.empty())
            continue;

        square->SetText(decode_puz(str));
    }
    if (! f.CheckEof())
        return false;
    return true;
}
Esempio n. 21
0
Bitboard SEE::extractShadowAttacker(const Position& position,
                                    Bitboard bb,
                                    Square from,
                                    Square to) {
  Direction dir = from.dir(to);
  if (dir >= Direction::EndS) {
    return bb;
  }

  Bitboard occ = nosseOr(position.getBOccupiedBitboard(),
                         position.getWOccupiedBitboard());
  RotatedBitboard occ90 = position.get90RotatedBitboard();
  RotatedBitboard occR45 = position.getRight45RotatedBitboard();
  RotatedBitboard occL45 = position.getLeft45RotatedBitboard();

  Bitboard masked;
  switch (dir) {
  case Direction::Up:
  case Direction::Down:
    masked = MoveTables::ver(occ, from);
    break;
  case Direction::Left:
  case Direction::Right:
    masked = MoveTables::hor(occ90, from);
    break;
  case Direction::RightUp:
  case Direction::LeftDown:
    masked = MoveTables::diagR45(occR45, to);
    break;
  case Direction::LeftUp:
  case Direction::RightDown:
    masked = MoveTables::diagL45(occL45, to);
    break;
  default:
    ASSERT(false);
  }

  BB_EACH(square, masked) {
    Piece piece = position.getPieceOnBoard(square);
    if (square.dir(from) == dir && MoveTables::isMovableInLongStep(piece, dir)) {
      bb.set(square);
      break;
    }
  }
Esempio n. 22
0
void Table::push(Square A){
	int key = (A.getMainColor().R) % 100;
	if (head[key].chain == NULL){
		ChainElem *newel = new ChainElem;
		newel->next = NULL;
		newel->sqaure = A;
		head[key].chain = newel;
	}

	else {
		ChainElem *newel = new ChainElem;
		newel = head[key].chain;
		while (newel->next != NULL){
			newel = newel->next;
		}
		ChainElem *newell = new ChainElem;
		newell->next = NULL;
		newell->sqaure = A;
		newel->next = newell;


	}
}
Esempio n. 23
0
bool LevelManager::quakeSquare(int hit, int wid){
    Square *victim = game->getSquare(wid,hit);
    Structure *killStruct = game->getStructure("Ru");
    if(victim->getImage() != "Ca"){
    victim->setStruct(killStruct);
    victim->setAddition("No");
    victim->setType("Ca");
    victim->setImage("Ca");
    //SquareLabel *vicLbl = victim->getLabel();
    //int size = GuiManager::instance().getUi()->gridLayoutWidget->width()/game->getSize()/2;
     //QSize size1(size,size);
    //vicLbl->setPixmap(GuiManager::instance().setmap(victim,size1));
    return true;
    }
    else{
        return false;
    }
}
Esempio n. 24
0
void Square::getIntersection(Square other, vector<Coordinate> & pos){
	vector<double> boundingRectanglePoints;
	Square boundingRectangle = getBoundingRectangle(other, boundingRectanglePoints);

	pos.push_back(Coordinate(max(LB.getX(), other.getLB().getX()), max(LB.getY(), other.getLB().getY())));
	pos.push_back(Coordinate(min(RA.getX(), other.getRA().getX()), min(RA.getY(), other.getRA().getY())));
	//cout << "height bounding rectangle: " << abs(pos[1].getY() - pos[0].getY()) << endl;
	//cout << "height first rectangle: " << getHeight() << endl;
	if (abs(pos[1].getY() - pos[0].getY()) >= getHeight()){
		pos.push_back(Coordinate(pos[0].getX(), pos[0].getY() + getHeight()));
		pos.push_back(Coordinate(pos[1].getX(), pos[1].getY() - getHeight()));

	}
	else if (abs(pos[1].getY() - pos[0].getY()) >= other.getHeight()){
		pos.push_back(Coordinate(pos[0].getX(), pos[0].getY() + other.getHeight()));
		pos.push_back(Coordinate(pos[1].getX(), pos[1].getY() - other.getHeight()));
	}
}
Esempio n. 25
0
bool SfenParser::parseMove(const char* data, Move& move) {
    if (strlen(data) < 4) {
        LOG(warning) << "invalid format: '" << data << '\'';
        return false;
    }

    if (strcmp(data, "none") == 0) {
        move = Move::none();
        return true;
    }

    if (isdigit(data[0])) {
        Square from = Square::parseSFEN(&data[0]);
        Square to = Square::parseSFEN(&data[2]);
        bool prom = data[4] == '+';

        if (!from.isValid() || !to.isValid()) {
            LOG(warning) << "invalid format: '" << data << '\'';
            return false;
        }

        move = Move(from, to, prom);

    } else {
        if (data[1] != '*') {
            LOG(warning) << "invalid format: '" << data << '\'';
            return false;
        }

        PieceType pieceType = Piece::parseSFEN(&data[0]).type();
        Square to = Square::parseSFEN(&data[2]);

        if (pieceType.isEmpty() || !to.isValid()) {
            LOG(warning) << "invalid format: '" << data << '\'';
            return false;
        }

        move = Move(pieceType, to);
    }

    return true;
}
void BasicSampleApp::mouseDown( MouseEvent event )
{
    if(Rand::randFloat() > 0.5){
        Circle *c = new Circle();
        c->setRegPoint(rph::DisplayObject2D::RegistrationPoint::CENTERCENTER);
        c->setColor(Color(Rand::randFloat(),Rand::randFloat(),Rand::randFloat()));
        c->setScale(Rand::randInt(50,100));
        c->setPos( event.getPos() );
        c->fadeOutAndDie();
        mContainer.addChild(c);
    }else{
        Square *s = new Square();
        s->setRegPoint(rph::DisplayObject2D::RegistrationPoint::CENTERCENTER);
        s->setColor(Color(Rand::randFloat(),Rand::randFloat(),Rand::randFloat()));
        s->setSize(Rand::randInt(50,100),Rand::randInt(50,100));
        s->setPos( event.getPos() );
        s->fadeOutAndDie();
        mContainer.addChild(s);
    }
}
Esempio n. 27
0
QDebug operator<<(QDebug out, const Square & square )
{
    QString dirs;
    Square * other( NULL );

    other = square.GetSquare( DIRECTION_UP );
    dirs += ( other == NULL ? "NA" : QString::number(other->GetID()) );
    dirs += " ";
    other = square.GetSquare( DIRECTION_RIGHT );
    dirs += ( other == NULL ? "NA" : QString::number(other->GetID()) );
    dirs += " ";
    other = square.GetSquare( DIRECTION_DOWN );
    dirs += ( other == NULL ? "NA" : QString::number(other->GetID()) );
    dirs += " ";
    other = square.GetSquare( DIRECTION_LEFT );
    dirs += ( other == NULL ? "NA" : QString::number(other->GetID()) );

    out << quint32( square.GetID() )
        << quint32( square.GetRow() )
        << quint32( square.GetColumn() )
        << dirs;

    return out;
}
Esempio n. 28
0
void Table::Load(){
	outputTable = fopen("Saved_Table.txt", "r");
	while (!feof(outputTable)){
		Square newS;
		point LT, RB;
		color MC, BC;
		int b;
		fscanf(outputTable, "%d %d\n", &LT.x, &LT.y);
		fscanf(outputTable, "%d %d\n", &RB.x, &RB.y);
		fscanf(outputTable, "%d\n", &b);
		fscanf(outputTable, "%d %d %d\n", &MC.R, &MC.G, &MC.B);
		fscanf(outputTable, "%d %d %d\n", &BC.R, &BC.G, &BC.B);
		newS.setLeftTop(LT);
		newS.setRightBottom(RB);
		newS.setBorderWidth(b);
		newS.setMainColor(MC);
		newS.setBorderColor(BC);
		push(newS);		
	}
	fclose(outputTable);
}
void TardyMoveGenerator::generateEvasions(const Position& position, CheckState cs, Moves& moves) {
  Turn turn = position.getTurn();
  Square king = turn == Turn::Black ? position.getBlackKingSquare() : position.getWhiteKingSquare();

  if (!isDoubleCheck(cs)) {
    ::generateMoves(position, moves, [king, cs](PieceType pieceType, Square to) {
      if (pieceType == PieceType::king()) {
        return false;
      }

      auto dir = king.dir(cs.from1);

      for (auto s = king.move(dir); ; s = s.move(dir)) {
        if (s == to) { return true; }
        if (s == cs.from1) { break; }
      }

      return false;
    });
  }

  auto& list = MovableMap.find(PieceNumber::King)->second;
  for (auto& info : list) {
    Square to = king.safetyMove(info.dir);
    if (!to.isValid()) {
      continue;
    }

    Piece pieceTo = position.getPieceOnBoard(to);
    if ((turn == Turn::Black && pieceTo.isBlack()) ||
        (turn == Turn::White && pieceTo.isWhite())) {
      continue;
    }

    moves.add(Move(king, to, false));
  }
}
Esempio n. 30
0
bool MovementCommand::redo(Chessboard &board)
{
    Square *to = board.squareAt(toSquare());
    Square *from = board.squareAt(fromSquare());
    if (!to->isEmpty())
    {
        qCritical() << "Runtime error: square is not empty. AttackCommand should be used";
        return false;
    }

    if (from->isEmpty())
    {
        qCritical() << "Runtime error: square is empty";
        return false;
    }

    Piece* movedePiece = from->piece();
    markAsMoved(*movedePiece);
    board.removePiece(movedePiece);
    board.putPiece(to, movedePiece);
    qDebug() << "Move: " << Chess::toString(movedePiece->type()) << " " << from->toStr() << ":" << to->toStr();

    return true;
}