【问题标题】:How to create a user input on Pygame?如何在 Pygame 上创建用户输入?
【发布时间】:2020-03-13 17:10:25
【问题描述】:

我正在尝试为使用 python 制作的数独求解器创建用户界面。到目前为止,我可以显示一个 9x9 的网格,并且我希望用户能够单击一个块,输入一个数字,并对网格中的所有起始数字执行此操作。任何帮助,将不胜感激。

【问题讨论】:

  • 您好 Walid,欢迎来到 StackOverflow!到目前为止,您能分享您的代码,以及您尝试过的内容吗?

标签: python oop pygame


【解决方案1】:

您的代码需要一个事件循环,它在其中等待鼠标点击。当收到鼠标点击时,代码需要判断81个子矩形中的哪一个被点击了。

将窗口尺寸和网格大小存储在变量中:

# Window stuff
WINDOW_WIDTH  = 600
WINDOW_HEIGHT = 600
GRID_SIZE     = 9
GRID_WIDTH_X  = WINDOW_WIDTH  // GRID_SIZE
GRID_HEIGHT_Y = WINDOW_HEIGHT // GRID_SIZE

当收到鼠标点击事件时,只需将坐标除以匹配的网格大小即可得到点击位置的单元格索引。 X 表示 X 宽度,Y 表示 Y 高度。显然,这给出了一个从 0 开始的偏移量,将单元格编号为 [0,0] 到 [8,8]。

    elif ( event.type == pygame.MOUSEBUTTONUP ):
        # Where was the click on the screen?
        mouse_x, mouse_y = pygame.mouse.get_pos()
        cell_x = mouse_x // GRID_WIDTH_X
        cell_y = mouse_y // GRID_HEIGHT_Y
        print( "Click in cell [%d,%d]" % ( cell_x, cell_y ) )

然后可以编辑、更新此位置等。

完整来源:

import pygame

# Window stuff
WINDOW_WIDTH  = 600
WINDOW_HEIGHT = 600
GRID_SIZE     = 9
GRID_WIDTH_X  = WINDOW_WIDTH  // GRID_SIZE
GRID_HEIGHT_Y = WINDOW_HEIGHT // GRID_SIZE

BACKGROUND_COLOUR = ( 200, 200, 200 )
GRID_COLOUR       = ( 200,  10,  10 )

pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption( "Suduko Solver Question" )

clock   = pygame.time.Clock()
exiting = False
# Main Loop
while not exiting:

    # Handle User Input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            exiting = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            # Where was the click on the screen?
            mouse_x, mouse_y = pygame.mouse.get_pos()
            cell_x = mouse_x // GRID_WIDTH_X
            cell_y = mouse_y // GRID_HEIGHT_Y
            print( "Click in cell [%d,%d]" % ( cell_x, cell_y ) )


    # Draw the screen
    window.fill( BACKGROUND_COLOUR )
    for i in range( GRID_SIZE ):
        x_coord = i * GRID_WIDTH_X
        y_coord = i * GRID_HEIGHT_Y
        pygame.draw.line( window, GRID_COLOUR, ( x_coord, 0 ), ( x_coord, WINDOW_WIDTH-1 ) )
        pygame.draw.line( window, GRID_COLOUR, ( 0, y_coord ), ( WINDOW_WIDTH-1, y_coord ) )

    pygame.display.flip()
    clock.tick(60)  # limit FPS

pygame.quit()

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多