从鼠标单击的位置为2d数组创建索引时遇到问题。该程序应该通过检查鼠标单击相对于数组中每个正方形(正方形)的正方形(只有1d)来工作。正方形是来自称为正方形的类的对象的数组,该对象绘制在屏幕上。 2d数组是由1和0组成的数组,会随机生成为用户输入的大小。
仅当鼠标单击位置在正方形内时,才应创建新索引,并且仅生成该正方形的索引。
for n in range(len(squares)):
for square in squares:
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)
但是该程序为1d数组中的每个正方形生成2d数组索引,而不只是鼠标单击所在的正方形。
那么我如何使此代码按预期工作?
答案 0 :(得分:0)
似乎您只需要删除嵌套循环并使用索引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)
同时遍历索引和项目的惯用方式是enumerate列表:
for n, square in enumerate(squares):
if square.x < x < (square.x+17) and square.y < y < (square.y+17):
如果要处理网格,则还可以将鼠标坐标除以tileize大小,以得到索引。然后以这种方式将2D索引转换为1D索引:i = x + width*y
。这意味着您不必再遍历正方形即可检查碰撞。
下面是一个示例,其中包含pygame.Rect
的列表和颜色,您可以通过单击单元格来更改它们:
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()