I've recently picked up SFML and I'm trying to make a simple tic tac toe game, but I cannot figure out how to take input from the keyboard, and draw a sprite that stays there even after the key isn't pressed.
I know its probably very simple, but I cannot figure out how to do it at all. At the moment, the cross is only drawn when the key is down, and gets removed once it is not pressed.
Some help please!
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window (sf::VideoMode(600,600), "TIC TAC TOE");
sf::Texture Grid_Texture;
sf::Texture Cross_Texture;
Grid_Texture.loadFromFile("Grid.png");
Cross_Texture.loadFromFile("Cross.png");
sf::Sprite Grid;
sf::Sprite Cross;
Grid.setTexture(Grid_Texture);
Cross.setTexture(Cross_Texture);
Cross.setPosition(-200,-200);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.draw(Grid);
window.display();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Numpad7))
{
Cross.setPosition(0,0);
window.draw(Grid);
window.draw(Cross);
window.display();
}
}
}
Why should it stay? You only call the draw() method inside the if block. That means that the sprite is only drawn when the key is pressed. You want something like a boolean that keeps track if the key has been pressed in the past:
bool drawSprite = false;
Cross.setPosition(0,0);
// ...
while(window.isOpen())
{
// .. poll the events
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Numpad7)
{
drawSprite = true; // only draw it if the key has been pressed
}
} // ... end polling events
window.clear(sf::Color::Black);
window.draw(Grid);
if (drawSprite)
{
window.draw(Cross);
}
window.display();
}
EDIT: Nexus was faster ;)