我会给
Game
a类
self.button = None
属性并在用户达到目标时分配按钮实例。要检查鼠标是否与按钮发生碰撞,可以使用
event.pos
pg.MOUSEBUTTONDOWN
事件并应用摄像机。我不得不给
Camera
a类
apply_mouse
方法,因为
只是一个元组,我需要负摄像机位置。
# In the `Game` class.
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
elif event.type == pg.MOUSEBUTTONDOWN:
if self.button is not None:
mouse = self.camera.apply_mouse(event.pos)
if self.button.rect.collidepoint(mouse):
print('Clicked!')
# Remove button from sprite groups and
# set self.button to None again.
button.kill()
self.button = None
# KEYDOWN events omitted.
elif event.type == pg.USEREVENT + 1:
self.text_object.kill()
self.text_object = Text((1760, 570), self.player.actions, self.font)
self.all_sprites.add(self.text_object)
# Check `if self.button is None` so that we don't add
# several buttons to the groups.
if self.button is None:
self.button = Button(self, 1060, 670)
class Button(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.all_sprites, game.buttons
pg.sprite.Sprite.__init__(self, self.groups)
self.image = pg.Surface((450, 335))
self.image.fill((0, 40, 200))
self.rect = self.image.get_rect(topleft=(x, y))
self._layer = 6
class Camera:
# I just added this method to the Camera class.
def apply_mouse(self, pos):
return (pos[0]-self.camera.x, pos[1]-self.camera.y)