I am trying to learn Design patterns using OOP by building a game.
The game will have a predator and a prey. When a predator comes near the prey, it starts eating it. Until now, I have come so far.
I think I will need a mediator pattern here as there will be one alien (predator) and multiple humans (preys) walking on a given area of the game. The area being the mediator.
I won't be going in to the graphics part yet, but I just want to run on the command line like human1.reduceHP()
that will reduce human1
's HP. But, the condition for this code to happen is missing (I believe in the form of the Mediator).
However, I am unable to wrap my head around the actual implementation. I have come this far with the following:
Organism
as the base class andIEatable
as interface.Human
andAlien
are the concrete implementations of theOrganism
.Human
isIEatable
.
export abstract class Organism {
abstract maxHP: number;
abstract currentHP: number;
abstract canHit: boolean;
isStomachFull = false;
stomachCapacity = 100;
reduceHp() {
if (this.currentHP > 0) {
this.currentHP -= 1;
}
}
recoverHp() {
if (this.maxHP < this.currentHP) {
this.currentHP += 1;
}
}
}
interface IEatable {
isEatable: boolean;
}
import { Organism } from '../abstract/Organism';
export class Alien extends Organism {
maxHP: number;
currentHP: number;
canHit: boolean;
constructor(hp, canHit) {
super();
this.maxHP = hp;
this.canHit = canHit;
this.currentHP = this.maxHP;
}
}
import { Organism } from '../abstract/Organism';
export class Human extends Organism implements IEatable {
maxHP: number;
currentHP: number;
canHit: boolean;
isStomachFull: boolean;
stomachCapacity: number;
isEatable: boolean;
constructor(hp, canHit, isEatable) {
super();
this.maxHP = hp;
this.canHit = canHit;
this.currentHP = this.maxHP;
this.isEatable = isEatable;
}
}
Aucun commentaire:
Enregistrer un commentaire