Pygame似乎跳过了关于我是否再次单击的if语句

2024-10-04 05:22:15 发布

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

在实现棋子移动功能的过程中,我创建了一个系统,该系统应:

  1. 寻找一个点击
  2. 查看是否单击了一块
  3. 确定单击的是哪一块
  4. 单击要移动到的正方形
  5. 将所述块移动到所述正方形

我为此编写了以下代码:

        if event.type == pygame.MOUSEBUTTONDOWN and moving == False:
            mousepos = pygame.mouse.get_pos()
            roundedmouse1 = rounddown80(mousepos[0]) #function to found out what square was clicked
            roundedmouse2 = rounddown80(mousepos[1]) #function to found out what square was clicked
            mousecoords = [roundedmouse1,roundedmouse2]
            for key,value in piecepositionsdict.items():
                if int(value[0]) == int(mousecoords[0]) and int(value[1]) == int(mousecoords[1]):
                    x = coordstosquaredict[str(mousecoords)]
                    print("You have clicked",whatpiece(x),"on square",x)
                    print("Click a square to move the piece to:")
                    moving = True
                    time.sleep(0.5)
                    #this should be where the program stops until it gets another click
                    if event.type == pygame.MOUSEBUTTONDOWN and moving == True:
                        mousepos2 = pygame.mouse.get_pos()
                        roundedmouse21 = rounddown80(mousepos2[0])
                        roundedmouse22 = rounddown80(mousepos2[1])
                        mousecoords2 = [roundedmouse21, roundedmouse22]
                        print(mousecoords2)
                        print(piecepositionsdict[whatpiece(x)+"pos"])
                        piecepositionsdict[whatpiece(x)+"pos"] = mousecoords2
                        print(piecepositionsdict[whatpiece(x) + "pos"])

然而,程序直接通过了第二次点击检查,当我只点击一次时,它是如何打印出mousecoords 2等的

我做错了什么导致了这个错误


Tags: andtoposifpygameintprintsquare
2条回答

游戏是事件驱动的应用程序。在事件驱动的应用程序中,有一个主循环检查所有事件,并在检测到事件时执行代码。逻辑的起点始终是事件

在您的情况下,事件是单击按钮。您必须在代码中(在主循环中)只检查一次单击,然后确定代码必须执行的操作。如果同一事件可能触发不同的操作,则需要一些额外的逻辑或标志来确定应执行哪些操作

在您的情况下,您有一个事件(鼠标单击)和两个可能的操作,请检查单击了哪些块,或移动该块

因此,代码的设计应如下所示:

def check_and_grab(position):
    # code here

def move_piece(position):
    # code here

piece_grabbed = None

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTODOWN:
            if piece_grabbed is None:
                check_and_grab(event.pos)
            else:
                move_piece(event.pos)

piece_grabbed是一个存储抓取的工件的变量:如果是None,则没有抓取工件

check_and_grab(position)应检查单击位置是否有工件,如果有,则将piece_grabbed设置为该工件。它实现了第2点和第3点

move_piece(position)应将抓取的工件移动到新位置,然后再次设置grabbed_piece = None。它实现了你的第5点

您的代码将在单个帧中运行,并且代码在该帧中仅注册一次单击。你需要有一个每次点击屏幕都会被调用的函数

请参见下面我的示例:

#Holder for the piece you have selected
currentPiece = piece

##Mouse click event/function##
if currentPiece == None:
    getPiece()
else:
    movePiece()

##Get piece function##
def getPiece():
    #Your function here which sets
    #currentPiece to what you selected.

##Move function##
    def movePiece():
    #Moves the currentPieece to the selected spot

相关问题 更多 >