简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM