Python 在课堂内外制作精灵
我所有的代码都是自己工作的。我需要开始把它全部链接到按钮上 问题:尝试将多个按钮设置为精灵以进行碰撞。我不知道课外怎么做 我有按钮在不同的类中工作,但无法让它们在同一个类中工作,原因很明显,第二个按钮的self.image正在覆盖第一个按钮Python 在课堂内外制作精灵,python,python-3.x,pygame,Python,Python 3.x,Pygame,我所有的代码都是自己工作的。我需要开始把它全部链接到按钮上 问题:尝试将多个按钮设置为精灵以进行碰撞。我不知道课外怎么做 我有按钮在不同的类中工作,但无法让它们在同一个类中工作,原因很明显,第二个按钮的self.image正在覆盖第一个按钮 class Icons(pygame.sprite.Sprite): def __init__(self, *args): pygame.sprite.Sprite.__init__(self, *args) self.image = py
class Icons(pygame.sprite.Sprite):
def __init__(self, *args):
pygame.sprite.Sprite.__init__(self, *args)
self.image = pygame.image.load("images/airbrushIC.gif").convert()
self.rect = self.image.get_rect()
ic1 = self.image
self.rect.x = 50
self.rect.y = 490
self.image = pygame.image.load("images/fillIC.gif").convert()
self.rect = self.image.get_rect()
ic2 = self.image
self.rect.x = 10
self.rect.y = 540
def update(self):
pygame.mouse.get_pos()
pygame.mouse.get_pressed()
此代码不必是类。但我不知道如何使图像成为一个精灵,而不是在一个类。如有任何帮助,我们将不胜感激。谢谢 您应该有一个通用图标类,而不是图标。 然后,您可以为每个按钮创建一个图标实例
class Icon(pygame.sprite.Sprite):
def __init__(self, image_name, pos, cb, cb_data, *args):
pygame.sprite.Sprite.__init__(self, *args)
self.image = pygame.image.load("images/" + image_name).convert()
self.rect = self.image.get_rect()
self.rect.x = pos[0]
self.rect.y = pos[1]
this.cb = cb # function to call when button is pressed
this.cb_data = cb_data # data to pass to the function
def pressed():
this.cb(cb_data)
然后在主功能中创建按钮:
ic1 = Icon("airbrushIC.gif", (50, 490), button_pressed, "airbrushIC")
ic2 = Icon("fillIC.gif", (10, 540), button_pressed, "fillIC")
buttons = [ic1, ic2]
def button_pressed(data):
print "Button pressed:" + str(data)
最后,对于每个鼠标按下事件,您都会查找按钮碰撞:
for b in buttons:
if b.rect.collidepoint(event.pos):
b.pressed()
您应该有一个通用图标类,而不是图标。 然后,您可以为每个按钮创建一个图标实例
class Icon(pygame.sprite.Sprite):
def __init__(self, image_name, pos, cb, cb_data, *args):
pygame.sprite.Sprite.__init__(self, *args)
self.image = pygame.image.load("images/" + image_name).convert()
self.rect = self.image.get_rect()
self.rect.x = pos[0]
self.rect.y = pos[1]
this.cb = cb # function to call when button is pressed
this.cb_data = cb_data # data to pass to the function
def pressed():
this.cb(cb_data)
然后在主功能中创建按钮:
ic1 = Icon("airbrushIC.gif", (50, 490), button_pressed, "airbrushIC")
ic2 = Icon("fillIC.gif", (10, 540), button_pressed, "fillIC")
buttons = [ic1, ic2]
def button_pressed(data):
print "Button pressed:" + str(data)
最后,对于每个鼠标按下事件,您都会查找按钮碰撞:
for b in buttons:
if b.rect.collidepoint(event.pos):
b.pressed()
图标
不应该是精灵
。它代表一组精灵。请删除精灵
超类,并保留精灵实例,或为单个图标创建一个类。另请参见:精灵组,它包含精灵列表并具有相关功能。图标
不应该是精灵
。它代表一组精灵。请删除精灵
超类,并保留精灵实例,或为单个图标创建一个类。另请参见:精灵组,它包含精灵列表并具有相关功能。