앞전에 배운 다형성과 객체지향을 이용하여 간단한 턴제게임을 만들어 볼 것이다.
1이 붙은 이유가 있는데..이는 계속해서 업그레이드를 할 것이다.
우선 Character라는 부모 클래스를 만들어 준다.
package com.practice;
public class Character {
protected String name;
protected int hp;
protected int fullHp;
protected int atk;
protected int def;
protected Weapon weapon;
void attack(Character character) {
if (weapon == null){
System.out.println(name + "의 맨손공격!");
System.out.println("enemy 에게 " + atk + "만큼의 데미지를 주었다.");
}else {
System.out.println(name + "의 공격!");
character.damaged(weapon.useWeapon(atk));
}
}
void damaged(int damage) {
int totalDamage = damage - def;
if(hp <= totalDamage){
System.out.println(name + "은(는) 쓰러졌다!");
return;
}
if (totalDamage <= 0) {
System.out.println(name + "은 공격을 받았으나, 데미지를 입지 않았다!");
} else {
hp -= damage - def;
System.out.println(name + "은(는) " + (damage-def) + "만큼의 데미지를 입었다!");
System.out.println("남은 채력 : " + hp + "/" + fullHp);
}
}
void equipWeapon(Weapon weapon){
this.weapon = weapon;
System.out.println(name + "은 " + weapon.getWeapon() + "을 장착했습니다.");
}
}
이름, 체력, 공격 방어, 무기와 같은 공통 필드를 갖고있고, 그게 맞는 공통 기능을 담당하고 있는 클래스이다.
package com.practice;
public class Warrior extends Character {
public Warrior(String name) {
super.name = name;
super.hp = 100;
super.atk = 10;
super.def = 5;
super.fullHp = hp;
}
@Override
void equipWeapon(Weapon weapon) {
super.equipWeapon(weapon);
}
}
package com.practice;
public class Ghoul extends Character{
public Ghoul() {
super.name = "구울";
super.hp = 50;
super.atk = 3;
super.def = 2;
super.fullHp = hp;
}
}
이제 그 Character를 구체화 시킨 클래스가 바로 이 자식 클래스들이다.
Warrier는 플레이어가 사용하는 캐릭터, Ghoul은 적대적 몬스터다.
package com.practice;
public class Weapon {
private String weapon;
private int weapon_atk;
public String getWeapon() {
return weapon;
}
public Weapon(String weapon, int weapon_atk) {
this.weapon = weapon;
this.weapon_atk = weapon_atk;
}
int useWeapon(int atk) {
return atk += weapon_atk;
}
}
무기의 정보와 기능을 담당하는 클래스이다. character 클래스와 집합관계를 가진다.
package com.practice;
public class MainGameTest {
public static void main(String[] args) {
Warrior warrior = new Warrior("전사");
Ghoul ghoul = new Ghoul();
Weapon weapon = new Weapon("검", 5);
warrior.equipWeapon(weapon);
warrior.attack(ghoul);
warrior.attack(ghoul);
warrior.attack(ghoul);
warrior.attack(ghoul);
}
}
아직 위의 기능도 완전하지 않아서 테스트로만 진행하고있다.