본문 바로가기
Back-End/Java

[Back-End][Java] 31. 객체 지향 프로그래밍 연습하기 (스타크래프트)

by nanee_ 2021. 9. 14.
728x90
반응형
SMALL

 

 

 

Unit.java

public abstract class Unit { // 추상 부모 클래스
  
  // 멤버변수
  protected String name;
  protected int power;
  protected int hp;

  // getter
  public String getName() {
  	return name;
  }

  public int getHp() {
  	return hp;
  }

  public int getPower() {
  	return power;
  }
  
  // 일반 메서드
  public void showInfo() {
    System.out.println("======정보창("+this.name+")======");
    System.out.println("이름 : " + this.name);
    System.out.println("공격력 : " + this.power);
    System.out.println("체력 : " + this.hp);
    System.out.println("========================");
  }

  public void attack(Unit unit) {
  	System.out.println(this.name + " 이 " + unit.getName()+" 을 공격합니다.");
  	unit.beAttacked(this.power);
  }

  public void beAttacked(int power) {
    if(hp < 0) {
    	System.out.println(name + " 은 사망하였습니다.");
    }else {
    	hp -= power;			
    }
  }	
}

 

Dragon.java

public class Dragon extends Unit {
	
  // 생성자
  public Dragon(String name) {
    this.name = name;
    this.power = 5;
    this.hp = 100;
  }
}

 

DarkTempler.java

public class DarkTempler extends Unit {

  // 생성자
  public DarkTempler(String name) {
  	this.name = name;
  	this.power = 5;
  	this.hp = 100;
  }	
}

 

Zealot.java

public class Zealot extends Unit {
	
  // 생성자
  public Zealot(String name) {
    this.name = name;
    this.power = 10;
    this.hp = 100;
  }
}

 

Gate.java

public class GateWay{

  public static int zealotCount;
  public static int dragonCount;
  public static int darkTemplerCount;
  private int gateWayId;
  private String name;

  public GateWay(int id) {
  	this.gateWayId = id;
  	name = "게이트웨이";
  }

  public Unit createUnit(int target) {
    // 매개변수 1. 질럿
    // 매개변수 2. 드라군
    // 매개변수 3. 다크템플러
    if(target == 1) {
    	System.out.println("질럿을 생산합니다.");
    	zealotCount++;
    	return new Zealot("질럿"+zealotCount);			
    }else if(target == 2) {
    	System.out.println("드라곤을 생산합니다.");
    	dragonCount++;
    	return new Dragon("드라곤"+dragonCount);
    }else {
    	System.out.println("다크템플러를 생산합니다.");
    	darkTemplerCount++;
    	return new DarkTempler("다크템플러"+darkTemplerCount);
  }	
  }
	
}

 

MainTest.java

public class MainTest {
	
  public static void main(String[] args) {
    
    // GateWay 객체 생성
    GateWay gateWay1 = new GateWay(1);

    // Unit 타입으로 gateWay1을 사용해서 객체생성
    Unit zealot1 = gateWay1.createUnit(1);
    Unit dragon1 = gateWay1.createUnit(2);
    Unit darkTempler1 = gateWay1.createUnit(3);

    // 생성된 객체 수 확인
    System.out.println(gateWay1.zealotCount);
    System.out.println(gateWay1.darkTemplerCount);
    System.out.println(gateWay1.dragonCount);

    // attack 메서드 구현
    zealot1.attack(darkTempler1);
    zealot1.attack(darkTempler1);
    
    System.out.println("");
    
    // 공격받은 객체 정보출력 메서드
    darkTempler1.showInfo();
  }
}

 

 

 

 

 

 

728x90
반응형
LIST