package cn.hp.demo03; /* * 玩家类 * 属性:名字,类型,血量,防御,攻击 * 行为:自我介绍,PK * */ public class Player { //封装:将属性设为private,提供公共的get和set方法间接访问 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 * @param * */ 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(this.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(2000); } 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; } }
package cn.hp.demo03; public class PlayerTest { public static void main(String[] args) { //创建玩家对象 Player player1 = new Player(); player1.setName("焦文倩"); player1.setType("美女"); player1.setLife(100); player1.setDefense(20); player1.setAttack(30); Player player2 = new Player(); player2.setName("安倍晋三"); player2.setType("狗"); player2.setLife(60); player2.setDefense(10); player2.setAttack(10); //开始PK player1.pk(player2); } }