package c07;
/**
* 1、定义了一个角色接口Events,完成定时任务执行功能
* 2、定义了一个类EatEvents,实现了具体的kill(send),killby(receive)功能
* 3、定义了一个EatEvents数组,轮循kill毒牛怪NPC
*/
public class EventTest {
public static void main(String[] args) {
//EatEvents(name,timetokill,wanttokill,selflive)
Events NPC=new EatEvents("毒牛怪",5,null,5);
Events[] e=new EatEvents[]{
new EatEvents("杀牛者",5,NPC,15),
new EatEvents("斗牛者",10,NPC,5)
};
/*
while(true){
for(int i=0;i<e.length;i++){
e[i].run();
}
}
*/
new EventThread(e[0],"杀牛者");
new EventThread(e[1],"斗牛者");
}
}
class EventThread implements Runnable{
private Events e;
private String name;
public EventThread(Events e,String name) {
this.e=e;
this.name=name;
new Thread(this,name).start();
}
public void run() {
// TODO Auto-generated method stub
if(e!=null){
while(true){
e.run();
}
}
}
}
interface Events{
boolean ready();
void reset();
void addTime();
void run();
void idle();
void send(Events sender,Events obj);
void receive(Events sender);
int getIdletime();
String description();
String getName();
}
class EatEvents implements Events{
String desc="GamePlay";
String name;
private int eventTime=1;
private int currTime=1;
private int idleTime=0;
private int oldLife;
private int life;
Events e;
public String getName() {
return this.name;
}
public void addTime() {
this.currTime++;
}
synchronized public void receive(Events arg0) {
System.out.println(this.name+":kill by "+arg0.getName());
this.life--;
if(this.life>0){
System.out.println(this.name+":I have life "+this.life+", I can kill "+arg0.getName());
send(this,arg0);
}
else{
System.out.println(this.name+":I killed by "+arg0.getName()+",he is a really hero!But I will relive");
this.life=this.oldLife;
}
}
public void send(Events arg0, Events arg1) {
if(arg1!=null){
System.out.println(this.name+":I want to kill "+arg1.getName());
arg1.receive(arg0);
}
}
public int getIdletime() {
return this.idleTime;
}
public void idle() {
this.idleTime++;
System.out.println(this.description()+":relax("+this.idleTime+")...");
}
public void reset() {
this.currTime=1;
this.idleTime=0;
}
EatEvents(String name,int eventTime,Events e,int life){
this.name=name;
if(eventTime>=1){
this.eventTime=eventTime;
}
this.currTime=0;
this.idleTime=0;
this.e=e;
this.life=life;
this.oldLife=life;
}
public boolean ready() {
return this.currTime>=this.eventTime;
}
public String description() {
return this.desc+":"+this.name;
}
public void run() {
this.addTime();
if(this.ready()){
System.out.println(this.description()+":running...");
System.out.println(this.name+":start war!");
send(this,e);
this.reset();
}
else{
this.idle();
}
}
}