/**
* 备忘录
* @author 熊诗言
*
*/
public class Memento {
private int blood;
private int sword;
public Memento(int blood, int sword) {
this.blood = blood;
this.sword = sword;
}
public int getBlood() {
return blood;
}
public int getSword() {
return sword;
}
}
/**
* 备忘录发起者
* @author 熊诗言
*
*/
public class Hero {
private int blood;
private int sword;
private final Random random = new Random();
public Hero() {
this.blood = 100;
this.sword = 100;
}
public Memento createMemen() {
System.out.println("创建备忘录");
return new Memento(blood,sword);
}
public void restoreFromMemento(Memento memento){
System.out.println("从备忘录恢复");
if(memento != null){
this.blood = memento.getBlood();
this.sword = memento.getSword();
}
}
@Override
public String toString() {
return "当前血液值:"+blood+"----战斗值:"+sword;
}
public int koBoss(){
//<=0的时候挑战失败,假设胜利的概率为2%
if(this.blood<=0 || this.sword<=0){
System.out.println(this.toString());
System.out.println("遗憾,挑战失败");
return -1;
}else {
double win = Math.random();
if(win<=0.02){
System.out.println(this.toString());
System.out.println("恭喜,挑战成功");
return 1;
}else {
System.out.println(this.toString());
System.out.println("起来,继续攻击");
int blood_sub = random.nextInt(10);
int sword_sub = random.nextInt(10);
this.blood -= blood_sub;
this.sword -= sword_sub;
return 0;
}
}
}
}
/**
* 备忘录管理者
* @author 熊诗言
*
*/
public class Caretaker {
/**
* 如果需要保存很多历史,就需要一个List来保存
*/
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
测试
public class Client {
public static void main(String[] args) {
Hero hero = new Hero();
Caretaker caretaker = new Caretaker();
caretaker.setMemento(hero.createMemen());//先保存起来
int cnt =1;
int ko = -1;//0表示胜利
while (ko!=1 && cnt<=3) {
System.out.println("=================第 " + cnt + "次挑战");
ko = hero.koBoss();
while (true) {
if(ko==-1){
hero.restoreFromMemento(caretaker.getMemento());
cnt ++;
break;
}else if(ko == 0){
ko = hero.koBoss();
}else {
break;
}
}
}
}
}