Skip to content
This repository has been archived by the owner on Nov 15, 2022. It is now read-only.

Klasa Block

Antek Bizon edited this page Mar 5, 2022 · 1 revision

Klasa Block

Odpowiada za platformy, po których gracz może się poruszać, a inne obiekty odbijać. Wyróżnia się trzy rodzaje platform (PLATFORM_1, PLATFORM_2, WALL). Tekstura ustalana jest na podstawie podanego rodzaju Blocku. Do rysowania wykorzystuje się małą teksturę, która jest powielana na całą wielkość Blocku. Akcja kolizji tyczy się tylko PLATFORM_2, którą gracz jest w stanie zniszczyć. Funkcja odejmuje dotychczasową ilość życia i w momencie, gdy osiągnie 0 obiekt ustawia swój stan na FINISHED i odgrywany jest dźwięk niszczenia.

class Block : public Sprite {
public:
    enum class Kind {
        WALL,
        PLATFORM_1,
        PLATFORM_2
    };

    Block(Game* game, float x, float y, float width, float height, Kind type);
    Block(Game* game, std::ifstream&);
    virtual void Draw();
    virtual void Collision(Sprite*);
    virtual void Save(std::ofstream&);
    short int health = 2;

private:
    Texture2D* texture;
    Kind kind;
};

Block::Block(Game *game, float x, float y, float width, float height, Kind kind)
    : Sprite(game, Position(x, y, width, height), Sprite::Type::BLOCK), kind(kind) {
    switch (kind) {
    case Kind::PLATFORM_1:
        texture = &game->textures[PLATFORM_1];
        break;
    case Kind::PLATFORM_2:
        texture = &game->textures[PLATFORM_2];
        break;
    default:
        texture = &game->textures[WALL];
    }
}

Block::Block(Game* game, std::ifstream& s)
    : Sprite(game, Position(s), Sprite::Type::BLOCK) {
    int k;
    Read(s, &k);
    kind = static_cast<Block::Kind>(k);

    switch (kind) {
    case Kind::PLATFORM_1:
        texture = &game->textures[PLATFORM_1];
        break;
    case Kind::PLATFORM_2:
        texture = &game->textures[PLATFORM_2];
        break;
    default:
        texture = &game->textures[WALL];
    }
}

void Block::Draw() {
    DrawTextureTiled(*texture, { 0, 0, 20, 20 }, position.rectangle, { 0, 0 }, 0, 1, WHITE);
}

void Block::Collision(Sprite* sprite) {
    if (kind == Kind::PLATFORM_2) {
        health--;
        if (health == 0) {
            state = State::FINISHED;
            PlaySound(game->audio[WALL_DESTRACTION]);
        }
    }
}

void Block::Save(std::ofstream& s) {
    int t = static_cast<int>(type);
    Write(s, &t);
    position.Save(s);
    int k = static_cast<int>(kind);
    Write(s, &k);
}
Clone this wiki locally