如何处理棋盘中的鼠标光标移动事件?

How do I handle the mouse cursor move event in the checkered board?

我正在 Pygame 中绘制方格板,应使用鼠标光标更改其单元格。启动板时,该字段本身最初为红色。简而言之,鼠标光标应该用黄色“突出显示”单个单元格。我也希望当我将光标移动到任何其他单元格时,我刚才所在的那个单元格,回到它原来的红色。

这是我在网站上的第一个问题,对于可能出现的任何错误,我深表歉意。如果你能帮助我如何最终写出这个谜题,我将不胜感激 :) 这是我的代码的一部分:

#_____
YELLOW = (204, 250, 35)
RED = (255, 0, 0)

#_____
WIDTH = 80
HEIGHT = 80

SG = True # While

# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = []
for row in range(10):
    # Add an empty array that will hold each cell
    # in this row
    grid.append([])
    for column in range(20):
        grid[row].append(0)  # Append a cell

# --------START-----------
while SG:

    # ======
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            SG = False
        if i.type == pygame.MOUSEMOTION:

            pos = pygame.mouse.get_pos()
            # Change the x/y screen coordinates to grid coordinates
            column = pos[0] // (WIDTH)
            row = pos[1] // (HEIGHT)
            # Set that location to one
            grid[row][column] = 1
            print("Click ", pos, "Grid coordinates: ", row, column)

    # DRAWING THE BOARD
    for row in range(8):
        for column in range(15):
            color = RED
            if grid[row][column] == 1:
                color = YELLOW

            x = column *(WIDTH) + (column + 1)
            y = row * (HEIGHT) + (row + 1)
            pygame.draw.rect(screen, color, (x, y, WIDTH, HEIGHT), 1)

您根本不需要 MOUSEMOTION 活动。 pygame.mouse.get_pos() returns 表示鼠标光标当前 x 和 y 坐标的元组。只需测试在绘制单元格时鼠标是否悬停在单元格上即可:

while SG:

    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            SG = False
       
    for row in range(8):
        for column in range(15):
            pos = pygame.mouse.get_pos()
            mouse_column = pos[0] // (WIDTH + 1)
            mouse_row = pos[1] // (HEIGHT + 1)

            color = RED
            if row == mouse_row and column == mouse_column:
                color = YELLOW
            
            x = column * WIDTH + (column + 1)
            y = row *  HEIGHT + (row + 1)
            pygame.draw.rect(screen, color, (x, y, WIDTH, HEIGHT), 1)

    pygame.display.flip()