pygame鼠标点击检测 [英] Pygame mouse clicking detection

查看:1293
本文介绍了pygame鼠标点击检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何编写代码来检测鼠标在精灵上的点击.例如:

I was wondering how to write code that would detect the mouse clicking on a sprite. For example:

if #Function that checks for mouse clicked on Sprite:
    print ("You have opened a chest!")

推荐答案

我假设您的游戏有一个主循环,并且所有子画面都位于一个名为sprites的列表中.

I assume your game has a main loop, and all your sprites are in a list called sprites.

在主循环中,获取所有事件,并检查MOUSEBUTTONDOWNMOUSEBUTTONUP事件.

In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.

while ... # your main loop
  # get all events
  ev = pygame.event.get()

  # proceed events
  for event in ev:

    # handle MOUSEBUTTONUP
    if event.type == pygame.MOUSEBUTTONUP:
      pos = pygame.mouse.get_pos()

      # get a list of all sprites that are under the mouse cursor
      clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
      # do something with the clicked sprites...

因此,基本上,每次主循环迭代时,您都必须自己检查是否单击了sprite.您将要使用 mouse.get_pos() rect.collidepoint().

So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().

Pygame不提供事件驱动的编程,例如 cocos2d 可以.

Pygame does not offer event driven programming, as e.g. cocos2d does.

另一种方法是检查鼠标光标的位置和所按按钮的状态,但是这种方法存在一些问题.

Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.

if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
  print ("You have opened a chest!")

如果处理这种情况,则必须引入某种标志,因为否则该代码将在主循环的每次迭代中打印您已经打开箱子了!" .

You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.

handled = False

while ... // your loop

  if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
    print ("You have opened a chest!")
    handled = pygame.mouse.get_pressed()[0]

当然,您可以继承Sprite的子类,并添加一个名为is_clicked的方法,如下所示:

Of course you can subclass Sprite and add a method called is_clicked like this:

class MySprite(Sprite):
  ...

  def is_clicked(self):
    return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())

因此,最好使用第一种方法恕我直言.

So, it's better to use the first approach IMHO.

这篇关于pygame鼠标点击检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆