复习java过程中,看到的一个很有意思的小程序
主程序:
public class GameTest {
public static void main(String[] args) {
Role r1=new Role("熊大",100,'男');
Role r2=new Role("熊二",100,'男');
r1.showRoleInfo();
r2.showRoleInfo();
while(true){
r1.attack(r2);
if(r2.getBlood()==0){
System.out.println(r1.getName()+"杀死了"+r2.getName());
break;
}
r2.attack(r1);
if(r1.getBlood()==0){
System.out.println(r2.getName()+"杀死了"+r1.getName());
break;
}
}
}
}
功能代码:
import java.util.Random;
public class Role {
private String name;
private int blood;
private char gender;
private String face;
String[] boyface={"器宇轩昂","风流倜傥","一表人才"};
String[] girlface={"沉鱼落雁","闭月羞花","祸国殃民"};
String[] attacks_desc={
"%s使出一招【黑虎掏心】,向%s心口攻去。",
"%s使出【九阴白骨掌】,掌上凝聚寒气,向%s拍出一掌。",
"%s大喝一声,使出【手里剑】,向%s发出一道暗器。"
};
String[] injureds_desc={
"%s躲闪不急,遭受重创。",
"结果%s灵巧躲避,轻轻闪过。",
"%s被轻轻刮伤,些许疼痛。",
"结果给%s造成一处擦伤。"
};
public Role(){
}
public Role(String name, int blood,char gender) {
this.name = name;
this.blood = blood;
this.gender=gender;
setFace(gender);
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getFace() {
return face;
}
public void setFace(char gender) {
Random r=new Random();
if(gender=='男'){
int index=r.nextInt(boyface.length);
this.face =boyface[index];
} else if (gender=='女') {
int index=r.nextInt(girlface.length);
this.face =girlface[index];
}else {
this.face="慈悲";
}
}
public String getName(){return name;}
public void setName(){this.name=name;}
public int getBlood(){return blood;}
public void setBlood(int blood) {this.blood = blood;}
public void attack(Role role){
Random m=new Random();
int index=m.nextInt(attacks_desc.length);
String kong=attacks_desc[index];
System.out.printf(kong,this.getName(),role.getName());
System.out.println();
int hurt=m.nextInt(20)+1;
int remainBlood= role.getBlood()-hurt;
remainBlood=remainBlood <0 ? 0:remainBlood;
role.setBlood(remainBlood);
if(hurt>15){
System.out.printf(injureds_desc[0],role.getName());
}else if (hurt>10&& hurt<=15){
System.out.printf(injureds_desc[2],role.getName());
} else if (hurt>5&&hurt<=10) {
System.out.printf(injureds_desc[3],role.getName());
} else{
System.out.printf(injureds_desc[1],role.getName());
}
System.out.println();
// System.out.println(this.getName()+"打了"+role.getName()+"一次,"+"造成了"+hurt+"点伤害,"+role.getName()+"还剩"+
// remainBlood+"点生命");
}
public void showRoleInfo(){
System.out.println("姓名为"+getName());
System.out.println("血量为"+getBlood());
System.out.println("性别为"+getGender());
System.out.println("长相为"+getFace());
}
}