題目要求:
隨機實現“泰坦”與“宙斯”之間的模擬交戰。說明:本題以希臘神話中宙斯和泰坦間的交戰爲背景。
(1)分別建立宙斯和泰坦類,兩個類都有屬性“血量”, 設宙斯初始血量爲1000,設泰坦初始血量爲700。
(2)都有交戰的方法:泰坦交戰方法的參數是宙斯,隨機生成0~100間的攻擊值,受到攻擊的宙斯的血量要相應扣除,
然後輸出“泰坦攻擊宙斯,宙斯扣除血量”+攻擊值+“剩餘血量”+宙斯的血量。
(3)宙斯交戰的方法和泰坦一樣,只是參數爲泰坦,攻擊值在0~70之間。
(4)編寫測試類,並在該類中編寫雙方交戰方法,該方法有兩個參數:宙斯和泰坦。
該方法要實現雙方要持續交戰,直到一方血量小於或等於0。首先由宙斯攻擊泰坦,隨後泰坦攻擊宙斯。
攻擊後,任意一方血量小於0或等於0,均輸出“A死亡,B獲勝”(A爲血量小於或等於0的一方,B爲獲勝方)。退出模擬交戰。
讀完這個題目,不由自主的想起了洛克王國和賽爾號
咳咳,言歸正傳,學習要緊
不要看題目很長,但是一步一步的拆分,你會發現這個題很簡單
也不要看下面的代碼長,因爲生成了get、set方法,顯着代碼長,其實刪去就沒什麼東西了
public class Text_3 {
public static void main(String[] args) {
ZhouShi z = new ZhouShi("宙斯") ;
TaiTan t = new TaiTan("泰坦") ;
int i = 1 ;
double b1 = z.fight("泰坦", i) ;
double b2 = t.fight("宙斯", i) ;
while(b1 > 0 && b2 > 0 ) {
i++ ;
b1 = z.fight("泰坦", i) ;
b2 = t.fight("宙斯", i) ;
}
if(b1>0)
System.out.println(t.getName()+"死亡,"+z.getName()+"獲勝");
else
System.out.println(z.getName()+"死亡,"+t.getName()+"獲勝");
}
}
class ZhouShi{
private static double blood = 1000 ;
private String name ;
public ZhouShi(String name) {
super();
this.name = name;
}
public double fight (String name,int i) {
System.out.println("第"+i+"回合:"+name+"攻擊"+this.name+" : " );
double hurt = Math.random()*101 ;
blood -= hurt ;
if(blood>=0)
System.out.println(this.name+"受到了 "+hurt+" 點傷害"+"\t剩餘血量:"+blood);
else
System.out.println(this.name+"受到了 "+hurt+" 點傷害"+"\t剩餘血量:"+0);
return blood ;
}
public static double getBlood() {
return blood;
}
public static void setBlood(double blood) {
ZhouShi.blood = blood;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class TaiTan{
private static double blood = 700 ;
private String name ;
public TaiTan(String name) {
super();
this.name = name;
}
public double fight (String name,int i) {
System.out.println("第"+i+"回合:"+name+"攻擊"+this.name+" : " );
double hurt = Math.random()*71 ;
blood -= hurt ;
if(blood>=0)
System.out.println(this.name+"受到了 "+hurt+" 點傷害"+"\t剩餘血量:"+blood);
else
System.out.println(this.name+"受到了 "+hurt+" 點傷害"+"\t剩餘血量:"+0);
return blood ;
}
public static double getBlood() {
return blood;
}
public static void setBlood(double blood) {
TaiTan.blood = blood;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
一次就掉那麼一點血,打了個幾乎20回合,玩起遊戲來,玩家早就跑光了
所以啊,可以將上面的隨機數改大一點,這樣回合數就會少了,看起來也方便