第七次实验课代码

添加C04~C07
This commit is contained in:
2025-10-29 00:52:52 +08:00
parent 1986bbbe3e
commit 1c869f816f
24 changed files with 761 additions and 3 deletions

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,68 @@
public class Hero {
String name;//名称
char sex;//性别
int cost;//费用
int health;//生命值
int magic;//魔法值
int attack;//攻击力
int level;//等级(1-3) 1
int physicalResist;//物理抗性
int magicResist;//魔法抗性
//升级行为方法
public void levelUp(){
if (level < 3) {
this.level++;
this.health = (int) (this.health * 1.5);
this.attack = (int) (this.attack * 1.5);
System.out.format("%s升级到%d级\n", this.name, this.level);
}
}
//攻击行为方法
public void attack(Hero target){
if(this.health>0) {
int damage = calculateDamage(attack, target.physicalResist);
System.out.format("%s攻击了%s造成了%d点伤害\n", name, target.name, attack);
//必须为有效伤害
if (damage > 0)
target.takeDamage(damage);
else
System.out.println("攻击失败");
}
else
System.out.println(name+"已死亡,攻击失败");
}
//受到伤害行为方法
public void takeDamage(int damage){
health -= damage;
health=Math.max(health,0);
if(health>0)
System.out.format("%s受到了%d点伤害剩余生命值%d\n",name,damage,health);
else
System.out.format("%s受到了%d点伤害剩余生命值为0已被击败\n",name,damage);
}
private int calculateDamage(int damage,int resist){
return (int)(damage*1.0/(1+resist*1.0/100));
}
//无参构造器
public Hero() {
this.level=1;
}
//有参构造器
public Hero(String name, char sex, int cost, int health, int magic, int attack, int physicalResist, int magicResist) {
this();//在有参构造器中调用无参构造器
this.name = name;
this.sex = sex;
this.cost = cost;
this.health = health;
this.magic = magic;
this.attack = attack;
this.physicalResist = physicalResist;
this.magicResist = magicResist;
}
}

View File

@@ -0,0 +1,38 @@
public class Test {
public static void main(String[] args) {
//1.无参构造器,逐一赋值
Hero almin = new Hero();
almin.name="almin";
almin.sex='m';
almin.cost=1;
almin.health=1000;
almin.magic=100;
almin.attack=60;
almin.physicalResist=50;
almin.magicResist=50;
System.out.println(almin.name);
System.out.println(almin.health);
System.out.println(almin.level);
//2.有参构造器
Hero alen = new Hero("alen",'m',1,600,100,60,100,50);
System.out.println(alen.name);
System.out.println(alen.health);
System.out.println(alen.level);
//3.攻击
//almin.attack(alen);
System.out.println("游戏开始");
alen.levelUp();
int round = 0;
while(almin.health>0 && alen.health>0){
round++;
System.out.println(""+round+"回合");
almin.attack(alen);
alen.attack(almin);
System.out.println("=====================");
}
System.out.format("%s获胜%s失败",almin.health==0?alen.name:almin.name,
almin.health==0?almin.name:alen.name);
}
}