题目
角色可向怪物实施攻击,一次攻击后,怪物会损失部分生命值,当生命值损失完之后,怪物死亡
需求
角色可装备不同的武器,目前有木剑、铁剑、魔剑三种
木剑攻击,生命值-20
铁剑攻击,生命值-50
魔剑攻击,生命值-100
代码
攻击接口
package fightMonsters;
interface Attack {
void lossBlood(Monster m);
int getHu();
}
木剑
package fightMonsters;
public class WoodenSword implements Attack{
Monster m = new Monster();
WoodenSword(){}
WoodenSword(Monster m){
this.m = m;
}
int hu = 20;
public int getHu() {
return hu;
}
public void lossBlood(Monster m){
m.health -= hu;
}
}
铁剑
package fightMonsters;
public class LronSword implements Attack{
Monster m = new Monster();
int hu = 50;
LronSword(){}
LronSword(Monster m){
this.m = m;
}
public int getHu() {
return hu;
}
public void lossBlood(Monster m){
m.health -= hu;
}
}
魔剑
package fightMonsters;
public class MagicSword implements Attack{
Monster m = new Monster();
int hu = 100;
MagicSword(){}
MagicSword(Monster m){
this.m = m;
}
public int getHu() {
return hu;
}
public void lossBlood(Monster m){
m.health -= hu;
}
}
怪兽
package fightMonsters;
public class Monster {
public int health = 0;
public Monster(){
}
public Monster(int health){
this.health = health;
}
}
角色(主类)
package fightMonsters;
public class Main {
public static void main(String[] args){
Monster monster = new Monster(500);
int t = 0;
Attack a[] = new Attack[3];
a[0] = new WoodenSword();
a[1] = new LronSword();
a[2] = new MagicSword();
while(monster.health > 0){
a[t].lossBlood(monster);
System.out.println("怪物被攻击,血量减 " + a[t].getHu());
if(monster.health > 0)
System.out.println("怪物剩余血量 " + monster.health);
else
System.out.println("怪物剩余血量为0");
t = (++t) % 3;
}
System.out.println("怪物已死亡, 游戏结束!!!");
}
}