package cn.hp.demo3;
/*
*玩家类
*属性:名字,类型,血量,防御,攻击
* 行为:自我介绍,pk
*
*/
public class Player {
//封装,将属性设置为private,
private String name;
private String type;
private int life;
private int defense;
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;
}
private int attack;
public void say(){
System.out.println("我叫"+name+"是一个"+type+",我的生命值高达"+life+",防御"+defense+",攻击"+attack);
}
public void pk(Player p){
//回合制pk,直到一方死亡
while (true){
//每次都显示剩余的生命值
this.say();
p.say();
//定义一个标记,0表示我方进攻,1表示敌方进攻
int flag = 0;//默认我方进攻
if (flag==0){
//我方进攻:敌方生命值-(我方攻击力-敌方防御力)
int harm = p.life-(this.attack-p.defense);
p.setLife(p.life-harm);
System.out.println(p.name+"掉血" + harm);
flag = 1;//改变进攻方
}else{
//敌方进攻:我方生命值-(敌方攻击力-我方防御力)
int harm = this.life-(p.attack-this.defense);//受到伤害
this.setLife(this.life-harm);
System.out.println(p.name+"掉血" + harm);
flag = 0;//改变进攻方
}
}
}
}
package cn.hp.demo3;
public class PlayerTest {
public static void main(String[] args) {
//创建玩家对象
Player p1 = new Player();
p1.setName("安琪拉");
p1.setType("法师");
p1.setLife(2222);
p1.setDefense(12000);
p1.setAttack(20000);
Player p2 = new Player();
p2.setName("兰陵王");
p2.setType("刺客");
p2.setLife(8888);
p2.setDefense(82000);
p2.setAttack(80000);
}
}