我正在尝试使这个名为 Button
的 Sprite 可点击。它会在玩家到达目标后出现,单击它后, Sprite 应该会在新 map 中消失。我也会这样做,以便在单击 Sprite 后将加载新关卡,但现在让我们继续完成单击 Sprite 并因此发生一些事情。
这是感兴趣的代码:
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.game = game
self.image = pg.Surface((450, 335))
self.image = game.alert_img
self.rect = self.image.get_rect()
self.x = x
self.y = y
self._layer = 2
self.rect.x = x * TILESIZE
self.rect.y = y * TILESIZE
def events(self):
# catch all events here
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_LEFT:
self.player.move(dx=-1)
if event.key == pg.K_RIGHT:
self.player.move(dx=1)
if event.key == pg.K_UP:
self.player.move(dy=-1)
if event.key == pg.K_DOWN:
self.player.move(dy=1)
if 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)
Button(self, self.player.x -1.5, self.player.y - 2.4)
请注意,事件位于主类中,而类按钮显然不在主类中。我的观点是 def 事件不在按钮类中。
编辑 两个答案都在下面,但是 skrx 他的回答更适合我的个人项目,根据您想要完成的任务,我的解决方案可能更适合您。我建议仔细查看两者。
最佳答案
我会给 Game
类一个 self.button = None
属性,并在用户达到目标时分配按钮实例。要检查鼠标是否与按钮发生碰撞,可以使用 pg.MOUSEBUTTONDOWN 事件的 event.pos 并应用相机。我必须为 Camera
类提供一个 apply_mouse
方法,因为 event.pos
只是一个元组,我需要负相机位置。
# 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)
关于python-3.x - 如何使该 Sprite 可点击,然后关闭它以便渲染新 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46303352/