Now that we've got some fancy code coming along, it's time to move all of this to a function, so that we can use this dynamically to create other buttons, rather than copy and pasting the code over and over!
The conversion to a function is pretty straight forward. If you want more explanation than the code, check out the video tutorial on this above.
This function has the parameters of:
msg: What do you want the button to say on it.
x: The x location of the top left coordinate of the button box.
y: The y location of the top left coordinate of the button box.
w: Button width.
h: Button height.
ic: Inactive color (when a mouse is not hovering).
ac: Active color (when a mouse is hovering).
def button(msg,x,y,w,h,ic,ac): mouse = pygame.mouse.get_pos() if x+w > mouse[0] > x and y+h > mouse[1] > y: pygame.draw.rect(gameDisplay, ac,(x,y,w,h)) else: pygame.draw.rect(gameDisplay, ic,(x,y,w,h)) smallText = pygame.font.Font("freesansbold.ttf",20) textSurf, textRect = text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) gameDisplay.blit(textSurf, textRect)
Now that we have this button function, we need a way to pass other functions through it, so our buttons can actually "run" a function when clicked. To do this, we just need to add another parameter and then just pass the function object through it.