我在pygame中制作跳棋,我想要一块棋子移动的方式是点击两下鼠标,但我不知道怎么做

2024-03-28 10:15:32 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我有一个拖动机制,下面是代码。有人知道我怎么做吗?所以第一次点击选择一个工件,第二次点击移动工件。只需将另一个鼠标按钮下放到第一个鼠标按钮下,什么都不会发生

while not game_over:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            start_x = event.pos[0]
            start_y = event.pos[1]
        if event.type == pygame.MOUSEBUTTONUP:
            end_x = event.pos[0]
            end_y = event.pos[1]

            board.valid_moves(start_x, start_y)
            board.get_mouse_pos_and_place(start_x, start_y, end_x, end_y)

1条回答
网友
1楼 · 发布于 2024-03-28 10:15:32

使用第一次单击鼠标时设置的变量。第二次单击鼠标时,进行移动。
None初始化start_xstart_y。单击鼠标时设置变量。再次单击鼠标时使用变量:

start_x = None
start_y = None

while not game_over:
    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.MOUSEBUTTONDOWN:

            if start_x == None and start_y == None:
                # select piece
                start_x, start_y = event.pos

            else:
                # do movement
                end_x, end_y = event.pos
                
                board.valid_moves(start_x, start_y)
                board.get_mouse_pos_and_place(start_x, start_y, end_x, end_y)

                # prepare for next move
                start_x = None
                start_y = None

通过检查第一次单击是否在工件上,可以改进算法:

if event.type == pygame.MOUSEBUTTONDOWN:

    if start_x == None and start_y == None:
        # select piece
        click_x, click_y = event.pos
               
        is_on_piece = # [...] check if click_x, click_y is on a piece
        if is_on_piece:
            start_x = click_x
            start_y = click_y 
  
        else:
            # [...]

相关问题 更多 >