Я предполагаю, что вы сохранили плитки в списке.Вы можете разделить координаты события на пол, чтобы получить индексы плиток в вашем списке.Например, если вы нажмете на (164, 97) и поделите эти координаты на пол по размеру плитки (20), вы получите индексы (8, 4) и сможете использовать их, чтобы поменять плитку.
import itertools
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
tilesize = 20
IMG1 = pg.Surface((tilesize, tilesize))
IMG1.fill((0, 70, 170))
IMG2 = pg.Surface((tilesize, tilesize))
IMG2.fill((180, 200, 200))
img_cycle = itertools.cycle((IMG1, IMG2))
# A list of lists of lists which contain an image and a position.
tiles = []
# I create a checkerboard pattern here with the help of the `next`
# function and itertools.cycle.
for y in range(20):
row = []
for x in range(30):
# I add a list consisting of an image and its position.
row.append([next(img_cycle), [x*tilesize, y*tilesize]])
next(img_cycle)
tiles.append(row)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
# Use floor division to get the indices of the tile.
x = event.pos[0] // tilesize
y = event.pos[1] // tilesize
print(event.pos, x, y)
if event.button == 1: # Left mouse button.
# Replace the image at indices y, x.
tiles[y][x][0] = IMG1
elif event.button == 3: # Right mouse button.
tiles[y][x][0] = IMG2
# Blit the images at their positions.
for row in tiles:
for img, pos in row:
screen.blit(img, pos)
pg.display.flip()
clock.tick(30)
pg.quit()