0

Dear Developers and Community,

I am currently working on a Snake Game with Win32 API with GUI.

I am painting the Snake in the WndProc() Function within the WM_PAINT message, then I am creating the Painting Context and drawing the Rectangles.

But the problem is that the Snake is moving and the drawn Rectangles aren't disappearing anymore. So I called the Function InvalidateRect() in WndProc() to update my Window. That's working but after 42 steps with the snake, the Window is turning White and sometimes the Buttons(Minimize, Maximize, ...) also

Here is the Picture

Then I put the InvalidRect() call in a TimerRoutine with CreateTimerQueueTimer(). The Problem seemed solved but after many minutes it's happening again. Here is the Code:

VOID CALLBACK TimerRoutine(HWND lpParam, BOOLEAN TimerOrWaitFired)
{
    BoardEditing();
    InvalidateRect(lpParam, NULL, TRUE);
}

... In Main:

CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)TimerRoutine, hWnd, 0, 100, 0);

... In WndProc():

switch (message)
{
case WM_PAINT:
    hdc = BeginPaint(hWnd, &ps);
    if (GameOver == 1) {
        TextOut(hdc, 100, 100, gameover, _tcslen(gameover));
    }
    else {
        HBRUSH brushrot = CreateSolidBrush(RGB(255, 0, 0));
        HBRUSH brushgruen = CreateSolidBrush(RGB(0, 255, 0));
        HBRUSH brushschwarz = CreateSolidBrush(RGB(0, 0, 0));

        for (int y = 0; y < Board_Y; y++) {
            for (int x = 0; x < Board_X; x++) {

                RECT rect = { x * 30,y * 30,x * 30 + 29,y * 30 + 29 };
                if (Board[y][x] == 1) {
                    FillRect(hdc, &rect, brushrot);
                }
                else if (Board[y][x] == 2) {

                    FillRect(hdc, &rect, brushgruen);
                }
            }
        }
    }

    EndPaint(hWnd, &ps);

    break;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Flam3rboy
  • 95
  • 2
  • 7
  • 3
    You are creating GDI resources (e.g. brushes) every time you paint, but not destroying them or reusing them. You have a GDI resource leak. – Igor Tandetnik Apr 28 '18 at 13:54
  • How I can destroy them? – Flam3rboy Apr 28 '18 at 14:01
  • [GDI Objects](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724291(v=vs.85).aspx) – Axalo Apr 28 '18 at 14:12
  • 2
    @Flam3rboy: Rather than destroying and re-creating them every iteration, I'd consider creating them up-front, and just re-using the same ones when you have to re-draw. Granted, a snake game isn't likely to tax the system resources much, but still--it's better to minimize work when you can. – Jerry Coffin Apr 28 '18 at 14:24

0 Answers0