如何使用鼠标和键盘检测在 pygame 中编辑数独网格?

how can I edit a sudoku grid in pygame using mouse and keyboard detection?

我想在数独网格上插入值,使用 pygame,编辑内部矩阵。如果用户单击一个空单元格,我希望他们能够选择一个键盘编号,并且内部矩阵将更新,这个数字在相应的单元格中。现在,我的循环代码如下所示:

while custom:
    pygame.display.flip()
    screen.blit(bgCustom, (0, 0))
    for event in pygame.event.get():
        if (event.type == pygame.MOUSEBUTTONDOWN):
            setGrid(board)

setGrid 看起来像这样:

def setGrid(board):
    position = pygame.mouse.get_pos()
    x = position[0]
    y = position[1]
    #print(y, x)
    line = x // 92
    col = y // 80
    #print(col, line)
    #print(board)

    for event in pygame.event.get():
        if event.type == pygame.KEYUP   :
            if event.key == pygame.K_1:
                board[line][col] = 1
                print(board)
            elif event.key == pygame.K_2:
                board[line][col] = 2
            elif event.key == pygame.K_3:
                board[line][col] = 3
            elif event.key == pygame.K_4:
                board[line][col] = 4
            elif event.key == pygame.K_5:
                board[line][col] = 5
            elif event.key == pygame.K_6:
                board[line][col] = 6
            elif event.key == pygame.K_7:
                board[line][col] = 7
            elif event.key == pygame.K_8:
                board[line][col] = 8
            elif event.key == pygame.K_9:
                board[line][col] = 9

没有语法错误,但棋盘仍未编辑。我的猜测是,当用户激活 setGrid 时,计算机会立即尝试检测键盘输入,但用户不会 "fast enough" 使该功能起作用。我考虑过制作某种等待功能,等待键盘输入,但我不希望用户卡在 setGrid 中。有什么想法吗?

提前致谢

您必须设置一个由 None 初始化的变量 (clicked_cell)。单击单元格时,将带有行和列的元组分配给单元格。按下按钮后重置变量:

clicked_cell = None

while custom:
    # [...]

    for event in pygame.event.get():

        if event.type == pygame.MOUSEBUTTONDOWN:

            line = event.pos[0] // 92
            col = event.pos[1] // 80
            clicked_cell = (line, col)

        if event.type == pygame.KEYUP:

            if clicked_cell != None:
                if pygame.K_1 <= event.key <= pygame.K_9:

                    line, col = clicked_cell
                    clicked_cell = None

                    number = int(event.unicode)
                    board[line][col] = number

    # [...]