/* * 玩家类 * 属性:名字,类型,血量,防御,攻击 * 行为:自我介绍,pk*/ public class Player { //封装:将属性设为private,提供公共的get和sat方法间接访问,提升安全性 private String name;//玩家名称 private String type;//玩家类型:战士,法师 private int life;//生命 private int defense;//防御 private int attack;//攻击力 /* 自我介绍*/ public void say(){ System.out.println("我叫"+name+",是一个"+type+",生命值高达"+life+",防御"+defense+",攻击"+attack); } /* pk的方法,和另一个玩家pk*/ public void pk(Player p){//对手 //定义一个标记,0代表我方进攻,1代表敌方进攻 int flag = 0;//默认我方进攻 //回合制PK,直到一方死亡 while (true){ //每次都显示剩余的生命值 this.say(); p.say(); if(flag==0) { //我放进攻:我放进攻-敌方防御力 int harm = (this.attack - p.defense);//得到伤害 //暴击:伤害翻倍 int sj= (int)Math.round(Math.random()*(2-1)+1); if(sj==2){ System.out.println(p.name+"暴击掉血"+harm*2); }else { System.out.println(p.name+"掉血"+harm); } p.setLife(p.life-harm*sj);//敌方掉血 flag = 1;//改变进攻方 }else { //敌方进攻: int harm = p.attack - this.defense; int sj= (int)Math.round(Math.random()*(10-1)+1); if (sj == 3 || sj==9) {//如果随机的是3或9表示暴击 System.out.println(p.name+"暴击掉血"+harm*2); this.setLife(this.life-harm*2);//我方掉血 }else{ System.out.println(this.name+"掉血" + harm); this.setLife(this.life-harm);//我方掉血 } flag = 0;//改变进攻方 } //判别血量 if(this.life<=0){ System.out.println(this.name+"被ko了"); this.explosiveEquipment();//物品掉落的方法 break;//有人倒下,停止战斗 } if(p.life<=0){ System.out.println(p.name+"被ko了"); this.explosiveEquipment();//物品掉落的方法 break;//有人倒下,停止战斗 } //线程休眠 try{ Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } } //爆装备 public void explosiveEquipment(){ //装备仓库 String[]arr={"屠龙宝刀","方天画戟","五雷轰顶技能书","灭世套装","大还丹","10W金币"}; //随机数数组元素的下标 0- arr.length-1 int sj= (int)Math.round(Math.random()*((arr.length-1)-0)+0); System.out.println("暴了["+arr[sj]+"]!!!"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getLife() { return life; } public void setLife(int life) { this.life = life; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } public int getAttack() { return attack; } public void setAttack(int attack) { this.attack = attack; } }
public class PlayerTest { public static void main(String[] args) { //创建玩家 Player p1=new Player(); p1.setName("龙傲天"); p1.setType("战士"); p1.setLife(100); p1.setDefense(20); p1.setAttack(30); Player p2=new Player(); p2.setName("赵日天"); p2.setType("法师"); p2.setLife(60); p2.setDefense(15); p2.setAttack(55); //pk p1.pk(p2); } }