Python Pygame似乎跳过了关于我是否再次单击的if语句
在实现棋子移动功能的过程中,我创建了一个系统,该系统应:Python Pygame似乎跳过了关于我是否再次单击的if语句,python,pygame,Python,Pygame,在实现棋子移动功能的过程中,我创建了一个系统,该系统应: 寻找一个点击 查看是否单击了一块 确定单击的是哪一块 单击要移动到的正方形 将所述块移动到所述正方形 我为此编写了以下代码: if event.type == pygame.MOUSEBUTTONDOWN and moving == False: mousepos = pygame.mouse.get_pos() roundedmouse1 = rounddown80(mou
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等的
我做错了什么导致了这个错误?您的代码将在一个帧中运行,并且代码将在该帧中只注册一次单击。你需要有一个每次点击屏幕都会被调用的函数 请参见下面我的示例:
#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
游戏是事件驱动的应用程序。在事件驱动的应用程序中,有一个主循环检查所有事件,并在检测到事件时执行代码。逻辑的起点始终是事件 在您的情况下,事件是单击按钮。您必须在代码中(在主循环中)只检查一次单击,然后确定代码必须执行的操作。如果同一事件可能触发不同的操作,则需要一些额外的逻辑或标志来确定应执行哪些操作 在您的情况下,您有一个事件(鼠标单击)和两个可能的操作,请检查单击了哪些块,或移动该块 因此,代码的设计应如下所示:
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)
工件抓取
是存储抓取工件的变量:如果为无
,则未抓取工件
检查和抓取(位置)
应检查单击位置是否有工件,如果有,将抓取的工件设置为该工件。它实现了第2点和第3点
移动工件(位置)
应将抓取的工件移动到新位置,然后再次设置抓取的工件=无
。它实现了你的第5点。@rabbi76我已经做了两个单独的if语句来处理鼠标按下,所以我假设在我的鼠标按钮机械地向上移动后,至少在点击后一秒钟,我将不得不再次按下鼠标按钮,以便执行第二个if语句pass@Rabbid76这是否意味着我必须添加一些明确的事件?我试着把它放进去,但它没有改变任何事情。你可以找到一个完整的例子。这对OP没有任何帮助