Python Fat Chicken Battle Development Record (5): Improve the Fat Chicken Movement

1. Move
left and right Similar to move right, add related code of move left
update: \chicken.py:

	self.moving_left = False
...
    if self.moving_left:
        self.rect.centerx -= 1

Update: \game_functions.py:

def check_events(chicken):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                chicken.moving_right = True
            elif event.key == pygame.K_LEFT:
                chicken.moving_left = True

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                chicken.moving_right = False
            elif event.key == pygame.K_LEFT:
                chicken.moving_left = False

Second, adjust the speed
Implementation method: add the speed attribute
If added to the Chicken class, it means that this is the attribute of the fat chicken, and different fat chickens should have the same speed in the game environment. For coordination, add it directly to the Settings class.
Add: \settings.py-Class Settings-def _ init _ (self):

        # 肥鸡设置
        self.chicken_speed_factor = 1.5

Update: \chicken.py:

...
class Chicken():
    def __init__(self, screen, fcw_settings):
        """肥鸡初始化"""
        self.screen = screen
        self.fcw_settings = fcw_settings

        # 加载肥鸡图像并获取其外接矩形
        self.image = pygame.image.load('images/QQChicken.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # 将肥鸡放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
        
        # 转化小数值
        self.center = float(self.rect.centerx)

        # 移动标志
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """根据移动标志调整肥鸡位置"""
        if self.moving_right:
            self.center += self.fcw_settings.chicken_speed_factor
        if self.moving_left:
            self.center -= self.fcw_settings.chicken_speed_factor
            
        # 根据center更新rect
        self.rect.centerx = self.center
...

Update: \FatChickenWars.py-def run_game():

...
    chicken = Chicken(screen, fcw_settings)
...

3. Limit the range of activities to
prevent fat chickens from running out of the screen.
Update: \chicken.py-def update(self):

...
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.fcw_settings.chicken_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.fcw_settings.chicken_speed_factor
...

2021.1.21

Guess you like

Origin blog.csdn.net/k1095118808/article/details/112920658