Home > Back-end >  SFML not drawing multiple Circles
SFML not drawing multiple Circles

Time:10-03

I am trying to program Tic Tac Toe in C with SFML. I have programmed it to draw a circle, once the left mouse button is click. Then when I click again, it redraws that circle in another position, instead of drawing another circle. I want to make it draw another circle in a different place.

I draw the Circle with the sf::CircleShape SFML data type, in a function called CreateO:

sf::CircleShape CreateO(float x_pos, float y_pos)
{
  // Radius: 50px                                                                                                                                                                                                   
  sf::CircleShape o(50);
  o.setFillColor(sf::Color::Black);
  o.setOutlineThickness(1);
  o.setOutlineColor(sf::Color::White);
  o.setPosition(x_pos, y_pos);
  return o;
}

In the Main function:

  sf::RenderWindow window(sf::VideoMode(900, 900), "Tic Tac Toe");
  sf::Event event;
  bool draw_o;
  float x_pos, y_pos;
  while (window.isOpen())
    {
      while (window.pollEvent(event))
    {
      switch (event.type)
        {
        case sf::Event::Closed: window.close(); break;
        case sf::Event::MouseButtonPressed:
              switch (event.mouseButton.button)
                {
                case sf::Mouse::Right:
                  draw_x = true;
                  draw_o = false;
                  x_pos  = event.mouseButton.x;
                  y_pos  = event.mouseButton.y;
                  break;
                default: break;
                }
              break;
            default: break;
            }
        }
      window.clear();
      if (draw_o) window.draw(CreateO(x_pos, y_pos)); // Called here.
      window.display();
    }

CodePudding user response:

Analyze that part of your code:

window.clear();
if (draw_o) window.draw(CreateO(x_pos, y_pos)); // Called here.
window.display();

It clears the whole window and draws one circle given from the function.

You only draw one circle in the game loop. To have multiple circles I recommend creating a circles vector, for example:

std::vector<sf::CircleShape> circles;

Than in the window.draw part you need to draw a whole vector using for-loop.

And your CreateO function can just add a circle to the vector if the draw_o is true.

  • Related