Skip to content

Instantly share code, notes, and snippets.

@espio999
Last active March 3, 2026 06:15
Show Gist options
  • Select an option

  • Save espio999/fea6f5a63b534cbc92715f31a3bfc148 to your computer and use it in GitHub Desktop.

Select an option

Save espio999/fea6f5a63b534cbc92715f31a3bfc148 to your computer and use it in GitHub Desktop.
OOP in JavaScript
class BasicRole {
constructor(name) {
if (this.constructor === BasicRole) {
throw new Error("BasicRoleは抽象クラスのため、インスタンス化できません。");
}
this.name = name;
}
attack() {
console.log(`${this.name}は攻撃した`);
}
guard() {
console.log(`${this.name}は身を守っている`);
}
run() {
//
console.log(`${this.name}は逃げ出した`);
}
}
class Fighter extends BasicRole {
doubleAttack() {
//
console.log(`${this.name}の2回攻撃!`);
this.attack();
this.attack();
}
guard() {
console.log(`${this.name}の防御力強化`);
}
}
class Magician extends BasicRole {
magic() {
console.log(`${this.name}は呪文を唱えた!`);
}
}
class Priest extends BasicRole {
pray() {
console.log(`${this.name}は祈りをささげた!`);
}
}
// バトル処理
function battle(party, command) {
function special(member) {
if (member instanceof Fighter) {
member.doubleAttack();
} else if (member instanceof Magician) {
member.magic();
} else if (member instanceof Priest) {
member.pray();
}
}
for (let i = 0; i < party.length; i++) {
switch (command[i]) {
case 1:
party[i].attack();
break;
case 2:
party[i].guard();
break;
case 3:
party[i].run();
break;
default:
special(party[i]);
break;
}
}
}
function main() {
const rhodesia = new Fighter("ローデシア");
const sumaltria = new Magician("サマルトリア");
const moonburg = new Priest("ムーンブルグ");
const party = [rhodesia, sumaltria, moonburg];
console.log("--- ターン 1 ---");
battle(party, [4, 4, 4]);
console.log("\n--- ターン 2 ---");
battle(party, [2, 1, 3]);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment