使用类命名/调用生成的对象

2024-04-20 14:12:12 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是使用同一类生成25个对象。你知道吗

我当前正在使用以下代码创建对象:

class Card:
    def __init__(self,pos):
        self.flipping = False
        self.images = loadanimationimages()
        self.frame = 0
        self.pos = pos
    def flip():
        self.flipping = True
    def update():
        if self.flipping:
            self.frame += 1
            self.frame %= len(self.images)
    def draw(screen):
        screen.blit(pygame.transform.smoothscale(self.images[self.frame],
        self.pos),55*scale).convert_alpha() #Continued.

def updatecards():  #Create the cards.
  cards = []
  for x in range(5):
     for y in range(5):
        cards.append(Card((x*92*scale+offsetx*scale,y*92*scale+offsety*scale)))

我知道我必须打电话给card.flip(),但我不知道如何打个人牌。救命啊?你知道吗


Tags: inposself目标fordefrangecard
1条回答
网友
1楼 · 发布于 2024-04-20 14:12:12

cards[10].flip()

因为你已经把每一张卡存储在一个列表中([]),而且它只是由一个整数索引的,所以要调用卡号10,你可以cards[9].<function>等等

另一种方法是在将卡片添加到卡片列表之前翻转卡片,但这可能会毁了你的游戏:)

while 1:
    cardNr = int(raw_input('Flip a card, any card of the total ' + str(len(cards)) + ': '))
    cards[cardNr-1].flip()  # -1 because humans don't count from 0 normally :)

将翻转用户选择要翻转的卡。你知道吗

由于您使用的是GUI,下面是一些示例代码:

while 1:
  ev = pygame.event.get()
  for event in ev:
    if event.type == pygame.MOUSEBUTTONUP:
      mouse = pygame.mouse.get_pos()
      clicked_cards = [c for c in cards if c.clicked(mouse)]
      for card in clicked_cards:
          if card:
              card.flip()

现在为您的卡添加一个函数,该函数可以:

def clicked(self, mouse):
    if mouse.x >= self.x and mouse.x <= self.x+self.width:
        if mouse.y >= self.y and mouse.y <= self.y+self.height:
            return self
    return False

如果我没有弄错的话,有一个更好的方法,通过card.Rect.collidepoint但是由于我在使用Pygame的早期就转向了其他GUI库,您需要阅读以下内容:

相关问题 更多 >