package springroad.demo.chap5.aspectj;
public class Soldier {
private String name;
private int health=100;
private int damage=10;
private int x=10;
private int y=10;
public boolean attack(Soldier target){
boolean ret=false;
if(!target.dodge())
{
target.setHealth(target.getHealth()-this.damage);
ret=true;
}
move();
treat();
return ret;
}
public void move()
{
this.x+=getRandom(5);
this.y+=getRandom(5);
}
//躲避x及y随机变动,成功率为50%
public boolean dodge()
{
return getRandom(10)%2==0;
}
//治疗,具有一定成功的机会,可以提高生命值0-20点
public void treat()
{
if(canTreat())
this.health+=getRandom(20);
}
public boolean canTreat()
{
return getRandom(10)/2==0;
}
private int getRandom(int seed)
{
return RandomUtil.getRandomValue(seed);
}
//getter及setter方法
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
}
public class MainTest {
public static void main(String[] args) {
Soldier p1=new Soldier();
p1.setName("角色1");
Soldier p2=new Soldier();
p2.setName("角色2");
int i=0;
while(p1.getHealth()>0 && p2.getHealth()>0)
{
p2.attack(p1);
p1.attack(p2);
i+=2;
}
System.out.println("战斗次数:"+i);
if(p1.getHealth()>0)System.out.println(p1.getName()+"战胜!");
else System.out.println(p2.getName()+"战胜!");
}
}
private static java.util.Random random=new java.util.Random();
public static int getRandomValue(int seed)
{
return random.nextInt(seed);
}
}
public aspect RecordGame {
private static java.text.SimpleDateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd H:m:s");
pointcut doRecord():execution(boolean Soldier.attack(Soldier));
pointcut supperRole(Soldier s): target(s)&&execution(boolean Soldier.canTreat());
after() returning(boolean value) :doRecord()
{
Soldier s=(Soldier)thisJoinPoint.getTarget();
Soldier t=(Soldier)thisJoinPoint.getArgs()[0];
System.out.println(df.format(new java.util.Date())+":"+s.getName()+" 向 "+t.getName()+" 发动了一次攻击!--结果:"+(value?"成功":"失败"));
System.out.println(s.getName()+"生命值:"+s.getHealth()+";"+t.getName()+"生命值:"+t.getHealth());
}
after(Soldier s)returning(boolean value):target(s)&&call(boolean Soldier.canTreat())
{
if(value)System.out.println(s.getName()+"得到治疗!");
}
boolean around(Soldier s): supperRole(s)
{
if("super".equals(s.getName())) return true;
else return proceed(s);
}
}
