Похоже, вам просто нужно удалить вложенный цикл и использовать индекс n
для доступа к текущему квадрату:
for n in range(len(squares)):
square = squares[n]
if square.x < x < (square.x+17) and square.y < y < (square.y+17):
j = int(n/width)
i = n - j*width
print(j,i)
Идиоматический способ перебирать индексы и элементы одновременновремя перечислять список:
for n, square in enumerate(squares):
if square.x < x < (square.x+17) and square.y < y < (square.y+17):
Если вы работаете с сеткой, вы также можете просто разделить координаты мыши по полу на размер плитки, чтобы получить индексы,Затем просто преобразуйте 2D-индексы в 1D-индекс следующим образом: i = x + width*y
.Это означает, что вам больше не нужно перебирать квадраты для проверки столкновений.
Вот пример со списком pygame.Rect
s и цветов, которые вы можете изменить, нажав на ячейку:
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
ORANGE = pg.Color(200, 100, 0)
BLUE = pg.Color('dodgerblue1')
tilesize = 27
width = 16
height = 10
# A list of pygame.Rects + colors.
squares = [[pg.Rect(x*tilesize, y*tilesize, tilesize-1, tilesize-1), ORANGE]
for y in range(height) for x in range(width)]
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
# Floor division by the tilesize to get the x and y indices.
x, y = event.pos[0]//tilesize, event.pos[1]//tilesize
if 0 <= x < width and 0 <= y < height: # Inside of the grid area.
i = x + width*y # Index of the 1D list.
print(x, y, i)
# I just toggle the color here.
squares[i][1] = BLUE if squares[i][1] == ORANGE else ORANGE
screen.fill(BG_COLOR)
for square, color in squares:
pg.draw.rect(screen, color, square)
pg.display.flip()
clock.tick(60)
pg.quit()