본문 바로가기

개발자노트

클래스) 상속..오버라이딩, toString 응용예제(포켓몬)

package class05;

import java.util.Random;

class Pokemon {
	String name;
	int level;
	int exp;

	@Override
	public String toString() {
		String msg = this.name + " ";
		msg += "Lv." + this.level + " ";
		msg += "[" + this.exp + "/100]";
		return msg;

	}

	void action() {
		System.out.println(this.name + "이(가) ㅁㅁ공격!");
		if (this.check()) {
			this.success();
		} else {
			this.fail();
		}
	}

	boolean check() {
		Random rand = new Random();
		int num = rand.nextInt(5); // 성공 80% 실패 20%
		if (num == 0) {
			return false;
		}
		return true;
	}

	void success() {
		Random rand = new Random();
		int exp = rand.nextInt(201) + 10; // 10~210
		this.exp += exp;
		while (this.exp >= 100) {
			this.exp -= 100;
			this.level++;
			System.out.println(this.name + ", 레벨업!");
		}
		System.out.println(this.name + " 공격성공! 획득경험치: " + exp);
	}

	void fail() {
		System.out.println(this.name + " 공격실패...");
		if (this.level == 1) {
			System.out.println("레벨은 1미만이 불가능합니다.");
			return;
		}
		this.level--;
	}

	Pokemon(String name) {
		this.name = name;
		Random rand = new Random();
		this.level = rand.nextInt(5) + 5;
		this.exp = 0;
	}

}

class Pikachu extends Pokemon {
	@Override
	void action() {
		System.out.println(this.name + "이(가) 백만볼트공격!");
		if (this.check()) {
			this.success();
		} else {
			this.fail();
		}
	}

	Pikachu() {
		super("피카츄");
	}
}

class Firi extends Pokemon {

	@Override
	void action() { // 오버라이딩
		System.out.println(this.name + "이(가) 불꽃공격!");
		if (this.check()) {
			this.success();
		} else {
			this.fail();
		}
	}

	Firi() {
		super("파이리");

	}
}

public class Test02 {
	@Override
	public String toString() {
		return "Test02 []";
	}

	public static void main(String[] args) {
		Pikachu p1 = new Pikachu();
		p1.action();
		Firi f1 = new Firi();

		System.out.println(p1);
		System.out.println(f1);
	}
}