user12210905
user12210905

Reputation:

How to generate random pixels around the screen?

I'm setting my new code, and i have an problem with code. The box is always located at the top left in the screen.

let me explain the code. r is need to generate random locations around the screen. r + 256 is specify the animated pixels size ( 256 ) is creating a box. RGB is just a the colors of the box.

How do i do that the box will generated in random location around the screen ?

I tried to play with the code, change the variables , etc.

int main() 
{

    int r = rand() % 400;
    HDC hdc = GetDC(GetDesktopWindow());

    while (true)
    {
        srand(time(NULL));
        srand(GetTickCount64());
        for (int x = r; x < r + 256; x++)
        for (int y = r; y < r + 256; y++)
        SetPixel(hdc, x, y, RGB(127, x % 256, y % 256));
    }
    return 0;
}

I'm not getting any errors.

Upvotes: 0

Views: 796

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

int r = rand() % 400; is only evaluated once, with the same starting point ("seed") for the random number generator every time you start the program.
Thus, r always has the same value.

Calling srand does not update r; it sets the seed for subsequent uses of rand.

You need to

  • generate a new random number every time you want a different number,
  • only seed the random number generator once, and before using rand.

So,

int main() 
{

    srand(time(NULL));
    HDC hdc = GetDC(GetDesktopWindow());

    while (true)
    {
        int r = rand() % 400;
        for (int x = r; x < r + 256; x++)
            for (int y = r; y < r + 256; y++)
                SetPixel(hdc, x, y, RGB(127, x % 256, y % 256));
    }
    return 0;
}

Upvotes: 3

Related Questions