Check if mouse pointer touching any rectangles created using for loop

Viewed 44

I'm currently creating a minesweeper game and my code looks something like this (for creating the rectangles). I've already created a list of every rectangle and their coordinates but there's one thing I now need. I need to know if the mouse pointer clicks on a rectangle (and which rectangle - each will have different information). When it clicks on one, it will check if that one has a bomb.

for i in range(1,boardSquaresY):
    global rectList
    for x in range(1,boardSquaresX):
        pygame.draw.rect(display,gray,pygame.Rect(squareX*x,squareY,tileSize,tileSize))
        rectList.append(Rect(squareX*x,squareY,tileSize,tileSize))
        print(rectList)
        for stroke in range(4):
            pygame.draw.rect(display, (0,0,0), pygame.Rect(squareX*x-2, squareY-2, tileSize + 2, tileSize + 2), 1)
            pygame.draw.rect(display, (220, 220, 220), pygame.Rect(squareX * x - 4, squareY - 4, tileSize + 2, tileSize + 2), 1)
            pygame.draw.rect(display, (150, 150, 150), pygame.Rect(squareX * x - 4, squareY - 4, tileSize + 0.5, tileSize + 1), 1)
    squareY += 50

Full code below (currently) - only done UI so far.

import pygame
from pygame.locals import *
#Beginner has a 9x9 board and 10 mines
rectList = []
def Main():
    pygame.init()

    display = pygame.display.set_mode((850,600),0,32)

    white = (255,255,255)
    blue = (0,0,255)
    gray = (220,220,220)
    display.fill(white)

    squareX = 50
    squareY = 50
    tileSize = 50
    boardSquaresX = 10
    boardSquaresY = 10
    mouse = pygame.mouse.get_pos()
    print(mouse)

    for i in range(1,boardSquaresY):
        global rectList
        for x in range(1,boardSquaresX):
            pygame.draw.rect(display,gray,pygame.Rect(squareX*x,squareY,tileSize,tileSize))
            rectList.append(Rect(squareX*x,squareY,tileSize,tileSize))
            print(rectList)
            for stroke in range(4):
                pygame.draw.rect(display, (0,0,0), pygame.Rect(squareX*x-2, squareY-2, tileSize + 2, tileSize + 2), 1)
                pygame.draw.rect(display, (220, 220, 220), pygame.Rect(squareX * x - 4, squareY - 4, tileSize + 2, tileSize + 2), 1)
                pygame.draw.rect(display, (150, 150, 150), pygame.Rect(squareX * x - 4, squareY - 4, tileSize + 0.5, tileSize + 1), 1)
        squareY += 50
    while True:
        mouse = pygame.mouse.get_pos()
        if mouse[0]
        if squareX * x + tileSize > mouse[0] > squareX * x - tileSize and squareY + tileSize > mouse[1] > squareY - tileSize:
            print(mouse)
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()
Main()
rectList = []
2 Answers

If you only want to know the row and column, you just need to test if the mouse is in the rectangle and calculate the row and column using the // (floor division) operator:

mouse = pygame.mouse.get_pos()
gridRect = pygame.Rect(0, 0, boardSquaresX*tileSize, boardSquaresY*tileSize)
if gridRect.collidePoint(mouse):
    row = mouse[0] // tileSize
    col = mouse[1] // tileSize

If you want to find the Rect object in the list, you can use pygame.Rect.collidelist:

mouse = pygame.mouse.get_pos()
muoseRect = pygame.Rect(mouse[0], mouse[1], 1, 1)
index = muoseRect.collidelist(rectList):
if index >= 0:
    rect = rectList[index]
    row = rect.x // tileSize
    col = rect.y // tileSize

See also How do I detect collision in pygame? and Pygame mouse clicking detection.

I usually do it like this:

grid = []
for y in range(5):
    grid.append([])
    for x in range(5):
        grid[y].append(0)

rectangle_size = 100

while True:
    mouse_pos = pygame.mouse.get_pos()
    for y in range(len(grid)):
        for x in range(len(grid[y])):
            if y * rectangle_size < mouse_pos[0] < y * rectangle_size + 50:
                if x * rectangle_size < mouse_pos[1] < x * rectangle_size + 50:
                    print(f"{y}, {x}")

Example:

import pygame
import sys
import random


pygame.init()

pygame.display.set_caption("hub")
screen = pygame.display.set_mode((500, 500))

grid = []
for y in range(5):
    grid.append([])
    for x in range(5):
        grid[y].append((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

rect_size = 100

while True:
    pygame.time.Clock().tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((0, 0, 0))

    mouse_pos = pygame.mouse.get_pos()
    for y in range(len(grid)):
        for x in range(len(grid[y])):

            pygame.draw.rect(screen, grid[y][x], (y * rect_size, x * rect_size, rect_size, rect_size))

            if y * rect_size < mouse_pos[0] < y * rect_size + 50:
                if x * rect_size < mouse_pos[1] < x * rect_size + 50:
                    print(f"{y}, {x}")
    pygame.display.update()
Related