使用精灵作为健康栏

时间:2018-08-19 14:20:00

标签: python pygame sprite

最近,我终于设法在每个匹配之间实现了一个带有I帧的健康栏。但是,它看起来不整洁,因为我用于运行状况栏的所有内容都是pygame绘制的一条红线。取而代之的是,我希望使用每次击中玩家时都会减少半个心的心。

我的问题是;当我的健康状况超过特定点时,如何更新健康状况栏?我尝试的每种方法似乎都无效。

我的工作代码如下;

游戏类

import pygame
from constants import *
from player import Player
from enemy import Enemy


pygame.init()

screen = pygame.display.set_mode([500, 500])

pygame.display.set_caption('Labyrinth')

# Spawn player

player = Player(50, 50)
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(player)


# Spawn enemy

enemy = Enemy(150, 150)
enemy_sprites = pygame.sprite.Group()
enemy_sprites.add(enemy)


healthbar = HealthBar.Health_Bar(10, 10)
health_bar = pygame.sprite.Group()
health_bar.add(healthbar)




clock = pygame.time.Clock()

done = False


# ----- Event Loop

while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_UP:
                player.changespeed(0, -3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, 3)

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_UP:
                player.changespeed(0, 3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, -3)


# ----- Game Logic

    all_sprites_list.update()
    enemy_sprites.update(player)

    player_hit_list = pygame.sprite.spritecollide(player, enemy_sprites, False)

    for hit in player_hit_list:
       player.hit_check(1)

       if player.is_dead():
           done = True



    screen.fill(WHITE)

    all_sprites_list.draw(screen)
    enemy_sprites.draw(screen)
    health_bar.draw(screen)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()

播放器类

from constants import *
import pygame
import time
from datetime import datetime, timedelta

class Player(pygame.sprite.Sprite):


    def __init__(self, x, y):

        super().__init__()

        self.image = pygame.Surface([15, 15])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.health = 10
        self.invincible_until = datetime.now()


        self.change_x = 0
        self.change_y = 0

    def changespeed(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        self.rect.x += self.change_x
        self.rect.y += self.change_y



# I-frames for when taking damage

# ---

    def can_take_damage(self):

        if datetime.now() < self.invincible_until:
            return False

        return True


    def hit_check(self, damage):

        if self.can_take_damage():
            self.health -= damage
            self.invincible_until = datetime.now() + timedelta(seconds = .5)


    def is_dead(self):

        return self.health <= 0

敌军阶级

from constants import *
import pygame

class Enemy(pygame.sprite.Sprite):


    def __init__(self, x, y):

        super().__init__()

        self.image = pygame.Surface([10, 10])
        self.image.fill(RED)

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

健康酒吧课

import pygame
import constants
from Spritesheet import SpriteSheet



class Health_Bar(pygame.sprite.Sprite):

    def __init__(self, x, y):

        super().__init__()

        health_frames = []

        sprite_sheet = SpriteSheet("full_heart.png")

        image = sprite_sheet.get_image(0, 0, 40, 40)
        health_frames.append(image)
        image = sprite_sheet.get_image(0, 0, 40, 30)
        health_frames.append(image)
        image = sprite_sheet.get_image(0, 0, 40, 20)
        health_frames.append(image)
        image = sprite_sheet.get_image(0, 0, 10, 30)
        health_frames.append(image)

        self.image = health_frames[0]
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

    def update(self):

        if player.health <= 5:
            self.image = health_frames[1]

SpriteSheet类

import pygame
import constants

class SpriteSheet(object):

    def __init__(self, file_name):

        self.sprite_sheet = pygame.image.load(file_name).convert()


    def get_image(self, x, y, width, height):

        image = pygame.Surface([width, height]).convert()
        image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
        image.set_colorkey(constants.BLACK)

        return image

常量类仅定义了几种颜色

下面是用于健康栏的心脏(在示例中,为简单起见,我只有两个阶段的健康栏)

enter image description here

enter image description here

谢谢您提供的任何帮助!

2 个答案:

答案 0 :(得分:2)

当玩家受到伤害时(或每帧调用一次),您必须调用update组或health_bar精灵的healthbar方法,以便它可以改变self.imageself.health_frames[1]

此外,health_frames列表必须是一个属性,否则您将无法使用update方法访问它。

class Health_Bar(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__()
        sprite_sheet = SpriteSheet("full_heart.png")
        self.health_frames = [
            sprite_sheet.get_image(0, 0, 40, 40),
            sprite_sheet.get_image(0, 0, 40, 30),
            ]
        self.image = self.health_frames[0]
        self.rect = self.image.get_rect(topleft=(x, y))

    def update(self):
        if player.health <= 5:
            self.image = self.health_frames[1]

答案 1 :(得分:-1)

绘制健康栏应与绘制玩家角色完全分开。 (Ditto可以绘制其他GUI,例如得分,击杀,拥有什么)。

您通常应该在帧渲染代码的末尾进行GUI绘制,以便在其他所有内容之上绘制它。