如何解决PyGame:MOUSEBUTTONDOWN 事件问题
我正在尝试在 PyGame 中构建一个国际象棋游戏。我的代码是这样的:
while running:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
select_piece(event.pos)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
# Will move the piece if it is selected:
if piece_currently_selected and event.pos == selected_piece_coordinates:
selected_piece_name = moves[selected_piece]
Position.move_piece(selected_piece_name,'d4')
piece_currently_selected = False # The piece has been moved,so we change this to False again.
我想要做的是:第一个 MOUSEDOWNEVENT 将选择用户点击的一块。如果用户没有点击该作品,它将简单地返回 None。第二个 MOUSEDOWNEVENT 实际上会将选定的片段移动到用户点击的新地址。
问题是,这两个事件几乎同时运行。一旦第一个 MOUSEDOWNEVENT 选择了该棋子,第二个 MOUSEDOWNEVENT 就会运行并立即移动它,然后用户才有机会点击新方块并将其移动到那里。
所以我需要做到这一点,以便用户首先单击以选择一块,然后单击不同的位置以将其移动到那里。我该怎么做?谢谢!
解决方法
您不能实现“第一个”和“第二个”MOUSEBUTTONDOWN
事件。事件不知道是第一次还是第二次。您必须实现 1 个 MOUSEBUTTONDOWN
事件并区分当前是否选择了一个作品:
while running:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if not piece_currently_selected:
# no pices is selected -> select a piece
select_piece(event.pos)
else:
# a pieces is selected -> move the piece
# [...]
# deselect the piece when the piece is successfully moved
piece_currently_selected = False
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。