클래스 객체 생성자 이해하기
캐릭터의 공통 기능을 함수로 모아놓음 (붕어빵 틀처럼)
package Game;
public class characters {
String name;
int hp;
int atk;
public characters (String name,int hp, int atk) {
this.name = name;
this.hp = hp;
this.atk = atk;
}
public void attacks (characters enemy) {
System.out.println(this.name + "attacks!");
enemy.hp -= this.atk;
System.out.println(enemy.name + " HP : "+enemy.hp);
System.out.println("---------------------------");
}
public boolean isLives() {
if( hp <= 0) {
return false;
}else {
return true;
}
}
}
캐릭터 고유 특성을 살리기 위해 분리 구성.
package Game;
public class dalplayer extends characters {
public dalplayer(String name,int hp, int atk) {
super(name,hp,atk);
}
int hp2 = (int)(hp*0.3);
@Override
public void attacks (characters enemy) {
if ( hp <= hp2) {
System.out.println("달이가 미쳐 날뛴다잉");
atk = (int)(atk*1.05);
System.out.println(this.name+"atk : "+this.atk);
}
super.attacks(enemy);
}
}
package Game;
public class soplayer extends characters {
public soplayer(String name,int hp, int atk) {
super(name,hp,atk);
}
public void Heals() {
System.out.println("소애가 힐한다잉");
hp += 50;
}
}
위에 선언한 클래스들을 이용한 메인 클래스
package Game;
public class main2 {
public static void main(String[] args) {
int cnt = 0;
dalplayer player = new dalplayer("dal",7000,66);
soplayer player2 = new soplayer("so",6000,77);
while(player.isLives() && player2.isLives()) {
player2.attacks(player);
cnt++;
if(cnt==3) {
player2.Heals();
cnt=0;
}
if(!player.isLives()) break;
player.attacks(player2);;
if(!player2.isLives())break;
}
if(player.isLives()) {
System.out.println("달이 이겼다잉.");
}else {
System.out.println("소가 이겼다잉.");
}
}
}
characters.java
dalplayer.java
soplyaer.java
main2.java