Project_xxx
[Project_] JSROUGE - 2
wakelight23
2024. 11. 12. 22:18
JavaScript로 roguelike 장르의 게임 만들기 - 2
● 플레이어와 몬스터의 공격 주고 받기
// Player 클래스
class Player {
constructor() {
this.maxHp = 100;
this.currentHp = 100;
this.minAttackDmg = 8;
this.maxAttackDmg = 12;
}
// Player가 Monster를 공격할 때 계산되는 공식
attack(monster) {
// 소수점은 버리고 정수만 표시
const damage =
Math.floor(Math.random() * (this.maxAttackDmg - this.minAttackDmg + 1)) +
this.minAttackDmg;
monster.currentHp = Math.max(0, monster.currentHp - damage);
return damage;
}
}
// Monster 클래스
class Monster {
// stage가 증가할 때마다 몬스터가 강해진다
constructor(stage) {
this.maxHp = 50 + stage * 10;
this.currentHp = this.maxHp;
this.minAttackDmg = 2 + stage * 2;
this.maxAttackDmg = 6 + stage * 2;
}
// Monster가 Player를 공격할 때 계산되는 공식
attack(player) {
// 소수점은 버리고 정수만 표시
const damage =
Math.floor(Math.random() * (this.maxAttackDmg - this.minAttackDmg + 1)) +
this.minAttackDmg;
player.currentHp = Math.max(0, player.currentHp - damage);
return damage;
}
}
- Player, Monster를 클래스로 정의
- 필요한 스탯들을 this로 지정해서 기본적인 form 생성
- 공격이라는 행동을 attack()로 정의
- 랜덤 범위는 minattackDmg, maxattackDmg 의 사이 값
// Player가 Monster에게 데미지를 줬을 때 출력해줄 형태
const playerDamage = player.attack(monster);
// logs.push는 플레이어가 몬스터에게 공격했다는 것을 확인하기 위한 배열
logs.push(
`${chalk.yellow(`플레이어가 몬스터에게 ${playerDamage}의 데미지를 입혔습니다.`)}`,
);
// Monster의 currentHp가 0이 되면 전투 승리
if (monster.currentHp === 0) {
logs.push(`${chalk.green('몬스터를 물리쳤습니다!')}`);
return true; // 전투 승리
}
// Player가 어떤 행동을 하면 Monster는 공격을 한다
const monsterDamage = monster.attack(player);
logs.push(
`${chalk.red(`몬스터가 플레이어에게 ${monsterDamage}의 데미지를 입혔습니다.`)}`,
);
if (player.currentHp === 0) {
logs.push(`${chalk.red('플레이어가 쓰러졌습니다. 게임 오버!')}`);
return false; // 전투 패배
}
- currentHp로 현재체력을 설정하고 수치에 따라 전투 승리, 전투 패배를 선언
- logs.push는 행동이 작동하는 확인하는 Log Sheet