본문 바로가기
Javascript

OOP(4)

by Doromi 2023. 11. 6.
728x90
반응형
게임 캐릭터와 캐릭터의 행동을 모델링하는 객체 지향 프로그래밍(OOP) 예시입니다.
// 게임 캐릭터 클래스 정의
class GameCharacter {
  constructor(name, health, damage) {
    this.name = name;
    this.health = health;
    this.damage = damage;
  }

  attack(target) {
    console.log(`${this.name}이(가) ${target.name}을(를) 공격합니다.`);
    target.takeDamage(this.damage);
  }

  takeDamage(amount) {
    this.health -= amount;
    if (this.health <= 0) {
      console.log(`${this.name}이(가) 전사했습니다.`);
    } else {
      console.log(`${this.name}의 남은 체력: ${this.health}`);
    }
  }
}

// 게임 캐릭터 객체 생성
const playerCharacter = new GameCharacter("플레이어", 100, 20);
const enemyCharacter = new GameCharacter("적", 80, 15);

// 게임 진행
playerCharacter.attack(enemyCharacter);
enemyCharacter.attack(playerCharacter);
GameCharacter 클래스를 정의하고, 게임 캐릭터의 속성과 메서드를 정의합니다. 캐릭터는 이름, 체력(health), 공격력(damage)을 가지며, attack 메서드로 다른 캐릭터를 공격하고, takeDamage 메서드로 피해를 받습니다.

두 개의 캐릭터 객체를 생성하고 서로를 공격하면서 게임이 진행됩니다. 이 예시는 객체 지향 프로그래밍을 사용하여 게임 캐릭터와 그들의 상호 작용을 모델링한 간단한 예시입니다.
728x90
반응형

'Javascript' 카테고리의 다른 글

Async Functions in Javascript  (0) 2024.04.01
OOP(5)  (0) 2023.11.07
OOP(3)  (0) 2023.11.05
OOP(2)  (0) 2023.11.05
OOP  (0) 2023.11.05