♥️Hero health

Si consideri un videogame dove il personaggio del giocatore è modellato da questa classe:

initial.cpp
class Player {
private:
int health;
public:
Player(int initial Health): health(initial Health) {}
int getHealth() const { return health; }
void receiveDamage(int damage) { health -= damage; } void useStimPack(int healing) { health += healing; }
void move() { /* Movement logic */ }
void fight() { /* Fighting logic */ }
};i

Le componenti della interfaccia utente del gioco (per esempio lo head-up display) e del sistema audio devono essere notificati quando lo stato di salute (health) cambia: la componente Ul deve mostrare lo stato attuale di salute, mentre la componente audio suona una musica quando la salute aumenta, ed una musica diversa quando diminuisce o diventa 0. Si implementi un sistema basato sul pattern Observer (14 punti).

Si disegni il diagramma UML di classe (2 punti).

Risposta Accettata

main.cpp
#include <iostream>
#include <list>
#include <string>
using namespace std;

class Observer {
public:
    virtual void update()=0;
};

class Subject{
public:
    virtual void notify()=0;
    virtual void addListener(Observer*)=0;
};

class Player : public Subject {
private:
    int health;
public:
    list <Observer*> obsList;

    int message;

    void notify() override {
        message = health;
        for (auto i : obsList){
            i -> update();
        }
    }

    void addListener(Observer* o) override {
        obsList.push_back(o);
    }
    explicit Player(int initialHealth) : health(initialHealth) {}

    int getHealth() const {
        return health;
    }
    void receiveDamage(int damage){
        health -= damage;
        notify();
    }
    void useStimPack(int healing){
        health += healing;
        notify();
    }
    void move() {}
    void fight() {}
};

class Display : public Observer {
private:
    Player* p;
public:
    Display (Player* P):p(P){
        p->addListener(this);
    }
    void update() override {
        int current_message= p->message;
        cout << "current health now is " << current_message << endl;
    }
};

class Sound : public Observer{
private:
    Player* p;
    void healthGainSound(){
        cout<<"Launched: healthGainSound()"<<endl;
    };
    void healthLossSound(){
        cout<<"Launched: healthLossSound()"<<endl;
    };

    int lastHealth = p->getHealth();

public:
    Sound (Player* P):p(P){
        p->addListener(this);
    }
    void update() override {
        if (p->getHealth() > lastHealth){
            healthGainSound();
        } else {
            healthLossSound();
        }
        lastHealth = p->getHealth();
    }
};


int main() {
    Player player(10);
    Display display(&player);
    Sound sound(&player);
    player.receiveDamage(5);
    player.useStimPack(3);

    return 0;
}

Last updated