在实现棋子移动功能的过程中,我创建了一个系统,该系统应:
我为此编写了以下代码:
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等的
我做错了什么导致了这个错误
游戏是事件驱动的应用程序。在事件驱动的应用程序中,有一个主循环检查所有事件,并在检测到事件时执行代码。逻辑的起点始终是事件
在您的情况下,事件是单击按钮。您必须在代码中(在主循环中)只检查一次单击,然后确定代码必须执行的操作。如果同一事件可能触发不同的操作,则需要一些额外的逻辑或标志来确定应执行哪些操作
在您的情况下,您有一个事件(鼠标单击)和两个可能的操作,请检查单击了哪些块,或移动该块
因此,代码的设计应如下所示:
piece_grabbed
是一个存储抓取的工件的变量:如果是None
,则没有抓取工件check_and_grab(position)
应检查单击位置是否有工件,如果有,则将piece_grabbed
设置为该工件。它实现了第2点和第3点move_piece(position)
应将抓取的工件移动到新位置,然后再次设置grabbed_piece = None
。它实现了你的第5点您的代码将在单个帧中运行,并且代码在该帧中仅注册一次单击。你需要有一个每次点击屏幕都会被调用的函数
请参见下面我的示例:
相关问题 更多 >
编程相关推荐