Search code examples
pythonpygame

Selecting a specific rectangle with pygame


I am learning python and pygame, and I am trying to make a card game; I have made the basics of the logic, but I'm struggling with a simple GUI. I need to have a player be able to select a card from a draft row and place it on their 6x4 "board". For this I drew the rectangles like so:

class Board:
    def __init__(self):
        self.visible_draft = []
        self.placed_totems_P1 = [[]]
        self.placed_totems_P2 = [[]]

    def draw_card_base(self, window):
        window.fill(WHITE)
        for col in range(COLS):
            y = 770 - col*175
            for row in range(ROWS):
                x = row*175 + 40
                pygame.draw.rect(window, GREY, (x, y, CARD_SIZE, CARD_SIZE))
def main():
    board = Board()

    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
        board.draw_card_base(window)
        pygame.display.flip()

but now I'm stuck, because I have no idea how to let the player "pick" a slot where to put the chosen card (which I assume will be chosen the same way, just earlier). I read about the collisions, and thought about doing a manual "if the mouse is here, this is the slot where it is". Ideally I'd imagine I could read which card was chosen in maybe a 1A, 1B, 2C, sheet format, but I really just have no idea where to go from here. Hopefully this makes sense, it's possible I don't have a proper vocabulary to describe what I'm trying to say, I am still learning! Excited for answers, thanks!


Solution

  • Use pygame.Rect and collidepoint() to see if the mouse is on the board. Compute the row and the column of the mouse pointer:

    while run:
            clock.tick(60)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
    
                if event.type == pygame.MOUSEBUTTONDOWN:
    
                    mx, my = event;
                    
                    board_rect = pygame.Rect(40, 770 - ROWS*175, COLS*175, ROWS*175)
                    if board_rect.collidepoint(mx, my):
    
                        col = (mx - 40) // COLS
                        row = (my - 770 + ROWS*175) // ROWS
                     
                        print(col, row)
    

    See also Pygame mouse clicking detection.