PyGame Buttons, part 1, drawing the rectangle

Now that we've got this great start screen (not really), and we know how to draw shapes, we're curious about stepping things up a bit and we want to add buttons to our game. The only problem? We have no idea how to do buttons. Surely PyGame has some sort of buttons module built in right? No.

Do we give up?

..?

No! Instead, we see if we can just build our own. So far, we've shown how we can draw rectangles, so we can do that. We also know how to add text to the screen and center it, so there's that. How about making the button actually do something when clicked? This isn't something we've covered completely, but do you remember when we printed out all of the events in our event for loop? Contained in there was our mouse position and actions. With that, we can indeed know when a user has clicked within the bounds of our button. We can even take it a bit further and make our buttons "interactive" to a mouse hovering over them!

With all of that in mind, it's a multi-step problem, which we need to just take one step at a time. Let's get started!

The new game intro code:

def game_intro(): intro = True while intro: for event in pygame.event.get(): print(event) if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(white) largeText = pygame.font.Font('freesansbold.ttf',115) TextSurf, TextRect = text_objects("A bit Racey", largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.draw.rect(gameDisplay, green,(150,450,100,50)) pygame.draw.rect(gameDisplay, red,(550,450,100,50)) pygame.display.update() clock.tick(15)

The only change here is the addition of a couple of rectangles. Should be easy enough, since there's no topic being covered here.