python 如何响应鼠标点击 PyGame 中的精灵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/380420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I respond to mouse clicks on sprites in PyGame?
提问by Eli Bendersky
What is the canonical way of making your sprites respond to mouse clicks in PyGame ?
在 PyGame 中使您的精灵响应鼠标点击的规范方法是什么?
Here's something simple, in my event loop:
这是一些简单的事情,在我的事件循环中:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game()
[...]
elif ( event.type == pygame.MOUSEBUTTONDOWN and
pygame.mouse.get_pressed()[0]):
for sprite in sprites:
sprite.mouse_click(pygame.mouse.get_pos())
Some questions about it:
关于它的一些问题:
- Is this the best way of responding to mouse clicks ?
- What if the mouse stays pressed on the sprite for some time ? How do I make a single event out of it ?
- Is this a reasonable way to notify all my sprites of the click ?
- 这是响应鼠标点击的最佳方式吗?
- 如果鼠标在精灵上停留一段时间会怎样?我如何制作一个单一的事件?
- 这是通知我的所有精灵点击的合理方法吗?
Thanks in advance
提前致谢
回答by Zoomulator
I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.
我通常给我的可点击对象一个点击功能,就像你的例子一样。我将所有这些对象放在一个列表中,以便在调用单击函数时轻松迭代。
when checking for which mousebutton you press, use the button property of the event.
检查您按下了哪个鼠标按钮时,请使用事件的按钮属性。
import pygame
from pygame.locals import * #This lets you use pygame's constants directly.
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN: #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code.
if event.button == 1:
for object in clickableObjectsList:
object.clickCheck(event.pos)
I would say this is the recommended way of doing it. The click only registers once, so it wont tell your sprite if the user is "dragging" with a button. That can easily be done with a boolean that is set to true with the MOUSEBUTTONDOWN event, and false with the MOUSEBUTTONUP. The have "draggable" objects iterated for activating their functions... and so on.
我会说这是推荐的方法。单击仅注册一次,因此它不会告诉您的精灵是否用户正在使用按钮“拖动”。这可以通过使用 MOUSEBUTTONDOWN 事件设置为 true 并使用 MOUSEBUTTONUP 设置为 false 的布尔值轻松完成。具有迭代的“可拖动”对象以激活它们的功能......等等。
However, if you don't want to use an event handler, you can let an update function check for input with:
但是,如果您不想使用事件处理程序,您可以让更新函数检查输入:
pygame.mouse.get_pos()
pygame.mouse.get_pressed().
This is a bad idea for larger projects, since it can create hard to find bugs. Better just keeping events in one place. Smaller games, like simple arcade games might make more sense using the probing style though.
对于较大的项目来说,这是一个坏主意,因为它会导致难以发现错误。最好将事件保存在一个地方。较小的游戏,比如简单的街机游戏,使用探索风格可能更有意义。