这是模拟战斗的小项目,两个人相互攻击,直到其中的一个人死亡。
import com.bjsxt.util.MyUtil;
/**
-
需求:用面向对象的思想去演示一场战斗。
-
1:两个对象。只有一种类型 warrior
-
@author yhl
*/
public class TestOop {
public static void main(String[] args) {
Battle battle = new Battle();
battle.startBattle();
}
}
class Battle{
private Warrior ajls;
private Warrior hkt;
public Battle() {
initBattle();
}
private void initBattle(){
ajls = new Warrior(“阿基里斯”, 30);
hkt = new Warrior(“赫克托耳”, 30);
}
public void startBattle(){
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean result = hkt.attack(ajls);
if(result){
ajls.die();
break;
}
result = ajls.attack(hkt);
if(result){
hkt.die();
break;
}
}
endBattle();
}
private void endBattle(){
if(ajls.getHp() >0)
System.out.println(ajls.getName() + “~~~获得了胜利!”);
else
System.out.println(hkt.getName() + “~~~获得了胜利!”);
}
}
class Warrior{
public static final int MAX_HP = 1000;
private String name;
private int hp = MAX_HP;
private int damage;
public Warrior() {
}
public Warrior(String name, int damage) {
super();
this.name = name;
this.damage = damage;
}
/**
-
@param warrior 被攻击的对象
-
@return 如果对方被打死,返回 true,否则 false。
*/
public boolean attack(Warrior warrior){
//计算伤害
int curDamage = MyUtil.getRandomNumber(0, 10) + damage;
warrior.hp -= curDamage;
System.out.println("【"+name + “】攻击了【”+warrior.name+"】,造成了:【"+curDamage + “】点伤害!”);
if(warrior.hp <= 0){
return true;
}
return false;
}
public void die(){
System.out.println("【"+name+"】死了!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}