战斗小项目实例

这是模拟战斗的小项目,两个人相互攻击,直到其中的一个人死亡。

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;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值