Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save josecarneiro/7dc544959052957a30586210487a79c1 to your computer and use it in GitHub Desktop.
Save josecarneiro/7dc544959052957a30586210487a79c1 to your computer and use it in GitHub Desktop.
// Soldier
class Soldier {
constructor(a, b) {
this.health = a;
this.strength = b;
}
attack() {
return this.strength;
}
receiveDamage(damage) {
this.health -= damage;
}
}
// Viking
class Viking extends Soldier {
constructor(name, health, strength) {
super(health, strength); // Call the constructor of class we are extending
this.name = name;
}
receiveDamage(damage) {
this.health -= damage;
if (this.health > 0) {
return `${this.name} has received ${damage} points of damage`;
} else {
return `${this.name} has died in act of combat`;
}
}
battleCry() {
return 'Odin Owns You All!';
}
}
// Saxon
class Saxon extends Soldier {
receiveDamage(damage) {
this.health -= damage;
if (this.health > 0) {
return `A Saxon has received ${damage} points of damage`;
} else {
return `A Saxon has died in combat`;
}
}
}
// War
class War {
constructor() {
this.vikingArmy = [];
this.saxonArmy = [];
}
addViking(viking) {
this.vikingArmy.push(viking);
}
addSaxon(saxon) {
this.saxonArmy.push(saxon);
}
// genericAttack(attackingArmy, defendingArmy) {
// const indexDefender = Math.floor(Math.random() * defendingArmy.length);
// const attacker = attackingArmy[Math.floor(Math.random() * attackingArmy.length)];
// const defender = defendingArmy[indexDefender];
// const message = defender.receiveDamage(attacker.strength);
// if (defender.health <= 0) {
// defendingArmy.splice(indexDefender, 1);
// }
// return message;
// }
vikingAttack() {
// this.genericAttack(this.vikingArmy, this.saxonArmy);
const indexSaxon = Math.floor(Math.random() * this.saxonArmy.length);
const saxon = this.saxonArmy[indexSaxon];
const viking = this.vikingArmy[Math.floor(Math.random() * this.vikingArmy.length)];
const message = saxon.receiveDamage(viking.strength);
if (saxon.health <= 0) {
this.saxonArmy.splice(indexSaxon, 1);
}
return message;
}
saxonAttack() {
// return this.genericAttack(this.saxonArmy, this.vikingArmy);
const saxon = this.saxonArmy[Math.floor(Math.random() * this.saxonArmy.length)];
const viking = this.vikingArmy[Math.floor(Math.random() * this.vikingArmy.length)];
const message = viking.receiveDamage(saxon.strength);
this.vikingArmy = this.vikingArmy.filter(viking => {
return viking.health > 0;
});
return message;
}
showStatus() {
if (!this.saxonArmy.length) {
return 'Vikings have won the war of the century!';
} else if (!this.vikingArmy.length) {
return 'Saxons have fought for their lives and survived another day...';
} else {
return 'Vikings and Saxons are still in the thick of battle.';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment