1
General / C++/SFML: display several shapes simultaneously on screen
« on: February 22, 2024, 11:05:51 am »
Hello. I'm a beginner in c++ and I'm learning SFML. I have coded a small program to simultaneously display several shapes of different size, color and position on the screen, but I don't understand why there is just one shape that is displayed when the code is executed. Please help me.
#include <SFML/Graphics.hpp>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!");
vector<sf::RectangleShape> vecRec(25);
srand(time(NULL));
int r, g, b = rand()%255+1;
sf::Vector2f recSize(rand()%40+20, rand()%40+20);
sf::Vector2f recPos(rand()%760+1, rand()%560+1);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
sf::RectangleShape rec;
rec.setFillColor(sf::Color(r,g,b));
rec.setSize(recSize);
rec.setPosition(recPos);
vecRec.push_back(rec);
/*for(auto& r: vecRec){
window.draw(r);
}*/
for(int i=0; i<vecRec.size();i++){
window.draw(vecRec[i]);
}
window.display();
}
return 0;
}
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!");
vector<sf::RectangleShape> vecRec(25);
srand(time(NULL));
int r, g, b = rand()%255+1;
sf::Vector2f recSize(rand()%40+20, rand()%40+20);
sf::Vector2f recPos(rand()%760+1, rand()%560+1);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
sf::RectangleShape rec;
rec.setFillColor(sf::Color(r,g,b));
rec.setSize(recSize);
rec.setPosition(recPos);
vecRec.push_back(rec);
/*for(auto& r: vecRec){
window.draw(r);
}*/
for(int i=0; i<vecRec.size();i++){
window.draw(vecRec[i]);
}
window.display();
}
return 0;
}