跳至正文
View Categories

< 1 min read

python开发打地鼠3 #

  1. 创建锤子类1
  2. 创建锤子类2

收获 #

掌握python类的使用方法,通过PyGame实践学会独立建立和更新项目,完成打地鼠游戏开发。

创建锤子类1 #

本小节为锤子类的构造函数定义。

class Hammer(pygame.sprite.Sprite):
    def __init__(self, images, position, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images = images
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.images[1])
        self.rect.left, self.rect.top = position
        # 用于显示锤击时的特效
        self.hammer_count = 0
        self.hammer_last_time = 4
        self.is_hammering = False

创建锤子类2 #

本小节为锤子类中锤子的位置函数、动作函数和屏显函数的设置。

##############################在Hammer类下,__init__()函数后面,添加下列新的功能函数###################
 '''设置位置'''
def setPosition(self, pos):
    self.rect.centerx, self.rect.centery = pos
'''设置hammering'''
def setHammering(self):
    self.is_hammering = True
'''显示在屏幕上'''
def draw(self, screen):
    if self.is_hammering:
        self.image = self.images[1]
        self.hammer_count += 1
        if self.hammer_count > self.hammer_last_time:
            self.is_hammering = False
            self.hammer_count = 0
    else:
        self.image = self.images[0]
    screen.blit(self.image, self.rect)

小结 #

本节介绍了锤子类的创建过程和功能函数的实现
需要掌握并实现如何使用pygame在项目中创建锤子类