0
\$\begingroup\$

I'm trying to create a simple recreation of the popular memory game "Simon" using C and SDL2. The idea is that the game is a small window with four squares of different colors that are purposefully dim. When the player clicks on a square, I want it to "light up" until the player let's go of their mouse button, in which it returns to it's original dim color.

I have this working to an extent, but the problem is that it only works if the player let's go of the mouse button while the pointer is over the square. If they let go anywhere else, the square stays lit up.

Here is the example code:

if(e.type == SDL_MOUSEBUTTONDOWN && mouseX >= 10 && mouseX <= 110 && mouseY >= 10 && mouseY <= 110) {
    if(e.button.button == SDL_BUTTON_LEFT) {
        SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
        SDL_RenderFillRect(renderer, &squareOne);
        SDL_RenderPresent(renderer);
    }
}

if(e.type == SDL_MOUSEBUTTONUP && mouseX >= 10 && mouseX <= 110 && mouseY >= 10 && mouseY <= 110) {
    if(e.button.button == SDL_BUTTON_LEFT) {
        SDL_SetRenderDrawColor(renderer, 0, 50, 0, 255);
        SDL_RenderFillRect(renderer, &squareOne);
        SDL_RenderPresent(renderer);
    }
} 

As you can see, I'm looking for the user to be clicking in a very specific area, and waiting for them to "unclick" in that same specific area. There has got to be a better way to do this. Would anyone do me the pleasure of offering a few hints?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Simply removing your if-statements concerning the position of the mouse cursor from the SDL_MOUSEBUTTONUP event check should work. That way the position would play a role if the mouse is clicked, but from what I could gather it doesn't matter where you release the mouse. So don't check for the mouse position on release.

A better way perhaps would be to split this behaviour into smaller class methods (or functions, in case you are doing this in pure C). Those hardcoded mouse position values won't last very long. You for an example might want to consider adding a boolean value to a Square struct, which could handle rendering the correct texture (or filled rectangle) to the screen, depending on the state of the boolean value.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thank you Tyyppi, that did the trick! Yeah, I am learning pure C and experimenting with SDL, so no classes unfortunately. Eventually I start fiddling around with C++. I shall take your advice and try to start using structs and functions and see what I can do :) \$\endgroup\$ Commented Sep 27, 2016 at 16:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .