PyGame MOUSEBUTTONDOWN 事件菜单问题
是的,这个标题确实没写好。
好吧,情况是这样的——我们有一个用Python编写的程序,使用了pyGame库,我们正在制作一个游戏。我们从一个菜单界面开始,文件名是main.py
。当用户点击菜单中的某个按钮时,就会执行一个动作。程序通过以下代码来检查用户是否点击了菜单项:
if event.type == pygame.MOUSEBUTTONDOWN:
mousePos = pygame.mouse.get_pos()
for item in buttons: # For each button
X = item.getXPos() # Check if the mouse click was...
Y = item.getYPos() # ...inside the button
if X[0] < mousePos[0] < X[1] and Y[0] < mousePos[1] < Y [1]:
# If it was
item.action(screen) # Do something
当用户点击“开始游戏”按钮时,它会打开一个子模块,文件名是playGame.py
。在这个子模块里,还有另一个pyGame循环等等。
游戏的一部分是按住左键鼠标,从当前位置“生长”出圆圈(这是一个益智游戏,这样做是有道理的)。以下是我用来实现这个功能的代码:
mouseIsDown == False
r = 10
circleCentre = (0,0)
[...other code...]
if mouseIsDown == True:
# This grown the circle's radius by 1 each frame, and redraws the circle
pygame.draw.circle(screen, setColour(currentColourID), circleCentre, r, 2)
r += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
runningLevel = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# User has pressed mouse button, wants to draw new circle
circleCentre = pygame.mouse.get_pos()
mouseIsDown = True
elif event.type == pygame.MOUSEBUTTONUP:
# Stop drawing the circle and store it in the circles list
mouseIsDown = False
newCircle = Circle(circleCentre, r, currentColourID)
circles.append(newCircle)
circleCount += 1
r = 10 # Reset radius
我遇到的问题是,用户在主菜单的左键点击会持续影响到playGame.py
模块,导致它创建并存储一个半径为10、位置在(0,0)的新圆圈。这两个都是默认值。
这个问题只在菜单之后的一个帧中发生。
有没有办法防止这种情况发生,还是说这是我代码中的一个缺陷?
非常感谢大家的帮助。如果你需要更多代码或对这些代码片段的解释,请告诉我。
如果你想要完整的代码,可以在GitHub上找到。
2 个回答
1
在Play
的开头加上pygame.event.clear()
,这样做能解决问题吗?
2
你可以在菜单中使用 MOUSEBUTTONUP,而不是 MOUSEBUTTONDOWN。