Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - ashirinuim

Pages: [1]
1
General / how to make a grid
« on: August 14, 2020, 08:38:11 pm »
Hello everyone. I just started learning C++ and SFML today. As a hello world sort of program, I was hoping to make a grid with the feature that whenever the user clicks on a rectangle on the grid, the rectangle changes color. This is the code I have written.
However, this does not display anything on the screen. Here is my code (I have not yet implemented the logic of taking mouse input and changing the color of the rectangle on user input coz I can not get the grid working in the first place)

I tried using an array instead of the vector but even that doesn't help.

Any help would be appreciated.

#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>

const float WIDTH        = 512; //SCREEN WIDTH
const float HEIGHT       = 512; //SCREEN HEIGHT
const float BORDER_WIDTH = 2.0f; //Outline width

const sf::Vector2f rectSize(75.0f, 75.0f); //Rectangle size


int main()
{
    sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "need to make boxes!");

   std::vector<std::vector<sf::RectangleShape> > grid; //2D VECTOR of Rectangles

   //Initializing the grid
   for(int i = 0; i < 5; i++)
   {
      std::vector<sf::RectangleShape> v1(5);
      for(int j = 0; j < 5; j++)
      {
         sf::RectangleShape rect(rectSize);
         rect.setFillColor(sf::Color(255,255,255));
         rect.setOutlineThickness(BORDER_WIDTH);
         rect.setOutlineColor(sf::Color(0,0,0));
         v1.push_back(rect);
      }
      grid.push_back(v1);
   }

   //main loop
    while (window.isOpen())
    {
       //event loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        //Drawing the grid
        window.clear();

        for(int i = 0; i < 5; i ++)
       {
          for(int j = 0; j < 5; j++)
          {   
             //calculating the x and y coordinates
             //taking into considertation the Outline thickness
             float x = (rectSize.x + BORDER_WIDTH) * i;
             float y = (rectSize.y + BORDER_WIDTH) * j;

             grid[j].setPosition(x,y);
             window.draw(grid[j]);
          }
       }

        window.display();
    }
    return 0;
}

Pages: [1]