Filling rectangles using floodfill c++

Chris Anderson picture Chris Anderson · Jun 2, 2015 · Viewed 8.1k times · Source

I'm trying to make a grid of rectangles to look like a checkerboard and am having some trouble using BGI graphics. I have gotten my code to produce a series of rectangles, but every time I try to add color the entire display becomes white. Here is my current code:

#include <iostream>
#include <graphics.h>

using namespace std;


int main( )
{
    int e = 1;
    int gd = DETECT, gm;

   initgraph(&gd, &gm, "C:\\TC\\BGI");
   rectangle(0,0,160,160);
   for(int a=0;a<=160;a+=20) {
           for(int b=0;b<=160;b+=20) {
           if (a == 0) {   
                  rectangle(a*e,b*e,20*e,20*e); 
                  getch();
                  floodfill(a+1,b+1,RED);
              }
               else if ((160/a)%2 == 0) {
                  rectangle(a*e,b*e,20*e,20*e);
                  getch();
                  floodfill(a,b,RED);
              }
               else {
                   rectangle(a*e,b*e,20*e,20*e);
                   getch();
                   floodfill(100,100,BLACK); 
                   }
           } 
   } 

    while (!kbhit( ))
    {
       delay(1000);
    } 
    return 0;
}

Answer

The Dark picture The Dark · Jun 2, 2015

According to this web page the third parameter to floodfill is the color to use when looking for the border of the area to fill. It uses the current fill pattern and fill color to paint the area.

In your case it never finds a black or red border, so it fills the whole page with white.

To fix it, you could either

  1. Make your rectangle the right border color and set the fill color to red or black, and fix up the x,y positions of where you are filling from.

    or

  2. More simply use the bar function as Captain Obvlious commented.