Gracz i przeciwnik dziedziczą z innej klasy? (klasy głównej?)
Jeśli chodzi o problem "2" to nie lepiej funkcja publiczna o nazwie "Atakuj" która przyjmuje jeden albo 2 parametry?
Jeden parametr to damage a drugi adres przeciwnika/gracza (Tu przychodzi z pomocąKlasa virtualna)
Albo może gracz/przeciwnika będzie posiadał funkcję "atakuj(Typ_danych przeciwnika)" (tu też się przyda klasa virtualna która informuje że klasa inna zawiera funkcję "atakuj")
Na szybko napisany przykład:
#include <iostream>
#include <conio.h>
using namespace std;
bool en = false;
class loncznik
{
public:
virtual void Defense(loncznik * Odkogo,int damage);
virtual void Atakuj(loncznik * przeciwnik);
};
class Gracz : public loncznik
{
int hp;
int damage;
public:
Gracz(int hps ,int damages): hp(hps) , damage(damages)
{}
void Atakuj(loncznik * przeciwnik)
{
przeciwnik->Defense(this,damage);
}
private:
void Defense(loncznik * Odkogo, int damage)
{
cout << this << " Dostaje od " << Odkogo << " " << damage << "obrazen!" << endl;
if(hp>damage)
hp -= damage;
else
{
cout << this << " umiera!";
hp = 0;
}
}
};
class Bot : public loncznik
{
int hp;
int damage;
public:
Bot(int hps ,int damages): hp(hps) , damage(damages)
{}
void Atakuj(loncznik * przeciwnik)
{
przeciwnik->Defense(this,damage);
}
private:
void Defense(loncznik * Odkogo, int damage)
{
cout << this << " Dostaje od " << Odkogo << " " << damage << "obrazen!" << endl;
if(hp>damage)
hp -= damage;
else
{
en = true;
cout << this << " umiera!";
hp = 0;
}
}
};
int main() {
Gracz player(100,10);
Bot bot(100,10);
while(!en)
{
player.Atakuj(&bot);
if(en) break;
bot.Atakuj(&player);
}
return 0;
}
O wiele lepszym pomysłem jest zrobienie takie coś:
#include <iostream>
#include <conio.h>
using namespace std;
bool en = false;
class live
{
int hp;
int damage;
public:
live(int hps ,int damages) : hp(hps) , damage(damages)
{}
void Atakuj(live * przeciwnik)
{
przeciwnik->Defense(this,damage);
}
private:
void Defense(live * Odkogo, int damage)
{
cout << this << " Dostaje od " << Odkogo << " " << damage << "obrazen!" << endl;
if(hp>damage)
hp -= damage;
else
{
en = true;
cout << this << " umiera!";
hp = 0;
}
}
};
class Gracz : public live
{
public:
Gracz(int hps ,int damages): live(hps,damages)
{}
};
class Bot : public live
{
public:
Bot(int hps ,int damages): live(hps,damages)
{}
};
int main() {
Gracz player(100,10);
Bot bot(100,10);
while(!en)
{
player.Atakuj(&bot);
if(en) break;
bot.Atakuj(&player);
}
return 0;
}