package com.csdn.study.test;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class FightGame {
//鲁班血量
private static AtomicInteger luBanBlood = new AtomicInteger();
//鲁班攻击力
private static int luBanHurt;
//鲁班闪躲率
private static double luBanDodge;
//怪物血量
private static AtomicInteger monsterBlood = new AtomicInteger();
//怪物攻击力
private static int monsterHurt;
//怪物血条
private static AtomicIntegerArray monsterBloodArray;
//怪物存活数量
private static AtomicInteger monsterLive = new AtomicInteger();
//怪物闪躲率
private static double monsterDodge;
private static Random random = new Random();
//攻击怪物
static class monster implements Callable<Boolean> {
@Override
public Boolean call() {
if (monsterLive.get() <= 0) {
System.out.println("当前小怪物全死啦。。。");
return false;
}
double r = random.nextDouble();
if (r <= monsterDodge) {
System.out.println("小怪物闪躲啦,当前小怪物血量分别为:" + monsterBloodArray.get(0) + "," + monsterBloodArray.get(1)
+ "," + monsterBloodArray.get(2) + "," + monsterBloodArray.get(3) + "," + monsterBloodArray.get(4));
return true;
}
//选择攻击对象
int i = -1;
int count = 10001;
do {
i = random.nextInt(5);
count--;
} while (monsterBloodArray.get(i) <= 0 && count >= 0);
monsterBloodArray.set(i, monsterBloodArray.get(i) - luBanHurt);
if (monsterBloodArray.get(i) <= 0) {
monsterLive.decrementAndGet();
}
System.out.println("当轮攻击小怪物" + i +"结束,当前小怪物血量分别为:" + monsterBloodArray.get(0) + "," + monsterBloodArray.get(1)
+ "," + monsterBloodArray.get(2) + "," + monsterBloodArray.get(3) + "," + monsterBloodArray.get(4) + ",存活数为:"+monsterLive);
return true;
}
}
//攻击鲁班
static class LuBan implements Callable<Boolean> {
@Override
public Boolean call() {
double r = random.nextDouble();
if (r <= luBanDodge) {
System.out.println("鲁班闪躲啦,当前鲁班血量:" + luBanBlood.get());
return true;
}
if (luBanBlood.get() <= 0) {
System.out.println("鲁班挂了。。。。游戏结束。。。。");
return false;
} else {
luBanBlood.set(luBanBlood.get() - monsterHurt);
System.out.println("攻击鲁班成功,当前鲁班血量:" + luBanBlood.get());
if (luBanBlood.get() <= 0) {
System.out.println("鲁班挂了。。。。游戏结束。。。。");
return false;
}
}
return true;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
luBanBlood.set(2650);
monsterBlood.set(1350);
monsterLive.set(5);
luBanHurt = 20;
monsterHurt = 10;
luBanDodge = 0.5;
monsterDodge = 0.3;
monsterBloodArray = new AtomicIntegerArray(monsterLive.get());
monsterBloodArray.set(0, 1350);
monsterBloodArray.set(1, 1350);
monsterBloodArray.set(2, 800);
monsterBloodArray.set(3, 3500);
monsterBloodArray.set(4, 600);
ExecutorService exec = Executors.newCachedThreadPool();
LuBan luBan = new LuBan();
monster monster = new monster();
Future<Boolean> luBanSubmit = null;
Future<Boolean> monsterSubmit = null;
//循环攻击,直到一方阵亡为止
do {
luBanSubmit = exec.submit(luBan);
monsterSubmit = exec.submit(monster);
}while (luBanSubmit.get() && monsterSubmit.get());
}
}