So I just started learning SFML. So, I want to take an input x. And when x=1 the color of the rectangle that I created changes. Here is my code:
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
int main()
{
int x;
sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close |
sf::Style::Titlebar);
sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);
while (MW.isOpen()) {
sf::Event evnt;
while (MW.pollEvent(evnt)) {
switch (evnt.type) {
case sf::Event::Closed:
MW.close(); break;
}
}
cin >> x;
if (x == 1) {
bg.setFillColor(sf::Color::Blue);
}
MW.clear();
MW.draw(bg);
MW.display();
}
return 0;
}
Now the problem here that I am facing is that the window does not load properly. And when I move the 'cin' out of the loop, I can't seem to take an input at all.
You can use threads:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <mutex>
#include <thread>
int main() {
std::mutex xmutex;
int x = 0;
std::thread thr([&]() {
std::lock_guard<std::mutex> lock(xmutex);
int x;
std::cin >> x;
});
thr.detach();
sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close | sf::Style::Titlebar);
sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);
while (MW.isOpen()) {
sf::Event evnt;
while (MW.pollEvent(evnt)) {
switch (evnt.type) {
case sf::Event::Closed:
MW.close(); break;
}
}
{
std::lock_guard<std::mutex> lock(xmutex);
if (x == 1) {
bg.setFillColor(sf::Color::Blue);
}
}
MW.clear();
MW.draw(bg);
MW.display();
}
}