repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
librec
librec-master/librec/src/main/java/librec/ext/NMF.java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LibRec is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.ext; import librec.data.Configuration; import librec.data.DenseMatrix; import librec.data.DenseVector; import librec.data.MatrixEntry; import librec.data.SparseMatrix; import librec.data.SparseVector; import librec.intf.IterativeRecommender; import librec.util.Strings; /** * Daniel D. Lee and H. Sebastian Seung, <strong>Algorithms for Non-negative Matrix Factorization</strong>, NIPS 2001. * * @author guoguibing * */ @Configuration("factors, numIters") public class NMF extends IterativeRecommender { // V = W * H protected DenseMatrix W, H; protected SparseMatrix V; public NMF(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { super(trainMatrix, testMatrix, fold); // no need to update learning rate lRate = -1; } @Override protected void initModel() throws Exception { W = new DenseMatrix(numUsers, numFactors); H = new DenseMatrix(numFactors, numItems); W.init(0.01); H.init(0.01); V = trainMatrix; } @Override protected void buildModel() throws Exception { for (int iter = 1; iter <= numIters; iter++) { // update W by fixing H for (int u = 0; u < W.numRows(); u++) { SparseVector uv = V.row(u); if (uv.getCount() > 0) { SparseVector euv = new SparseVector(V.numColumns()); for (int j : uv.getIndex()) euv.set(j, predict(u, j)); for (int f = 0; f < W.numColumns(); f++) { DenseVector fv = H.row(f, false); double real = fv.inner(uv); double estm = fv.inner(euv) + 1e-9; W.set(u, f, W.get(u, f) * (real / estm)); } } } // update H by fixing W DenseMatrix trW = W.transpose(); for (int j = 0; j < H.numColumns(); j++) { SparseVector jv = V.column(j); if (jv.getCount() > 0) { SparseVector ejv = new SparseVector(V.numRows()); for (int u : jv.getIndex()) ejv.set(u, predict(u, j)); for (int f = 0; f < H.numRows(); f++) { DenseVector fv = trW.row(f, false); double real = fv.inner(jv); double estm = fv.inner(ejv) + 1e-9; H.set(f, j, H.get(f, j) * (real / estm)); } } } // compute errors loss = 0; for (MatrixEntry me : V) { int u = me.row(); int j = me.column(); double ruj = me.get(); if (ruj > 0) { double euj = predict(u, j) - ruj; loss += euj * euj; } } loss *= 0.5; if (isConverged(iter)) break; } } @Override public double predict(int u, int j) { return DenseMatrix.product(W, u, H, j); } @Override public String toString() { return Strings.toString(new Object[] { numFactors, numIters }); } }
3,307
23.145985
118
java
librec
librec-master/librec/src/main/java/librec/ext/PRankD.java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LibRec is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.ext; import java.util.HashMap; import java.util.Map; import librec.data.DenseVector; import librec.data.SparseMatrix; import librec.data.SparseVector; import librec.data.SymmMatrix; import librec.data.VectorEntry; import librec.ranking.RankSGD; import librec.util.Lists; import librec.util.Randoms; /** * Neil Hurley, <strong>Personalised ranking with diversity</strong>, RecSys 2013. * * <p> * Related Work: * <ul> * <li>Jahrer and Toscher, Collaborative Filtering Ensemble for Ranking, JMLR, 2012 (KDD Cup 2011 Track 2).</li> * </ul> * </p> * * @author guoguibing * */ public class PRankD extends RankSGD { // item importance private DenseVector s; // item correlations private SymmMatrix itemCorrs; // similarity filter private float alpha; public PRankD(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { super(trainMatrix, testMatrix, fold); isRankingPred = true; } @Override protected void initModel() throws Exception { super.initModel(); // compute item sampling probability Map<Integer, Double> itemProbsMap = new HashMap<>(); double maxUsers = 0; s = new DenseVector(numItems); for (int j = 0; j < numItems; j++) { int users = trainMatrix.columnSize(j); if (maxUsers < users) maxUsers = users; s.set(j, users); // sample items based on popularity double prob = (users + 0.0) / numRates; if (prob > 0) itemProbsMap.put(j, prob); } itemProbs = Lists.sortMap(itemProbsMap); // compute item relative importance for (int j = 0; j < numItems; j++) { s.set(j, s.get(j) / maxUsers); } alpha = algoOptions.getFloat("-alpha"); // compute item correlations by cosine similarity itemCorrs = buildCorrs(false); } /** * override this approach to transform item similarity */ protected double correlation(SparseVector iv, SparseVector jv) { double sim = correlation(iv, jv, "cos-binary"); if (Double.isNaN(sim)) sim = 0.0; // to obtain a greater spread of diversity values return Math.tanh(alpha * sim); } @Override protected void buildModel() throws Exception { for (int iter = 1; iter <= numIters; iter++) { loss = 0; // for each rated user-item (u,i) pair for (int u : trainMatrix.rows()) { SparseVector Ru = trainMatrix.row(u); for (VectorEntry ve : Ru) { // each rated item i int i = ve.index(); double rui = ve.get(); int j = -1; while (true) { // draw an item j with probability proportional to popularity double sum = 0, rand = Randoms.random(); for (Map.Entry<Integer, Double> en : itemProbs) { int k = en.getKey(); double prob = en.getValue(); sum += prob; if (sum >= rand) { j = k; break; } } // ensure that it is unrated by user u if (!Ru.contains(j)) break; } double ruj = 0; // compute predictions double pui = predict(u, i), puj = predict(u, j); double dij = Math.sqrt(1 - itemCorrs.get(i, j)); double sj = s.get(j); double e = sj * (pui - puj - dij * (rui - ruj)); loss += e * e; // update vectors double ye = lRate * e; for (int f = 0; f < numFactors; f++) { double puf = P.get(u, f); double qif = Q.get(i, f); double qjf = Q.get(j, f); P.add(u, f, -ye * (qif - qjf)); Q.add(i, f, -ye * puf); Q.add(j, f, ye * puf); } } } loss *= 0.5; if (isConverged(iter)) break; } } @Override public String toString() { return super.toString() + "," + alpha; } }
4,293
22.336957
112
java
librec
librec-master/librec/src/main/java/librec/ext/SlopeOne.java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LibRec is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.ext; import librec.data.DenseMatrix; import librec.data.SparseMatrix; import librec.data.SparseVector; import librec.intf.Recommender; /** * * Weighted Slope One: Lemire and Maclachlan, <strong>Slope One Predictors for Online Rating-Based Collaborative * Filtering</strong>, SDM 2005. * * @author guoguibing * */ public class SlopeOne extends Recommender { // matrices for item-item differences with number of occurrences/cardinary private DenseMatrix devMatrix, cardMatrix; public SlopeOne(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { super(trainMatrix, testMatrix, fold); } @Override protected void initModel() throws Exception { devMatrix = new DenseMatrix(numItems, numItems); cardMatrix = new DenseMatrix(numItems, numItems); } @Override protected void buildModel() throws Exception { // compute items' differences for (int u = 0; u < numUsers; u++) { SparseVector uv = trainMatrix.row(u); int[] items = uv.getIndex(); for (int i : items) { double rui = uv.get(i); for (int j : items) { if (i != j) { double ruj = uv.get(j); devMatrix.add(i, j, rui - ruj); cardMatrix.add(i, j, 1); } } } } // normalize differences for (int i = 0; i < numItems; i++) { for (int j = 0; j < numItems; j++) { double card = cardMatrix.get(i, j); if (card > 0) { double sum = devMatrix.get(i, j); devMatrix.set(i, j, sum / card); } } } } @Override public double predict(int u, int j) { SparseVector uv = trainMatrix.row(u, j); double preds = 0, cards = 0; for (int i : uv.getIndex()) { double card = cardMatrix.get(j, i); if (card > 0) { preds += (devMatrix.get(j, i) + uv.get(i)) * card; cards += card; } } return cards > 0 ? preds / cards : globalMean; } }
2,538
25.175258
112
java
librec
librec-master/librec/src/main/java/librec/main/Demo.java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LibRec is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.main; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import librec.util.FileIO; import librec.util.Logs; import librec.util.Strings; import librec.util.Systems; /** * A demo created for the UMAP'15 demo session, could be useful for other users. * * @author Guo Guibing * */ public class Demo { public static void main(String[] args) { try { new Demo().execute(args); } catch (Exception e) { e.printStackTrace(); } } public void execute(String[] args) throws Exception { // config logger String dirPath = FileIO.makeDirPath("demo"); Logs.config(dirPath + "log4j.xml", true); // set the folder path for configuration files String configDirPath = FileIO.makeDirPath(dirPath, "config"); // prepare candidate options List<String> candOptions = new ArrayList<>(); candOptions.add("General Usage:"); candOptions.add(" 0: the format of rating prediction results;"); candOptions.add(" 1: the format of item recommendation results;"); candOptions.add(" 2: run an algorithm by name [Input: 2 algoName];"); candOptions.add(" 3: help & about this demo;"); candOptions.add("-1: quit the demo!"); candOptions.add(""); candOptions.add("Part I: baselines"); candOptions.add("10: Global Average; 11: User Average; 12: Item Average;"); candOptions.add("13: Most Popularity; 14: User Cluster; 15: Item Cluster;"); candOptions.add("16: Association Rule; 17: Non-neg MF; 18: Slope One;"); candOptions.add(""); candOptions.add("Part II: rating prediction"); candOptions.add("20: UserKNN;\t 21: ItemKNN; \t 22: TrustSVD; "); candOptions.add("23: RegSVD; \t 24: BiasedMF;\t 25: SVD++; "); candOptions.add(""); candOptions.add("Part III: item recommendation"); candOptions.add("30: LDA; \t 31: BPR; \t 32: FISM; "); candOptions.add("33: WRMF; \t 34: SLIM; \t 35: RankALS. "); int option = 0; boolean flag = false; Scanner reader = new Scanner(System.in); String configFile = "librec.conf"; do { Logs.debug(Strings.toSection(candOptions)); System.out.print("Please choose your command id: "); option = reader.nextInt(); // print an empty line Logs.debug(); flag = false; // get algorithm-specific configuration file switch (option) { case 10: configFile = "GlobalAvg.conf"; break; case 11: configFile = "UserAvg.conf"; break; case 12: configFile = "ItemAvg.conf"; break; case 13: configFile = "MostPop.conf"; break; case 14: configFile = "UserCluster.conf"; break; case 15: configFile = "ItemCluster.conf"; break; case 16: configFile = "AR.conf"; break; case 17: configFile = "NMF.conf"; break; case 18: configFile = "SlopeOne.conf"; break; case 20: configFile = "UserKNN.conf"; break; case 21: configFile = "ItemKNN.conf"; break; case 22: configFile = "TrustSVD.conf"; break; case 23: configFile = "RegSVD.conf"; break; case 24: configFile = "BiasedMF.conf"; break; case 25: configFile = "SVD++.conf"; break; case 30: configFile = "LDA.conf"; break; case 31: configFile = "BPR.conf"; break; case 32: configFile = "FISM.conf"; break; case 33: configFile = "WRMF.conf"; break; case 34: configFile = "SLIM.conf"; break; case 35: configFile = "RankALS.conf"; break; case -1: flag = true; break; case 0: Logs.debug("Prediction results: MAE, RMSE, NMAE, rMAE, rRMSE, MPE, <configuration>, training time, test time\n"); Systems.pause(); continue; case 1: Logs.debug("Ranking results: Prec@5, Prec@10, Recall@5, Recall@10, AUC, MAP, NDCG, MRR, <configuration>, training time, test time\n"); Systems.pause(); continue; case 2: // System.out.print("Please input the method name: "); String algoName = reader.next().trim(); configFile = algoName + ".conf"; break; case 3: StringBuilder about = new StringBuilder(); about.append("About. This demo was created by Guo Guibing, the author of the LibRec library.\n") .append("It is based on LibRec-v1.3 (http://www.librec.net/). Although initially designed\n") .append("for a demo session at UMAP'15, it may be useful for those who want to take a \n") .append("quick trial of LibRec. Source code: https://github.com/guoguibing/librec.\n\n") .append("Usage. To run a predefined recommender, simply choose a recommender id.\n") .append("To run a customized recommender, give the input '2 algoName' (e.g., '2 RegSVD').\n") .append("For case 2, make sure you have a configuration file named by 'algoName.conf'\n"); Logs.debug(about.toString()); Systems.pause(); continue; default: Logs.error("Wrong input id!\n"); Systems.pause(); continue; } if (flag) break; // run algorithm LibRec librec = new LibRec(); librec.setConfigFiles(configDirPath + configFile); librec.execute(args); // await next command Logs.debug(); Systems.pause(); } while (option != -1); reader.close(); Logs.debug("Thanks for trying out LibRec! See you again!"); } }
5,936
27.406699
138
java
librec
librec-master/librec/src/main/java/librec/main/LibRec.java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LibRec is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.main; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.TimeUnit; import librec.baseline.ConstantGuess; import librec.baseline.GlobalAverage; import librec.baseline.ItemAverage; import librec.baseline.ItemCluster; import librec.baseline.MostPopular; import librec.baseline.RandomGuess; import librec.baseline.UserAverage; import librec.baseline.UserCluster; import librec.data.DataDAO; import librec.data.DataSplitter; import librec.data.MatrixEntry; import librec.data.SparseMatrix; import librec.ext.AR; import librec.ext.External; import librec.ext.Hybrid; import librec.ext.NMF; import librec.ext.PD; import librec.ext.PRankD; import librec.ext.SlopeOne; import librec.intf.GraphicRecommender; import librec.intf.IterativeRecommender; import librec.intf.Recommender; import librec.metric.AvgMetricCollection; import librec.metric.MetricCollection; import librec.ranking.BHfree; import librec.ranking.BPR; import librec.ranking.BUCM; import librec.ranking.CLiMF; import librec.ranking.FISMauc; import librec.ranking.FISMrmse; import librec.ranking.GBPR; import librec.ranking.ItemBigram; import librec.ranking.LDA; import librec.ranking.LRMF; import librec.ranking.RankALS; import librec.ranking.RankSGD; import librec.ranking.SBPR; import librec.ranking.SLIM; import librec.ranking.WBPR; import librec.ranking.WRMF; import librec.rating.BPMF; import librec.rating.BiasedMF; import librec.rating.CPTF; import librec.rating.GPLSA; import librec.rating.ItemKNN; import librec.rating.LDCC; import librec.rating.PMF; import librec.rating.RSTE; import librec.rating.RfRec; import librec.rating.SVDPlusPlus; import librec.rating.SoRec; import librec.rating.SoReg; import librec.rating.SocialMF; import librec.rating.TimeSVD; import librec.rating.TrustMF; import librec.rating.TrustSVD; import librec.rating.URP; import librec.rating.UserKNN; import librec.util.Dates; import librec.util.EMailer; import librec.util.FileConfiger; import librec.util.FileIO; import librec.util.LineConfiger; import librec.util.Logs; import librec.util.Randoms; import librec.util.Strings; import librec.util.Systems; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Table; /** * Main Class of the LibRec Library * * @author guoguibing * */ public class LibRec { // version: MAJOR version (significant changes), followed by MINOR version (small changes, bug fixes) protected static String version = "1.4"; // output directory path protected static String tempDirPath = "./Results/"; // configuration protected FileConfiger cf; protected List<String> configFiles; protected String algorithm; protected float binThold; protected int[] columns; protected TimeUnit timeUnit; // rate DAO object protected DataDAO rateDao; // line configer for rating data, LibRec outputs protected LineConfiger ratingOptions, outputOptions; // rating, timestamp matrix protected SparseMatrix rateMatrix, timeMatrix; /** * run the LibRec library */ protected void execute(String[] args) throws Exception { // process librec arguments cmdLine(args); // multiple runs at one time for (String config : configFiles) { // reset general settings preset(config); // prepare data readData(); // run a specific algorithm run(); } // collect results String filename = (configFiles.size() > 1 ? "multiAlgorithms" : algorithm) + "@" + Dates.now() + ".txt"; String results = tempDirPath + filename; FileIO.copyFile("results.txt", results); // send notification notifyMe(results); } /** * read input data */ protected void readData() throws Exception { // DAO object rateDao = new DataDAO(cf.getPath("dataset.ratings")); // data configuration ratingOptions = cf.getParamOptions("ratings.setup"); // data columns to use List<String> cols = ratingOptions.getOptions("-columns"); columns = new int[cols.size()]; for (int i = 0; i < cols.size(); i++) columns[i] = Integer.parseInt(cols.get(i)); // is first line: headline rateDao.setHeadline(ratingOptions.contains("-headline")); // rating threshold binThold = ratingOptions.getFloat("-threshold"); // time unit of ratings' timestamps timeUnit = TimeUnit.valueOf(ratingOptions.getString("--time-unit", "seconds").toUpperCase()); rateDao.setTimeUnit(timeUnit); SparseMatrix[] data = ratingOptions.contains("--as-tensor") ? rateDao.readTensor(columns, binThold) : rateDao .readData(columns, binThold); rateMatrix = data[0]; timeMatrix = data[1]; Recommender.rateMatrix = rateMatrix; Recommender.timeMatrix = timeMatrix; Recommender.rateDao = rateDao; Recommender.binThold = binThold; } /** * reset general (and static) settings */ protected void preset(String configFile) throws Exception { // a new configer cf = new FileConfiger(configFile); // seeding the general recommender Recommender.cf = cf; // reset recommenders' static properties Recommender.resetStatics = true; IterativeRecommender.resetStatics = true; GraphicRecommender.resetStatics = true; // LibRec outputs outputOptions = cf.getParamOptions("output.setup"); if (outputOptions != null) { tempDirPath = outputOptions.getString("-dir", "./Results/"); } // make output directory Recommender.tempDirPath = FileIO.makeDirectory(tempDirPath); // initialize random seed LineConfiger evalOptions = cf.getParamOptions("evaluation.setup"); Randoms.seed(evalOptions.getLong("--rand-seed", System.currentTimeMillis())); // initial random seed } /** * entry of the LibRec library * */ public static void main(String[] args) { try { new LibRec().execute(args); } catch (Exception e) { // capture exception to log file Logs.error(e.getMessage()); e.printStackTrace(); } } /** * process arguments specified at the command line * * @param args * command line arguments */ protected void cmdLine(String[] args) throws Exception { if (args == null || args.length < 1) { if (configFiles == null) configFiles = Arrays.asList("librec.conf"); return; } LineConfiger paramOptions = new LineConfiger(args); configFiles = paramOptions.contains("-c") ? paramOptions.getOptions("-c") : Arrays.asList("librec.conf"); if (paramOptions.contains("-v")) { // print out short version information System.out.println("LibRec version " + version); System.exit(0); } if (paramOptions.contains("--version")) { // print out full version information about(); System.exit(0); } if (paramOptions.contains("--dataset-spec")) { for (String configFile : configFiles) { // print out data set specification cf = new FileConfiger(configFile); readData(); rateDao.printSpecs(); String socialSet = cf.getPath("dataset.social"); if (!socialSet.equals("-1")) { DataDAO socDao = new DataDAO(socialSet, rateDao.getUserIds()); socDao.printSpecs(); } } System.exit(0); } if (paramOptions.contains("--dataset-split")) { for (String configFile : configFiles) { // split the training data set into "train-test" or "train-validation-test" subsets cf = new FileConfiger(configFile); readData(); double trainRatio = paramOptions.getDouble("-r", 0.8); boolean isValidationUsed = paramOptions.contains("-v"); double validRatio = isValidationUsed ? paramOptions.getDouble("-v") : 0; if (trainRatio <= 0 || validRatio < 0 || (trainRatio + validRatio) >= 1) { throw new Exception( "Wrong format! Accepted formats are either '-dataset-split ratio' or '-dataset-split trainRatio validRatio'"); } // split data DataSplitter ds = new DataSplitter(rateMatrix); SparseMatrix[] data = null; if (isValidationUsed) { data = ds.getRatio(trainRatio, validRatio); } else { switch (paramOptions.getString("-target")) { case "u": data = paramOptions.contains("--by-date") ? ds.getRatioByUserDate(trainRatio, timeMatrix) : ds .getRatioByUser(trainRatio); break; case "i": data = paramOptions.contains("--by-date") ? ds.getRatioByItemDate(trainRatio, timeMatrix) : ds .getRatioByItem(trainRatio); break; case "r": default: data = paramOptions.contains("--by-date") ? ds.getRatioByRatingDate(trainRatio, timeMatrix) : ds.getRatioByRating(trainRatio); break; } } // write out String dirPath = FileIO.makeDirectory(rateDao.getDataDirectory(), "split"); writeMatrix(data[0], dirPath + "training.txt"); if (isValidationUsed) { writeMatrix(data[1], dirPath + "validation.txt"); writeMatrix(data[2], dirPath + "test.txt"); } else { writeMatrix(data[1], dirPath + "test.txt"); } } System.exit(0); } } /** * write a matrix data into a file */ private void writeMatrix(SparseMatrix data, String filePath) throws Exception { // delete old file first FileIO.deleteFile(filePath); List<String> lines = new ArrayList<>(1500); for (MatrixEntry me : data) { int u = me.row(); int j = me.column(); double ruj = me.get(); if (ruj <= 0) continue; String user = rateDao.getUserId(u); String item = rateDao.getItemId(j); String timestamp = timeMatrix != null ? " " + timeMatrix.get(u, j) : ""; lines.add(user + " " + item + " " + (float) ruj + timestamp); if (lines.size() >= 1000) { FileIO.writeList(filePath, lines, true); lines.clear(); } } if (lines.size() > 0) FileIO.writeList(filePath, lines, true); Logs.debug("Matrix data is written to: {}", filePath); } /** * run a specific algorithm one or multiple times * */ protected void run() throws Exception { // evaluation setup String setup = cf.getString("evaluation.setup"); LineConfiger evalOptions = new LineConfiger(setup); Logs.info("With Setup: {}", setup); // repeat many times with the same settings int numRepeats = evalOptions.getInt("--repeat", 1); for (int i = 0; i < numRepeats; i++) { runAlgorithm(evalOptions); } } /** * prepare training and test data, and then run a specified recommender * */ private void runAlgorithm(LineConfiger evalOptions) throws Exception { DataSplitter ds = new DataSplitter(rateMatrix); SparseMatrix[] data = null; int N; double ratio; Recommender algo = null; switch (evalOptions.getMainParam().toLowerCase()) { case "cv": runCrossValidation(evalOptions); return; // make it close case "leave-one-out": boolean isByDate = evalOptions.contains("--by-date"); switch (evalOptions.getString("-target", "r")) { case "u": data = ds.getLOOByUser(isByDate, timeMatrix); break; case "i": data = ds.getLOOByItem(isByDate, timeMatrix); break; case "r": default: runLeaveOneOut(evalOptions); return; // } break; case "test-set": DataDAO testDao = new DataDAO(evalOptions.getString("-f"), rateDao.getUserIds(), rateDao.getItemIds()); testDao.setTimeUnit(timeUnit); SparseMatrix[] testData = testDao.readData(columns, binThold); data = new SparseMatrix[] { rateMatrix, testData[0] }; Recommender.testTimeMatrix = testData[1]; break; case "given-n": N = evalOptions.getInt("-N", 20); switch (evalOptions.getString("-target")) { case "i": data = evalOptions.contains("--by-date") ? ds.getGivenNByItemDate(N, timeMatrix) : ds .getGivenNByItem(N); break; case "u": default: data = evalOptions.contains("--by-date") ? ds.getGivenNByUserDate(N, timeMatrix) : ds .getGivenNByUser(N); break; } break; case "given-ratio": ratio = evalOptions.getDouble("-r", 0.8); switch (evalOptions.getString("-target")) { case "u": data = evalOptions.contains("--by-date") ? ds.getRatioByUserDate(ratio, timeMatrix) : ds .getRatioByUser(ratio); break; case "i": data = evalOptions.contains("--by-date") ? ds.getRatioByItemDate(ratio, timeMatrix) : ds .getRatioByItem(ratio); break; case "r": default: data = evalOptions.contains("--by-date") ? ds.getRatioByRatingDate(ratio, timeMatrix) : ds .getRatioByRating(ratio); break; } break; default: ratio = evalOptions.getDouble("-r", 0.8); data = ds.getRatioByRating(ratio); break; } algo = getRecommender(data, -1); algo.execute(); printEvalInfo(algo, algo.measures); } private void runCrossValidation(LineConfiger params) throws Exception { int kFold = params.getInt("-k", 5); boolean isParallelFold = params.isOn("-p", true); DataSplitter ds = new DataSplitter(rateMatrix, kFold); Thread[] ts = new Thread[kFold]; Recommender[] algos = new Recommender[kFold]; // average performance of k-fold AvgMetricCollection avgMeasures = null; for (int i = 0; i < kFold; i++) { Recommender algo = getRecommender(ds.getKthFold(i + 1), i + 1); if (avgMeasures == null) { avgMeasures = new AvgMetricCollection(algo); } algos[i] = algo; ts[i] = new Thread(algo); ts[i].start(); if (!isParallelFold) ts[i].join(); } if (isParallelFold) for (Thread t : ts) t.join(); for (Recommender algo : algos) { avgMeasures.updateFromMeasures(algo.measures); } avgMeasures.compute(kFold); printEvalInfo(algos[0], avgMeasures); } /** * interface to run Leave-one-out approach */ private void runLeaveOneOut(LineConfiger params) throws Exception { int numThreads = params.getInt("-t", Runtime.getRuntime().availableProcessors()); // default by number of processors Thread[] ts = new Thread[numThreads]; Recommender[] algos = new Recommender[numThreads]; // average performance of k-fold AvgMetricCollection avgMeasures = null; int rows = rateMatrix.numRows(); int cols = rateMatrix.numColumns(); int count = 0; for (MatrixEntry me : rateMatrix) { double rui = me.get(); if (rui <= 0) continue; int u = me.row(); int i = me.column(); // leave the current rating out SparseMatrix trainMatrix = new SparseMatrix(rateMatrix); trainMatrix.set(u, i, 0); SparseMatrix.reshape(trainMatrix); // build test matrix Table<Integer, Integer, Double> dataTable = HashBasedTable.create(); Multimap<Integer, Integer> colMap = HashMultimap.create(); dataTable.put(u, i, rui); colMap.put(i, u); SparseMatrix testMatrix = new SparseMatrix(rows, cols, dataTable, colMap); // get a recommender Recommender algo = getRecommender(new SparseMatrix[] { trainMatrix, testMatrix }, count + 1); if (avgMeasures == null) { avgMeasures = new AvgMetricCollection(algo); } algos[count] = algo; ts[count] = new Thread(algo); ts[count].start(); if (numThreads == 1) { ts[count].join(); // fold by fold avgMeasures.updateFromMeasures(algo.measures); } else if (count < numThreads) { count++; } if (count == numThreads) { // parallel fold for (Thread t : ts) t.join(); count = 0; // record performance for (Recommender algo2 : algos) { avgMeasures.updateFromMeasures(algo2.measures); } } } // normalization int size = rateMatrix.size(); avgMeasures.compute(size); printEvalInfo(algos[0], avgMeasures); } /** * print out the evaluation information for a specific algorithm */ private void printEvalInfo(Recommender algo, AvgMetricCollection ms) throws Exception { String result = ms.getEvalResultString(); // These are averaging metrics, so we have to do the time conversion // manually. Double trainTime = ms.getMetric("TrainTime").getValue(); Double testTime = ms.getMetric("TestTime").getValue(); // we add quota symbol to indicate the textual format of time String time = String.format("'%s','%s'", Dates.parse(trainTime.longValue()), Dates.parse(testTime.longValue())); //Dates.parse(m_time.longValue()) // double commas as the separation of results and configuration StringBuilder sb = new StringBuilder(); sb.append("Metrics: ").append(ms.getMetricNamesString()).append("\n"); String config = algo.toString(); sb.append(algo.algoName).append(",").append(result).append(",,"); if (!config.isEmpty()) sb.append(config).append(","); sb.append(time).append("\n"); String evalInfo = sb.toString(); Logs.info(evalInfo); // copy to clipboard for convenience, useful for a single run if (outputOptions.contains("--to-clipboard")) { Strings.toClipboard(evalInfo); Logs.debug("Results have been copied to clipboard!"); } // append to a specific file, useful for multiple runs if (outputOptions.contains("--to-file")) { String filePath = outputOptions.getString("--to-file", tempDirPath + algorithm + ".txt"); FileIO.writeString(filePath, evalInfo, true); Logs.debug("Results have been collected to file: {}", filePath); } } /** * print out the evaluation information for a specific algorithm */ private void printEvalInfo(Recommender algo, MetricCollection ms) throws Exception { String result = ms.getEvalResultString(); // we add quota symbol to indicate the textual format of time String time = String.format("'%s','%s'", ms.getTimeMetric("TrainTime").getValueAsString(), ms.getTimeMetric("TestTime").getValueAsString()); // double commas as the separation of results and configuration StringBuilder sb = new StringBuilder(); sb.append("Metrics: ").append(ms.getMetricNamesString()).append("\n"); String config = algo.toString(); sb.append(algo.algoName).append(",").append(result).append(",,"); if (!config.isEmpty()) sb.append(config).append(","); sb.append(time).append("\n"); String evalInfo = sb.toString(); Logs.info(evalInfo); // copy to clipboard for convenience, useful for a single run if (outputOptions.contains("--to-clipboard")) { Strings.toClipboard(evalInfo); Logs.debug("Results have been copied to clipboard!"); } // append to a specific file, useful for multiple runs if (outputOptions.contains("--to-file")) { String filePath = outputOptions.getString("--to-file", tempDirPath + algorithm + ".txt"); FileIO.writeString(filePath, evalInfo, true); Logs.debug("Results have been collected to file: {}", filePath); } } /** * Send a notification of completeness * * @param attachment * email attachment */ protected void notifyMe(String attachment) throws Exception { String hostInfo = FileIO.getCurrentFolder() + "." + algorithm + " [" + Systems.getIP() + "]"; LineConfiger emailOptions = cf.getParamOptions("email.setup"); if (emailOptions == null || !emailOptions.isMainOn()) { System.out.println("Program " + hostInfo + " has completed!"); return; } EMailer notifier = new EMailer(); Properties props = notifier.getProps(); props.setProperty("mail.debug", "false"); String port = emailOptions.getString("-port"); props.setProperty("mail.smtp.host", emailOptions.getString("-host")); props.setProperty("mail.smtp.port", port); props.setProperty("mail.smtp.auth", emailOptions.getString("-auth")); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); final String user = emailOptions.getString("-user"); props.setProperty("mail.smtp.user", user); props.setProperty("mail.smtp.password", emailOptions.getString("-password")); props.setProperty("mail.from", user); props.setProperty("mail.to", emailOptions.getString("-to")); props.setProperty("mail.subject", hostInfo); props.setProperty("mail.text", "Program was completed @" + Dates.now()); String msg = "Program [" + algorithm + "] has completed !"; notifier.send(msg, attachment); } /** * @return a recommender to be run */ protected Recommender getRecommender(SparseMatrix[] data, int fold) throws Exception { algorithm = cf.getString("recommender"); SparseMatrix trainMatrix = data[0], testMatrix = data[1]; // output data writeData(trainMatrix, testMatrix, fold); switch (algorithm.toLowerCase()) { /* baselines */ case "globalavg": return new GlobalAverage(trainMatrix, testMatrix, fold); case "useravg": return new UserAverage(trainMatrix, testMatrix, fold); case "itemavg": return new ItemAverage(trainMatrix, testMatrix, fold); case "usercluster": return new UserCluster(trainMatrix, testMatrix, fold); case "itemcluster": return new ItemCluster(trainMatrix, testMatrix, fold); case "random": return new RandomGuess(trainMatrix, testMatrix, fold); case "constant": return new ConstantGuess(trainMatrix, testMatrix, fold); case "mostpop": return new MostPopular(trainMatrix, testMatrix, fold); /* rating prediction */ case "userknn": return new UserKNN(trainMatrix, testMatrix, fold); case "itemknn": return new ItemKNN(trainMatrix, testMatrix, fold); case "itembigram": return new ItemBigram(trainMatrix, testMatrix, fold); case "regsvd": return new PMF(trainMatrix, testMatrix, fold); case "rfrec": return new RfRec(trainMatrix, testMatrix, fold); case "biasedmf": return new BiasedMF(trainMatrix, testMatrix, fold); case "gplsa": return new GPLSA(trainMatrix, testMatrix, fold); case "svd++": return new SVDPlusPlus(trainMatrix, testMatrix, fold); case "timesvd++": return new TimeSVD(trainMatrix, testMatrix, fold); case "pmf": return new PMF(trainMatrix, testMatrix, fold); case "bpmf": return new BPMF(trainMatrix, testMatrix, fold); case "socialmf": return new SocialMF(trainMatrix, testMatrix, fold); case "trustmf": return new TrustMF(trainMatrix, testMatrix, fold); case "sorec": return new SoRec(trainMatrix, testMatrix, fold); case "soreg": return new SoReg(trainMatrix, testMatrix, fold); case "rste": return new RSTE(trainMatrix, testMatrix, fold); case "trustsvd": return new TrustSVD(trainMatrix, testMatrix, fold); case "urp": return new URP(trainMatrix, testMatrix, fold); case "ldcc": return new LDCC(trainMatrix, testMatrix, fold); case "cptf": return new CPTF(trainMatrix, testMatrix, fold); /* item ranking */ case "climf": return new CLiMF(trainMatrix, testMatrix, fold); case "fismrmse": return new FISMrmse(trainMatrix, testMatrix, fold); case "fism": case "fismauc": return new FISMauc(trainMatrix, testMatrix, fold); case "lrmf": return new LRMF(trainMatrix, testMatrix, fold); case "rankals": return new RankALS(trainMatrix, testMatrix, fold); case "ranksgd": return new RankSGD(trainMatrix, testMatrix, fold); case "wrmf": return new WRMF(trainMatrix, testMatrix, fold); case "bpr": return new BPR(trainMatrix, testMatrix, fold); case "wbpr": return new WBPR(trainMatrix, testMatrix, fold); case "gbpr": return new GBPR(trainMatrix, testMatrix, fold); case "sbpr": return new SBPR(trainMatrix, testMatrix, fold); case "slim": return new SLIM(trainMatrix, testMatrix, fold); case "lda": return new LDA(trainMatrix, testMatrix, fold); /* extension */ case "nmf": return new NMF(trainMatrix, testMatrix, fold); case "hybrid": return new Hybrid(trainMatrix, testMatrix, fold); case "slopeone": return new SlopeOne(trainMatrix, testMatrix, fold); case "pd": return new PD(trainMatrix, testMatrix, fold); case "ar": return new AR(trainMatrix, testMatrix, fold); case "prankd": return new PRankD(trainMatrix, testMatrix, fold); case "external": return new External(trainMatrix, testMatrix, fold); /* both tasks */ case "bucm": return new BUCM(trainMatrix, testMatrix, fold); case "bhfree": return new BHfree(trainMatrix, testMatrix, fold); default: throw new Exception("No recommender is specified!"); } } protected void writeData(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { if (outputOptions != null && outputOptions.contains("--fold-data")) { String prefix = rateDao.getDataDirectory() + rateDao.getDataName(); String suffix = ((fold >= 0) ? "-" + fold : "") + ".txt"; try { writeMatrix(trainMatrix, prefix + "-train" + suffix); writeMatrix(testMatrix, prefix + "-test" + suffix); } catch (Exception e) { Logs.error(e.getMessage()); e.printStackTrace(); } } } /** * set the configuration file to be used */ public void setConfigFiles(String... configurations) { configFiles = Arrays.asList(configurations); } /** * Print out software information */ private void about() { String about = "\nLibRec version " + version + ", copyright (C) 2014-2015 Guibing Guo \n\n" /* Description */ + "LibRec is free software: you can redistribute it and/or modify \n" + "it under the terms of the GNU General Public License as published by \n" + "the Free Software Foundation, either version 3 of the License, \n" + "or (at your option) any later version. \n\n" /* Usage */ + "LibRec is distributed in the hope that it will be useful, \n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of \n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n" + "GNU General Public License for more details. \n\n" /* licence */ + "You should have received a copy of the GNU General Public License \n" + "along with LibRec. If not, see <http://www.gnu.org/licenses/>."; System.out.println(about); } }
26,623
28.289329
118
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/mio/client-java/.mvn/wrapper/MavenWrapperDownloader.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
4,625
39.226087
116
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/mio/client-java/src/main/java/org/rustsgx/mio/AppClient.java
package org.rustsgx.mio; import org.apache.commons.io.IOUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import org.apache.http.message.BasicNameValuePair; import javax.net.ssl.HttpsURLConnection; import java.io.IOException; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AppClient { private String scheme = null; private String url = null; private int port = 80; public AppClient(final String scheme, final String url, final int port) { this.scheme = scheme; this.url = url; this.port = port; } public String request(final String requestType, final String endpoint, final HashMap<String, String> parameters) throws URISyntaxException, IOException { HttpURLConnection conn = null; try { List<NameValuePair> nameValues = new ArrayList<NameValuePair>(); for (String identifier : parameters.keySet()) { NameValuePair pair = new BasicNameValuePair(identifier, parameters.get(identifier)); nameValues.add(pair); } URI uri = new URIBuilder() .setScheme(this.scheme) .setHost(this.url) .setPort(this.port) .setPath(endpoint) .setParameters(nameValues) .build(); if (requestType.equals("https")) { HttpsURLConnection httpsConn = (HttpsURLConnection) uri.toURL().openConnection(); httpsConn.setRequestMethod(requestType); httpsConn.setDoInput(true); httpsConn.connect(); conn = httpsConn; } else { HttpURLConnection httpConn = (HttpURLConnection) uri.toURL().openConnection(); httpConn.setRequestMethod(requestType); httpConn.setDoInput(true); httpConn.connect(); conn = httpConn; } StringWriter writer = new StringWriter(); IOUtils.copy(conn.getInputStream(), writer, "UTF-8"); return writer.toString(); } finally { if (conn != null) { conn.disconnect(); } } } }
2,486
30.481013
108
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/mio/client-java/src/main/java/org/rustsgx/mio/MIOClientApplication.java
package org.rustsgx.mio; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.net.Socket; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @SpringBootApplication public class MIOClientApplication { public static void main(String[] args) { System.out.println("This is a mio client application"); SSLHelper.loadCerts("ca.cert"); int count = 20; ExecutorService service = Executors.newFixedThreadPool(count); for (int i = 0; i < count; i++) { service.execute(() -> { try { AppClient appClient = new AppClient("https", "localhost", 8443); System.out.println(appClient.request("GET", "/", new HashMap<>())); Thread.sleep(10000); } catch (Exception ex) { ex.printStackTrace(); } }); } service.shutdown(); service.awaitTermination(10000000, TimeUnit.SECONDS); } }
1,113
30.828571
87
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/mio/client-java/src/main/java/org/rustsgx/mio/SSLHelper.java
package org.rustsgx.mio; import javax.net.ssl.*; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.Collection; public class SSLHelper { public static void loadCerts(String fileName) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, IOException, URISyntaxException { ClassLoader classLoader = SSLHelper.class.getClassLoader(); final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final Collection<? extends Certificate> certs = certFactory.generateCertificates(classLoader.getResourceAsStream(fileName)); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); certs.iterator().forEachRemaining(cert -> { try { keyStore.setCertificateEntry(java.util.UUID.randomUUID().toString(), cert); } catch (KeyStoreException e) { e.printStackTrace(); } }); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); TrustManager[] trustManager = tmf.getTrustManagers(); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManager, new java.security.SecureRandom()); SSLSocketFactory sslFactory = context.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory); } }
1,837
38.956522
181
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/.mvn/wrapper/MavenWrapperDownloader.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
4,625
39.226087
116
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/CommonUtils.java
package org.rustsgx.ueraclientjava; import java.io.File; import java.util.ArrayList; import java.util.List; public class CommonUtils { public static List<Byte> string2BytesList(String[] strings) { ArrayList<Byte> arrayList = new ArrayList<Byte>(); for (int i = 0; i < strings.length; i++) { int intVal = Integer.decode(strings[i]); arrayList.add(Byte.valueOf((byte) intVal)); } return arrayList; } public static int getIndexOf(List<Byte> b, List<Byte> bb) { if (b == null || bb == null || b.size() == 0 || bb.size() == 0 || b.size() < bb.size()) return -1; int i, j; for (i = 0; i < b.size() - bb.size() + 1; i++) { if (b.get(i) == bb.get(0)) { for (j = 1; j < bb.size(); j++) { if (b.get(i + j) != bb.get(j)) break; } if (j == bb.size()) return i; } } return -1; } public static byte hexToByte(String inHex) { return (byte) Integer.parseInt(inHex, 16); } public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = "0" + hex; } return hex; } public static byte[] list2array(List<Byte> list) { byte[] bytes = new byte[list.size()]; for (int i = 0; i < list.size(); i++) { bytes[i] = list.get(i); } return bytes; } public static void printCert(byte[] rawByte) { System.out.print("---received-server cert: [Certificate(b\""); for (int i = 0; i < rawByte.length; i++) { char c = (char) (Byte.toUnsignedInt(rawByte[i])); if (c == '\n') { System.out.print("\\n"); } else if (c == '\r') { System.out.print("\\r"); } else if (c == '\t') { System.out.print("\\t"); } else if (c == '\\' || c == '"') { System.out.printf("\\%c", c); } else if (Byte.toUnsignedInt(rawByte[i]) >= 32 && Byte.toUnsignedInt(rawByte[i]) < 127) { System.out.printf("%c", c); } else { System.out.printf("\\x%02x", rawByte[i]); } } System.out.println("\")]"); } }
2,404
31.066667
102
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/PemReader.java
package org.rustsgx.ueraclientjava; import java.io.*; import java.nio.CharBuffer; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.GeneralSecurityException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.util.regex.Pattern.CASE_INSENSITIVE; public class PemReader { private static final Pattern CERT_PATTERN = Pattern.compile( "-+BEGIN\\s+.*CERTIFICATE[^-]*-+(?:\\s|\\r|\\n)+" + // Header "([a-z0-9+/=\\r\\n]+)" + // Base64 text "-+END\\s+.*CERTIFICATE[^-]*-+", // Footer CASE_INSENSITIVE); public static List<X509Certificate> readCertificateChain(File certificateChainFile) throws IOException, GeneralSecurityException { String contents = readFile(certificateChainFile); Matcher matcher = CERT_PATTERN.matcher(contents); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> certificates = new ArrayList<>(); int start = 0; while (matcher.find(start)) { byte[] buffer = base64Decode(matcher.group(1)); certificates.add((X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer))); start = matcher.end(); } return certificates; } private static String readFile(File file) throws IOException { try (Reader reader = new InputStreamReader(new FileInputStream(file), US_ASCII)) { StringBuilder stringBuilder = new StringBuilder(); CharBuffer buffer = CharBuffer.allocate(2048); while (reader.read(buffer) != -1) { buffer.flip(); stringBuilder.append(buffer); buffer.clear(); } return stringBuilder.toString(); } } private static byte[] base64Decode(String base64) { return Base64.getMimeDecoder().decode(base64.getBytes(US_ASCII)); } public static PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); String temp = new String(keyBytes); String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----\n", ""); privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", ""); //System.out.println("Private key\n"+privKeyPEM); org.bouncycastle.util.encoders.Base64 b64 = new org.bouncycastle.util.encoders.Base64(); byte[] decoded = b64.decode(privKeyPEM); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance(algorithm); return kf.generatePrivate(spec); } }
3,237
37.547619
121
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/PlatformInfoBlob.java
package org.rustsgx.ueraclientjava; import java.util.Arrays; public class PlatformInfoBlob { private int sgx_epid_group_flags; private long sgx_tcb_evaluation_flags; private long pse_evaluation_flags; private String latest_equivalent_tcb_psvn; private String latest_pse_isvsvn; private String latest_psda_svn; private long xeid; private long gid; private SGXEC256Signature sgx_ec256_signature_t; class SGXEC256Signature { private String gx; private String gy; public String getGx() { return gx; } public void setGx(String gx) { this.gx = gx; } public String getGy() { return gy; } public void setGy(String gy) { this.gy = gy; } } public int getSgx_epid_group_flags() { return sgx_epid_group_flags; } public void setSgx_epid_group_flags(int sgx_epid_group_flags) { this.sgx_epid_group_flags = sgx_epid_group_flags; } public void setSgx_tcb_evaluation_flags(int sgx_tcb_evaluation_flags) { this.sgx_tcb_evaluation_flags = sgx_tcb_evaluation_flags; } public void setPse_evaluation_flags(int pse_evaluation_flags) { this.pse_evaluation_flags = pse_evaluation_flags; } public String getLatest_equivalent_tcb_psvn() { return latest_equivalent_tcb_psvn; } public void setLatest_equivalent_tcb_psvn(String latest_equivalent_tcb_psvn) { this.latest_equivalent_tcb_psvn = latest_equivalent_tcb_psvn; } public String getLatest_pse_isvsvn() { return latest_pse_isvsvn; } public void setLatest_pse_isvsvn(String latest_pse_isvsvn) { this.latest_pse_isvsvn = latest_pse_isvsvn; } public String getLatest_psda_svn() { return latest_psda_svn; } public void setLatest_psda_svn(String latest_psda_svn) { this.latest_psda_svn = latest_psda_svn; } public void setXeid(int xeid) { this.xeid = xeid; } public long getSgx_tcb_evaluation_flags() { return sgx_tcb_evaluation_flags; } public void setSgx_tcb_evaluation_flags(long sgx_tcb_evaluation_flags) { this.sgx_tcb_evaluation_flags = sgx_tcb_evaluation_flags; } public long getPse_evaluation_flags() { return pse_evaluation_flags; } public void setPse_evaluation_flags(long pse_evaluation_flags) { this.pse_evaluation_flags = pse_evaluation_flags; } public long getXeid() { return xeid; } public void setXeid(long xeid) { this.xeid = xeid; } public long getGid() { return gid; } public void setGid(long gid) { this.gid = gid; } public void setGid(int gid) { this.gid = gid; } public SGXEC256Signature getSgx_ec256_signature_t() { return sgx_ec256_signature_t; } public void setSgx_ec256_signature_t(SGXEC256Signature sgx_ec256_signature_t) { this.sgx_ec256_signature_t = sgx_ec256_signature_t; } public void parsePlatInfo(byte[] piBlobByte, PlatformInfoBlob pfInfo) { pfInfo.sgx_ec256_signature_t = new SGXEC256Signature(); pfInfo.sgx_epid_group_flags = Byte.toUnsignedInt(piBlobByte[0]); pfInfo.sgx_tcb_evaluation_flags = computeDec(Arrays.copyOfRange(piBlobByte, 1, 3)); pfInfo.pse_evaluation_flags = computeDec(Arrays.copyOfRange(piBlobByte, 3, 5)); pfInfo.latest_equivalent_tcb_psvn = byte2Str(Arrays.copyOfRange(piBlobByte, 5, 23)); pfInfo.latest_pse_isvsvn = byte2Str(Arrays.copyOfRange(piBlobByte, 23, 25)); pfInfo.latest_psda_svn = byte2Str(Arrays.copyOfRange(piBlobByte, 25, 29)); pfInfo.xeid = computeDec(Arrays.copyOfRange(piBlobByte, 29, 33)); pfInfo.gid = computeDec(Arrays.copyOfRange(piBlobByte, 33, 37)); pfInfo.sgx_ec256_signature_t.gx = byte2Str(Arrays.copyOfRange(piBlobByte, 37, 69)); pfInfo.sgx_ec256_signature_t.gy = byte2Str(Arrays.copyOf(piBlobByte, 69)); } public long computeDec(byte[] piBlobSlice) { String hexString = new String(); for (int i = piBlobSlice.length - 1; i >= 0; i--) { hexString += CommonUtils.byteToHex(piBlobSlice[i]); } return Long.parseLong(hexString, 16); } public String byte2Str(byte[] piBlobSlice) { String piBlobStr = new String(); for (int i = 0; i < piBlobSlice.length; i++) { piBlobStr += Byte.toUnsignedInt(piBlobSlice[i]) + ", "; } return "[" + piBlobStr.substring(0, piBlobStr.length() - 2) + "]"; } }
4,650
28.251572
92
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/QuoteReportData.java
package org.rustsgx.ueraclientjava; //TODO: add more origin filed if needed public class QuoteReportData { private int version; private int signType; private QuoteReportBody quoteReportBody; public void setVersion(int version) { this.version = version; } public void setSignType(int signType) { this.signType = signType; } public void setQuoteReportBody(QuoteReportBody quoteReportBody) { this.quoteReportBody = quoteReportBody; } public int getVersion() { return version; } public int getSignType() { return signType; } public QuoteReportBody getQuoteReportBody() { return quoteReportBody; } //TODO: add more origin filed if needed class QuoteReportBody { private String mrEnclave; private String mrSigner; private String reportData; public void setMrEnclave(String mrEnclave) { this.mrEnclave = mrEnclave; } public void setMrSigner(String mrSigner) { this.mrSigner = mrSigner; } public void setReportData(String reportData) { this.reportData = reportData; } public String getMrEnclave() { return mrEnclave; } public String getMrSigner() { return mrSigner; } public String getReportData() { return reportData; } } public void pareReport(byte[] quoteRep, String repHex, QuoteReportData quoteReportData) { quoteReportData.quoteReportBody = new QuoteReportBody(); quoteReportData.version = Byte.toUnsignedInt(quoteRep[0]); quoteReportData.signType = Byte.toUnsignedInt(quoteRep[1]); quoteReportData.quoteReportBody.mrEnclave = repHex.substring(224, 288); quoteReportData.quoteReportBody.mrSigner = repHex.substring(352, 416); quoteReportData.quoteReportBody.reportData = repHex.substring(736, 864); } }
1,984
26.191781
93
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/ServerCertData.java
package org.rustsgx.ueraclientjava; import java.util.List; public class ServerCertData { public List<Byte> payload; public byte[] pub_k; public ServerCertData(List<Byte> payload, byte[] pub_k) { this.payload = payload; this.pub_k = pub_k; } }
277
20.384615
61
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/SgxCertVerifier.java
package org.rustsgx.ueraclientjava; import java.io.File; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.List; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class SgxCertVerifier { TrustManager[] trustAllCerts; KeyManagerFactory keyManagerFactory; public SgxCertVerifier() throws Exception { //init keyManagerFactory try { File crtFile = new File("./../cert/client.crt"); List<X509Certificate> certificateChain = PemReader.readCertificateChain(crtFile); PrivateKey key = PemReader.getPemPrivateKey("./../cert/client.pkcs8", "EC"); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("key", key, "".toCharArray(), certificateChain.stream().toArray(Certificate[]::new)); this.keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); this.keyManagerFactory.init(keyStore, "".toCharArray()); } catch (Exception e) { System.out.print(e.toString()); throw e; } //init TrustManager this.trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { CommonUtils.printCert(certs[0].getEncoded()); List<Byte> byteArray = new ArrayList<Byte>(); for (int i = 0; i < certs[0].getEncoded().length; i++) { byteArray.add(certs[0].getEncoded()[i]); } // get the pubkey and payload from raw data ServerCertData certData = VerifyMraCert.unmarshalByte(byteArray); try { // Load Intel CA, Verify Cert and Signature byte[] attnReportRaw = VerifyMraCert.verifyCert(certData.payload); // Verify attestation report VerifyMraCert.verifyAtteReport(attnReportRaw, certData.pub_k); } catch (Exception e) { System.out.println(e.toString()); System.exit(0); } } } }; } }
2,906
39.943662
122
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/SgxQuoteReport.java
package org.rustsgx.ueraclientjava; public class SgxQuoteReport { private String id; private String timestamp; private int version; private String isvEnclaveQuoteStatus; private String platformInfoBlob; private String isvEnclaveQuoteBody; public String getId() { return id; } public String getTimestamp() { return timestamp; } public int getVersion() { return version; } public String getIsvEnclaveQuoteStatus() { return isvEnclaveQuoteStatus; } public String getPlatformInfoBlob() { return platformInfoBlob; } public String getIsvEnclaveQuoteBody() { return isvEnclaveQuoteBody; } }
710
19.911765
46
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/UeRaClientJavaApplication.java
package org.rustsgx.ueraclientjava; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.net.ssl.*; import java.io.*; import java.net.Socket; import java.security.*; @SpringBootApplication public class UeRaClientJavaApplication { public static void main(String[] args) { System.out.println("Starting ue-ra-client-java"); try { SSLContext sc = SSLContext.getInstance("SSL"); SgxCertVerifier sgxCertVerifier = new SgxCertVerifier(); sc.init(sgxCertVerifier.keyManagerFactory.getKeyManagers(), sgxCertVerifier.trustAllCerts, new SecureRandom()); SSLSocketFactory sf = sc.getSocketFactory(); System.out.println("Connecting to localhost:3443"); Socket s = sf.createSocket("127.0.0.1", 3443); DataOutputStream out = new DataOutputStream(s.getOutputStream()); String str = "hello ue-ra-java-client"; out.write(str.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String x = in.readLine(); System.out.printf("server replied: %s\n", x); out.close(); in.close(); } catch (Exception e) { System.out.println(e.toString()); System.exit(0); } } }
1,354
30.511628
123
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/main/java/org/rustsgx/ueraclientjava/VerifyMraCert.java
package org.rustsgx.ueraclientjava; import com.google.gson.Gson; import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.openssl.PEMParser; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.Seconds; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.security.Signature; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Base64; import java.util.List; public class VerifyMraCert { public static ServerCertData unmarshalByte(List<Byte> certList) { // Search for Public Key prime256v1 OID String[] prime256v1_oid_string = new String[]{"0x06", "0x08", "0x2a", "0x86", "0x48", "0xce", "0x3d", "0x03", "0x01", "0x07"}; List<Byte> prime256v1_oid = CommonUtils.string2BytesList(prime256v1_oid_string); int offset = CommonUtils.getIndexOf(certList, prime256v1_oid); offset += 11; // 10 + TAG (0x03) // Obtain Public Key length int length = Byte.toUnsignedInt(certList.get(offset)); if (length > Byte.toUnsignedInt(CommonUtils.hexToByte("80"))) { length = Byte.toUnsignedInt(certList.get(offset + 1)) * 256 + Byte.toUnsignedInt(certList.get(offset + 2)); offset += 2; } // Obtain Public Key offset += 1; byte[] pub_k = CommonUtils.list2array(certList.subList(offset + 2, offset + length)); // skip "00 04" String[] ns_cmt_oid_string = new String[]{"0x06", "0x09", "0x60", "0x86", "0x48", "0x01", "0x86", "0xf8", "0x42", "0x01", "0x0d"}; List<Byte> ns_cmt_oid = CommonUtils.string2BytesList(ns_cmt_oid_string); offset = CommonUtils.getIndexOf(certList, ns_cmt_oid); offset += 12; // 10 + TAG (0x03) // Obtain Netscape Comment length length = Byte.toUnsignedInt(certList.get(offset)); if (length > Byte.toUnsignedInt(CommonUtils.hexToByte("80"))) { length = Byte.toUnsignedInt(certList.get(offset + 1)) * 256 + Byte.toUnsignedInt(certList.get(offset + 2)); offset += 2; } offset += 1; List<Byte> payload = certList.subList(offset, offset + length); return new ServerCertData(payload, pub_k); } public static byte[] verifyCert(List<Byte> payload) throws Exception { Base64.Decoder decoder = Base64.getDecoder(); int startIndex = payload.indexOf(CommonUtils.hexToByte("7c")); int endIndex = payload.lastIndexOf(CommonUtils.hexToByte("7c")); byte[] attnReportRaw = CommonUtils.list2array(payload.subList(0, startIndex)); byte[] sigRaw = CommonUtils.list2array(payload.subList(startIndex + 1, endIndex)); byte[] sig = decoder.decode(sigRaw); byte[] sigCertRaw = CommonUtils.list2array(payload.subList(endIndex + 1, payload.size())); byte[] sigCert = decoder.decode(sigCertRaw); X509Certificate server, provider; try { CertificateFactory cf = CertificateFactory.getInstance("X509"); server = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(sigCert)); FileReader reader = new FileReader("./../cert/AttestationReportSigningCACert.pem"); PEMParser pemParser = new PEMParser(reader); X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) pemParser.readObject(); provider = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); server.verify(provider.getPublicKey()); } catch (Exception e) { throw e; } System.out.println("Cert is good"); try { Signature signature = Signature.getInstance(server.getSigAlgName()); signature.initVerify(server); signature.update(attnReportRaw); boolean ok = signature.verify(sig); if (ok == false) { throw new Exception("failed to parse root certificate"); } } catch (Exception e) { throw e; } System.out.println("Signature good"); return attnReportRaw; } public static void verifyAtteReport(byte[] attnReportRaw, byte[] pubK) throws Exception { //extract data from attReportJson Gson gson = new Gson(); String attReportJson = new String(); for (int i = 0; i < attnReportRaw.length; i++) { attReportJson += (char) attnReportRaw[i]; } SgxQuoteReport sgxQr; try { sgxQr = gson.fromJson(attReportJson, SgxQuoteReport.class); } catch (Exception e) { throw e; } //1 Check timestamp is within 24H if (sgxQr.getTimestamp().length() != 0) { String timeFixed = sgxQr.getTimestamp() + "Z"; DateTime dateTime = new DateTime(timeFixed); DateTime now = new DateTime(); Interval interval = new Interval(dateTime.getMillis(), now.getMillis()); System.out.printf("Time diff = %d\n", Seconds.secondsIn(interval).getSeconds()); } else { throw new Exception("Failed to fetch timestamp from attestation report"); } //2 Verify quote status (mandatory field) if (sgxQr.getIsvEnclaveQuoteStatus().length() != 0) { System.out.printf("isvEnclaveQuoteStatus = %s\n", sgxQr.getIsvEnclaveQuoteStatus()); switch (sgxQr.getIsvEnclaveQuoteStatus()) { case "OK": break; case "GROUP_OUT_OF_DATE": case "GROUP_REVOKED": case "CONFIGURATION_NEEDED": if (sgxQr.getPlatformInfoBlob().length() != 0) { byte[] pfBlob = HexBin.decode(sgxQr.getPlatformInfoBlob()); PlatformInfoBlob platformInfoBlob = new PlatformInfoBlob(); platformInfoBlob.parsePlatInfo(Arrays.copyOfRange(pfBlob, 4, pfBlob.length), platformInfoBlob); System.out.printf("Platform info is: %s\n", gson.toJson(platformInfoBlob)); } else { throw new Exception("Failed to fetch platformInfoBlob from attestation report"); } break; default: throw new Exception("SGX_ERROR_UNEXPECTED"); } } else { throw new Exception("Failed to fetch isvEnclaveQuoteStatus from attestation report"); } // 3 Verify quote body if (sgxQr.getIsvEnclaveQuoteBody().length() != 0) { Base64.Decoder decoder = Base64.getDecoder(); byte[] qb = decoder.decode(sgxQr.getIsvEnclaveQuoteBody()); String qbString = new String(); String qbBytes = new String(); String pubKeyString = new String(); for (int i = 0; i < qb.length; i++) { qbBytes += String.format("%d, ", Byte.toUnsignedInt(qb[i])); qbString += String.format("%02x", qb[i]); } for (int i = 0; i < pubK.length; i++) { pubKeyString += String.format("%02x", pubK[i]); } QuoteReportData quoteReportData = new QuoteReportData(); quoteReportData.pareReport(qb, qbString, quoteReportData); System.out.println("Quote = [" + qbBytes.substring(0, qbBytes.length() - 2) + "]"); System.out.printf("sgx quote version = %s\n", quoteReportData.getVersion()); System.out.printf("sgx quote signature type = %s\n", quoteReportData.getSignType()); System.out.printf("sgx quote report_data = %s\n", quoteReportData.getQuoteReportBody().getReportData()); System.out.printf("sgx quote mr_enclave = %s\n", quoteReportData.getQuoteReportBody().getMrEnclave()); System.out.printf("sgx quote mr_signer = %s\n", quoteReportData.getQuoteReportBody().getMrSigner()); System.out.printf("Anticipated public key = %s\n", pubKeyString); if (pubKeyString.equals(quoteReportData.getQuoteReportBody().getReportData())) { System.out.println("ue RA done!"); } } else { throw new Exception("Failed to fetch isvEnclaveQuoteBody from attestation report"); } } }
8,579
43.921466
119
java
incubator-teaclave-sgx-sdk
incubator-teaclave-sgx-sdk-master/samplecode/ue-ra/ue-ra-client-java/src/test/java/org/rustsgx/ueraclientjava/UeRaClientJavaApplicationTests.java
package org.rustsgx.ueraclientjava; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class UeRaClientJavaApplicationTests { @Test public void contextLoads() { } }
351
19.705882
60
java
MicroRTS
MicroRTS-master/src/ai/BranchingFactorCalculatorBigInteger.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai; import java.math.BigInteger; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.PlayerActionGenerator; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.Pair; /** * * @author santi * * This class implements several methods for calculating the branching factor of a given game state: * - branchingFactorUpperBound: this is very fast, but only provides an uppower bound * Basically computing the number of actions each individual unit can execute, and * multiplying these numbers. * - branchingFactor: this is exact, but very slow. It enumerates each move. * - branchingFactorByResourceUsage: same, but returns a vector, with the number of actions * that require different nuber of resources. * - branchingFactorByResourceUsageFast/ * - branchingFactorByResourceUsageSeparatingFast: these are the fastest methods, * the second takes into account that there are groups of units for which we can compute * the branching factor separatedly. * * All the methods (Except for branchingFactorUpperBound) should return the same value */ public class BranchingFactorCalculatorBigInteger { public static int DEBUG = 0; public static BigInteger branchingFactorUpperBound(GameState gs, int player) throws Exception { PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); return BigInteger.valueOf(pag.getSize()); } public static BigInteger branchingFactor(GameState gs, int player) throws Exception { BigInteger n = BigInteger.valueOf(0); PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); while(pag.getNextAction(-1)!=null) n = n.add(BigInteger.ONE); return n; } public static BigInteger[] branchingFactorByResourceUsage(GameState gs, int player) throws Exception { BigInteger n[] = new BigInteger[gs.getPlayer(player).getResources()+1]; for(int i = 0;i<n.length;i++) n[i] = BigInteger.ZERO; PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); PlayerAction pa = null; do{ pa = pag.getNextAction(-1); if (pa!=null) { int r = 0; for(Pair<Unit,UnitAction> tmp:pa.getActions()) { r+=tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState()).getResourcesUsed(player); } // n[(pa.getResourceUsage()).getResourcesUsed(player)]++; n[r] = n[r].add(BigInteger.ONE); } }while(pa!=null); return n; } public static void addFootPrint(int map[][], int ID, int x, int y) { // System.out.println(ID + " -> " + x + "," + y); if (map[x][y]==0) { map[x][y] = ID; } else { // System.out.println("FF"); // propagate this ID with floodfill: int ID_to_remove = map[x][y]; List<Integer> open_x = new LinkedList<>(); List<Integer> open_y = new LinkedList<>(); open_x.add(x); open_y.add(y); while(!open_x.isEmpty()) { x = open_x.remove(0); y = open_y.remove(0); if (map[x][y]==ID) continue; map[x][y] = ID; if (x>0 && map[x-1][y]==ID_to_remove) { open_x.add(0,x-1); open_y.add(0,y); } if (x<map.length-1 && map[x+1][y]==ID_to_remove) { open_x.add(0,x+1); open_y.add(0,y); } if (y>0 && map[x][y-1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y-1); } if (y<map[0].length-1 && map[x][y+1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y+1); } } } } public static BigInteger branchingFactorByResourceUsageSeparatingFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); // This matrix helps finding areas that can be separated without causing conflicts: int [][]separation = new int[pgs2.getWidth()][pgs2.getHeight()]; int ID = 1; for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { List<UnitAction> ual = u.getUnitActions(gs2); addFootPrint(separation,ID,u.getX(), u.getY()); for(UnitAction ua:ual) { ResourceUsage ru = (ResourceUsage)ua.resourceUsage(u, gs2.getPhysicalGameState()); for(int pos:ru.getPositionsUsed()) { int x = pos%pgs2.getWidth(); int y = pos/pgs2.getWidth(); addFootPrint(separation,ID,x,y); } } ID++; } } LinkedList<Integer> areas = new LinkedList<>(); for(int i = 0;i<pgs2.getHeight();i++) { for(int j = 0;j<pgs2.getWidth();j++) { if (separation[j][i]!=0 && !areas.contains(separation[j][i])) areas.add(separation[j][i]); // System.out.print((separation[j][i]<10 ? " ":"") + separation[j][i] + " "); } // System.out.println(""); } // Separate map: // System.out.println(areas); List<BigInteger []> branchingOfSeparatedAreas = new LinkedList<>(); for(int area:areas) { PlayerAction pa = new PlayerAction(); // TODO the these two lists are filled but they are never used for anything // this also happens in the other BranchingFactorCalculator classes List<Unit> unitsInArea = new LinkedList<>(); List<Unit> unitsNotInArea = new LinkedList<>(); for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { if (separation[u.getX()][u.getY()]==area) { unitsInArea.add(u); } else { unitsNotInArea.add(u); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); } } } GameState gs3 = gs2.cloneIssue(pa).clone(); BigInteger []n = branchingFactorByResourceUsageFastInternal(gs3,player); // System.out.print("[ "); // for(int i = 0;i<playerResources+1;i++) System.out.print(n[i] + " "); // System.out.println(" ]"); branchingOfSeparatedAreas.add(n); } if (branchingOfSeparatedAreas.isEmpty()) return BigInteger.ONE; // accumulate: BigInteger n[] = branchingOfSeparatedAreas.remove(0); for(BigInteger n2[]:branchingOfSeparatedAreas) { BigInteger n_tmp[] = new BigInteger[playerResources+1]; for(int i = 0;i<playerResources+1;i++) n_tmp[i] = BigInteger.ZERO; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] = n_tmp[i+j].add(n2[i].multiply(n[j])); } } n = n_tmp; } BigInteger branching = BigInteger.ZERO; for(int i = 0;i<playerResources+1;i++) branching = branching.add(n[i]); return branching; } public static BigInteger branchingFactorByResourceUsageFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); BigInteger n[] = branchingFactorByResourceUsageFastInternal(gs,player); BigInteger branching = BigInteger.ZERO; for(int i = 0;i<playerResources+1;i++) branching=branching.add(n[i]); return branching; } public static BigInteger[] branchingFactorByResourceUsageFastInternal(GameState gs, int player) throws Exception { GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); int playerResources = gs2.getPlayer(player).getResources(); List<Unit> unitsThatCannotBeSeparated = new LinkedList<>(); List<Unit> unitsToSeparate = new LinkedList<>(); List<BigInteger []> branchingOfSeparatedUnits = new LinkedList<>(); PlayerAction pa = new PlayerAction(); // Try to identify units that have actions that do not interfere with any other actions: for(Unit u:gs2.getUnits()) { // only consider those units that do not have actions assigned: if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { HashSet<Integer> positionsUsed = new HashSet<>(); int resourcesUsed = 0; // Compute the set of positions required by all the other units (plus resources): for(Unit u2:gs2.getUnits()) { if (u2!=u && u2.getPlayer()==player && gs2.getUnitAction(u2)==null) { List<UnitAction> ual = u2.getUnitActions(gs2); int maxResources = 0; for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u2, pgs2); positionsUsed.addAll(ru.getPositionsUsed()); maxResources = Math.max(maxResources,ru.getResourcesUsed(player)); } resourcesUsed+=maxResources; } } if (DEBUG>=1) System.out.println("- " + u + " --------"); // if (DEBUG>=1) System.out.println(" Positions Used: " + positionsUsed); // if (DEBUG>=1) System.out.println(" Resources Used: " + resourcesUsed); List<UnitAction> ual = u.getUnitActions(gs2); boolean positionConflict = false; BigInteger []unitBranching = new BigInteger[playerResources+1]; for(int i = 0;i<playerResources+1;i++) { unitBranching[i] = BigInteger.ZERO; } for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u, pgs2); int i = ru.getResourcesUsed(player); unitBranching[i] = unitBranching[i].add(BigInteger.ONE); // System.out.println(" " + ua + " -> " + ru.getResourcesUsed(player)); for(Integer pos:ru.getPositionsUsed()) { // if (DEBUG>=1) System.out.println(" " + pos); if (positionsUsed.contains(pos)) positionConflict = true; } } // System.out.println(" branching("+positionConflict+"): " + Arrays.toString(unitBranching)); if (!positionConflict) { unitsToSeparate.add(u); branchingOfSeparatedUnits.add(unitBranching); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); if (DEBUG>=1) System.out.println(" *** Separating unit " + u); } else { unitsThatCannotBeSeparated.add(u); } } } gs2.issue(pa); if (!unitsThatCannotBeSeparated.isEmpty()) { // consider the rest of the board as a single unit: // System.out.println(" recursive call..."); BigInteger n[] = branchingFactorByResourceUsage(gs2,player); // System.out.println(" branching of non separated: " + Arrays.toString(n)); branchingOfSeparatedUnits.add(n); } // accumulate: BigInteger n[] = branchingOfSeparatedUnits.remove(0); // System.out.println("INITIAL " + Arrays.toString(n)); for(BigInteger n2[]:branchingOfSeparatedUnits) { // System.out.println("NEW " + Arrays.toString(n2)); BigInteger n_tmp[] = new BigInteger[playerResources+1]; for(int i = 0;i<playerResources+1;i++) n_tmp[i] = BigInteger.ZERO; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] = n_tmp[i+j].add(n2[i].multiply(n[j])); } } n = n_tmp; // System.out.println("ACCUM " + Arrays.toString(n)); } return n; } }
13,219
41.783172
118
java
MicroRTS
MicroRTS-master/src/ai/BranchingFactorCalculatorDouble.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.PlayerActionGenerator; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.Pair; /** * * @author santi * * This class implements several methods for calculating the branching factor of a given game state: * - branchingFactorUpperBound: this is very fast, but only provides an uppower bound * Basically computing the number of actions each individual unit can execute, and * multiplying these numbers. * - branchingFactor: this is exact, but very slow. It enumerates each move. * - branchingFactorByResourceUsage: same, but returns a vector, with the number of actions * that require different nuber of resources. * - branchingFactorByResourceUsageFast/ * - branchingFactorByResourceUsageSeparatingFast: these are the fastest methods, * the second takes into account that there are groups of units for which we can compute * the branching factor separatedly. * * All the methods (Except for branchingFactorUpperBound) should return the same value */ public class BranchingFactorCalculatorDouble { public static int DEBUG = 0; public static double branchingFactorUpperBound(GameState gs, int player) throws Exception { PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); return pag.getSize(); } public static double branchingFactor(GameState gs, int player) throws Exception { double n = 0; PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); while(pag.getNextAction(-1)!=null) n++; return n; } public static double[] branchingFactorByResourceUsage(GameState gs, int player) throws Exception { double n[] = new double[gs.getPlayer(player).getResources()+1]; PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); PlayerAction pa = null; do{ pa = pag.getNextAction(-1); if (pa!=null) { int r = 0; for(Pair<Unit,UnitAction> tmp:pa.getActions()) { r+=tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState()).getResourcesUsed(player); } // n[(pa.getResourceUsage()).getResourcesUsed(player)]++; n[r]++; } }while(pa!=null); return n; } public static void addFootPrint(int map[][], int ID, int x, int y) { // System.out.println(ID + " -> " + x + "," + y); if (map[x][y]==0) { map[x][y] = ID; } else { // System.out.println("FF"); // propagate this ID with floodfill: int ID_to_remove = map[x][y]; List<Integer> open_x = new LinkedList<>(); List<Integer> open_y = new LinkedList<>(); open_x.add(x); open_y.add(y); while(!open_x.isEmpty()) { x = open_x.remove(0); y = open_y.remove(0); if (map[x][y]==ID) continue; map[x][y] = ID; if (x>0 && map[x-1][y]==ID_to_remove) { open_x.add(0,x-1); open_y.add(0,y); } if (x<map.length-1 && map[x+1][y]==ID_to_remove) { open_x.add(0,x+1); open_y.add(0,y); } if (y>0 && map[x][y-1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y-1); } if (y<map[0].length-1 && map[x][y+1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y+1); } } } } public static double branchingFactorByResourceUsageSeparatingFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); // This matrix helps finding areas that can be separated without causing conflicts: int [][]separation = new int[pgs2.getWidth()][pgs2.getHeight()]; int ID = 1; for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { List<UnitAction> ual = u.getUnitActions(gs2); addFootPrint(separation,ID,u.getX(), u.getY()); for(UnitAction ua:ual) { ResourceUsage ru = (ResourceUsage)ua.resourceUsage(u, gs2.getPhysicalGameState()); for(int pos:ru.getPositionsUsed()) { int x = pos%pgs2.getWidth(); int y = pos/pgs2.getWidth(); addFootPrint(separation,ID,x,y); } } ID++; } } LinkedList<Integer> areas = new LinkedList<>(); for(int i = 0;i<pgs2.getHeight();i++) { for(int j = 0;j<pgs2.getWidth();j++) { if (separation[j][i]!=0 && !areas.contains(separation[j][i])) areas.add(separation[j][i]); // System.out.print((separation[j][i]<10 ? " ":"") + separation[j][i] + " "); } // System.out.println(""); } // Separate map: // System.out.println(areas); List<double []> branchingOfSeparatedAreas = new LinkedList<>(); for(int area:areas) { PlayerAction pa = new PlayerAction(); List<Unit> unitsInArea = new LinkedList<>(); List<Unit> unitsNotInArea = new LinkedList<>(); for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { if (separation[u.getX()][u.getY()]==area) { unitsInArea.add(u); } else { unitsNotInArea.add(u); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); } } } GameState gs3 = gs2.cloneIssue(pa).clone(); double []n = branchingFactorByResourceUsageFastInternal(gs3,player); // System.out.print("[ "); // for(int i = 0;i<playerResources+1;i++) System.out.print(n[i] + " "); // System.out.println(" ]"); branchingOfSeparatedAreas.add(n); } if (branchingOfSeparatedAreas.isEmpty()) return 1; // accumulate: double n[] = branchingOfSeparatedAreas.remove(0); for(double n2[]:branchingOfSeparatedAreas) { double n_tmp[] = new double[playerResources+1]; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] += n2[i]*n[j]; } } n = n_tmp; } double branching = 0; for(int i = 0;i<playerResources+1;i++) branching+=n[i]; return branching; } public static double branchingFactorByResourceUsageFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); double n[] = branchingFactorByResourceUsageFastInternal(gs,player); double branching = 0; for(int i = 0;i<playerResources+1;i++) branching+=n[i]; return branching; } public static double[] branchingFactorByResourceUsageFastInternal(GameState gs, int player) throws Exception { GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); int playerResources = gs2.getPlayer(player).getResources(); List<Unit> unitsThatCannotBeSeparated = new LinkedList<>(); List<Unit> unitsToSeparate = new LinkedList<>(); List<double []> branchingOfSeparatedUnits = new LinkedList<>(); PlayerAction pa = new PlayerAction(); // Try to identify units that have actions that do not interfere with any other actions: for(Unit u:gs2.getUnits()) { // only consider those units that do not have actions assigned: if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { HashSet<Integer> positionsUsed = new HashSet<>(); int resourcesUsed = 0; // Compute the set of positions required by all the other units (plus resources): for(Unit u2:gs2.getUnits()) { if (u2!=u && u2.getPlayer()==player && gs2.getUnitAction(u2)==null) { List<UnitAction> ual = u2.getUnitActions(gs2); int maxResources = 0; for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u2, pgs2); positionsUsed.addAll(ru.getPositionsUsed()); maxResources = Math.max(maxResources,ru.getResourcesUsed(player)); } resourcesUsed+=maxResources; } } if (DEBUG>=1) System.out.println("- " + u + " --------"); // if (DEBUG>=1) System.out.println(" Positions Used: " + positionsUsed); // if (DEBUG>=1) System.out.println(" Resources Used: " + resourcesUsed); List<UnitAction> ual = u.getUnitActions(gs2); boolean positionConflict = false; double []unitBranching = new double[playerResources+1]; for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u, pgs2); unitBranching[ru.getResourcesUsed(player)]++; // System.out.println(" " + ua + " -> " + ru.getResourcesUsed(player)); for(Integer pos:ru.getPositionsUsed()) { // if (DEBUG>=1) System.out.println(" " + pos); if (positionsUsed.contains(pos)) positionConflict = true; } } // System.out.println(" branching("+positionConflict+"): " + Arrays.toString(unitBranching)); if (!positionConflict) { unitsToSeparate.add(u); branchingOfSeparatedUnits.add(unitBranching); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); if (DEBUG>=1) System.out.println(" *** Separating unit " + u); } else { unitsThatCannotBeSeparated.add(u); } } } gs2.issue(pa); if (!unitsThatCannotBeSeparated.isEmpty()) { // consider the rest of the board as a single unit: // System.out.println(" recursive call..."); double n[] = branchingFactorByResourceUsage(gs2,player); // System.out.println(" branching of non separated: " + Arrays.toString(n)); branchingOfSeparatedUnits.add(n); } // accumulate: double n[] = branchingOfSeparatedUnits.remove(0); // System.out.println("INITIAL " + Arrays.toString(n)); for(double n2[]:branchingOfSeparatedUnits) { // System.out.println("NEW " + Arrays.toString(n2)); double n_tmp[] = new double[playerResources+1]; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] += n2[i]*n[j]; } } n = n_tmp; // System.out.println("ACCUM " + Arrays.toString(n)); } return n; } }
12,286
40.231544
114
java
MicroRTS
MicroRTS-master/src/ai/BranchingFactorCalculatorLong.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.PlayerActionGenerator; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.Pair; /** * * @author santi * * This class implements several methods for calculating the branching factor of a given game state: * - branchingFactorUpperBound: this is very fast, but only provides an uppower bound * Basically computing the number of actions each individual unit can execute, and * multiplying these numbers. * - branchingFactor: this is exact, but very slow. It enumerates each move. * - branchingFactorByResourceUsage: same, but returns a vector, with the number of actions * that require different nuber of resources. * - branchingFactorByResourceUsageFast/ * - branchingFactorByResourceUsageSeparatingFast: these are the fastest methods, * the second takes into account that there are groups of units for which we can compute * the branching factor separatedly. * * All the methods (Except for branchingFactorUpperBound) should return the same value */ public class BranchingFactorCalculatorLong { public static int DEBUG = 0; public static long branchingFactorUpperBound(GameState gs, int player) throws Exception { PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); return pag.getSize(); } public static long branchingFactor(GameState gs, int player) throws Exception { long n = 0; PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); while(pag.getNextAction(-1)!=null) n++; return n; } public static long[] branchingFactorByResourceUsage(GameState gs, int player) throws Exception { long n[] = new long[gs.getPlayer(player).getResources()+1]; PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); PlayerAction pa = null; do{ pa = pag.getNextAction(-1); if (pa!=null) { int r = 0; for(Pair<Unit,UnitAction> tmp:pa.getActions()) { r+=tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState()).getResourcesUsed(player); } // n[(pa.getResourceUsage()).getResourcesUsed(player)]++; n[r]++; } }while(pa!=null); return n; } public static void addFootPrint(int map[][], int ID, int x, int y) { // System.out.println(ID + " -> " + x + "," + y); if (map[x][y]==0) { map[x][y] = ID; } else { // System.out.println("FF"); // propagate this ID with floodfill: int ID_to_remove = map[x][y]; List<Integer> open_x = new LinkedList<>(); List<Integer> open_y = new LinkedList<>(); open_x.add(x); open_y.add(y); while(!open_x.isEmpty()) { x = open_x.remove(0); y = open_y.remove(0); if (map[x][y]==ID) continue; map[x][y] = ID; if (x>0 && map[x-1][y]==ID_to_remove) { open_x.add(0,x-1); open_y.add(0,y); } if (x<map.length-1 && map[x+1][y]==ID_to_remove) { open_x.add(0,x+1); open_y.add(0,y); } if (y>0 && map[x][y-1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y-1); } if (y<map[0].length-1 && map[x][y+1]==ID_to_remove) { open_x.add(0,x); open_y.add(0,y+1); } } } } public static long branchingFactorByResourceUsageSeparatingFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); // This matrix helps finding areas that can be separated without causing conflicts: int [][]separation = new int[pgs2.getWidth()][pgs2.getHeight()]; int ID = 1; for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { List<UnitAction> ual = u.getUnitActions(gs2); addFootPrint(separation,ID,u.getX(), u.getY()); for(UnitAction ua:ual) { ResourceUsage ru = (ResourceUsage)ua.resourceUsage(u, gs2.getPhysicalGameState()); for(int pos:ru.getPositionsUsed()) { int x = pos%pgs2.getWidth(); int y = pos/pgs2.getWidth(); addFootPrint(separation,ID,x,y); } } ID++; } } LinkedList<Integer> areas = new LinkedList<>(); for(int i = 0;i<pgs2.getHeight();i++) { for(int j = 0;j<pgs2.getWidth();j++) { if (separation[j][i]!=0 && !areas.contains(separation[j][i])) areas.add(separation[j][i]); // System.out.print((separation[j][i]<10 ? " ":"") + separation[j][i] + " "); } // System.out.println(""); } // Separate map: // System.out.println(areas); List<long []> branchingOfSeparatedAreas = new LinkedList<>(); for(int area:areas) { PlayerAction pa = new PlayerAction(); List<Unit> unitsInArea = new LinkedList<>(); List<Unit> unitsNotInArea = new LinkedList<>(); for(Unit u:gs2.getUnits()) { if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { if (separation[u.getX()][u.getY()]==area) { unitsInArea.add(u); } else { unitsNotInArea.add(u); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); } } } GameState gs3 = gs2.cloneIssue(pa).clone(); long []n = branchingFactorByResourceUsageFastInternal(gs3,player); // System.out.print("[ "); // for(int i = 0;i<playerResources+1;i++) System.out.print(n[i] + " "); // System.out.println(" ]"); branchingOfSeparatedAreas.add(n); } if (branchingOfSeparatedAreas.isEmpty()) return 1; // accumulate: long n[] = branchingOfSeparatedAreas.remove(0); for(long n2[]:branchingOfSeparatedAreas) { long n_tmp[] = new long[playerResources+1]; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] += n2[i]*n[j]; } } n = n_tmp; } long branching = 0; for(int i = 0;i<playerResources+1;i++) branching+=n[i]; return branching; } public static long branchingFactorByResourceUsageFast(GameState gs, int player) throws Exception { int playerResources = gs.getPlayer(player).getResources(); long n[] = branchingFactorByResourceUsageFastInternal(gs,player); long branching = 0; for(int i = 0;i<playerResources+1;i++) branching+=n[i]; return branching; } public static long[] branchingFactorByResourceUsageFastInternal(GameState gs, int player) throws Exception { GameState gs2 = gs.clone(); PhysicalGameState pgs2 = gs2.getPhysicalGameState(); int playerResources = gs2.getPlayer(player).getResources(); List<Unit> unitsThatCannotBeSeparated = new LinkedList<>(); List<Unit> unitsToSeparate = new LinkedList<>(); List<long []> branchingOfSeparatedUnits = new LinkedList<>(); PlayerAction pa = new PlayerAction(); // Try to identify units that have actions that do not interfere with any other actions: for(Unit u:gs2.getUnits()) { // only consider those units that do not have actions assigned: if (u.getPlayer()==player && gs2.getUnitAction(u)==null) { HashSet<Integer> positionsUsed = new HashSet<>(); int resourcesUsed = 0; // Compute the set of positions required by all the other units (plus resources): for(Unit u2:gs2.getUnits()) { if (u2!=u && u2.getPlayer()==player && gs2.getUnitAction(u2)==null) { List<UnitAction> ual = u2.getUnitActions(gs2); int maxResources = 0; for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u2, pgs2); positionsUsed.addAll(ru.getPositionsUsed()); maxResources = Math.max(maxResources,ru.getResourcesUsed(player)); } resourcesUsed+=maxResources; } } if (DEBUG>=1) System.out.println("- " + u + " --------"); // if (DEBUG>=1) System.out.println(" Positions Used: " + positionsUsed); // if (DEBUG>=1) System.out.println(" Resources Used: " + resourcesUsed); List<UnitAction> ual = u.getUnitActions(gs2); boolean positionConflict = false; long []unitBranching = new long[playerResources+1]; for(UnitAction ua:ual) { ResourceUsage ru = ua.resourceUsage(u, pgs2); unitBranching[ru.getResourcesUsed(player)]++; // System.out.println(" " + ua + " -> " + ru.getResourcesUsed(player)); for(Integer pos:ru.getPositionsUsed()) { // if (DEBUG>=1) System.out.println(" " + pos); if (positionsUsed.contains(pos)) positionConflict = true; } } // System.out.println(" branching("+positionConflict+"): " + Arrays.toString(unitBranching)); if (!positionConflict) { unitsToSeparate.add(u); branchingOfSeparatedUnits.add(unitBranching); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE)); if (DEBUG>=1) System.out.println(" *** Separating unit " + u); } else { unitsThatCannotBeSeparated.add(u); } } } gs2.issue(pa); if (!unitsThatCannotBeSeparated.isEmpty()) { // consider the rest of the board as a single unit: // System.out.println(" recursive call..."); long n[] = branchingFactorByResourceUsage(gs2,player); // System.out.println(" branching of non separated: " + Arrays.toString(n)); branchingOfSeparatedUnits.add(n); } // accumulate: long n[] = branchingOfSeparatedUnits.remove(0); // System.out.println("INITIAL " + Arrays.toString(n)); for(long n2[]:branchingOfSeparatedUnits) { // System.out.println("NEW " + Arrays.toString(n2)); long n_tmp[] = new long[playerResources+1]; for(int i = 0;i<playerResources+1;i++) { for(int j = 0;j<(playerResources-i)+1;j++) { n_tmp[i+j] += n2[i]*n[j]; } } n = n_tmp; // System.out.println("ACCUM " + Arrays.toString(n)); } return n; } }
12,232
40.050336
112
java
MicroRTS
MicroRTS-master/src/ai/PassiveAI.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.List; import rts.*; import rts.units.UnitTypeTable; /** * * @author santi */ public class PassiveAI extends AI { public PassiveAI(UnitTypeTable utt) { } public PassiveAI() { } @Override public void reset() { } @Override public AI clone() { return new PassiveAI(); } @Override public PlayerAction getAction(int player, GameState gs) { PlayerAction pa = new PlayerAction(); pa.fillWithNones(gs, player, 10); return pa; } @Override public List<ParameterSpecification> getParameters() { return new ArrayList<>(); } }
896
15.611111
61
java
MicroRTS
MicroRTS-master/src/ai/RandomAI.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.List; import rts.*; import rts.units.UnitTypeTable; /** * * @author santi */ public class RandomAI extends AI { public RandomAI(UnitTypeTable utt) { } public RandomAI() { } @Override public void reset() { } @Override public AI clone() { return new RandomAI(); } @Override public PlayerAction getAction(int player, GameState gs) { try { if (!gs.canExecuteAnyAction(player)) return new PlayerAction(); PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); return pag.getRandom(); }catch(Exception e) { // The only way the player action generator returns an exception is if there are no units that // can execute actions, in this case, just return an empty action: // However, this should never happen, since we are checking for this at the beginning return new PlayerAction(); } } @Override public List<ParameterSpecification> getParameters() { return new ArrayList<>(); } }
1,348
21.483333
106
java
MicroRTS
MicroRTS-master/src/ai/RandomBiasedAI.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.List; import java.util.Random; import rts.*; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Sampler; /** * * @author santi * * This AI is similar to the RandomBiasedAI, but instead of discarding "move" actions when there is an * attack available, it simply lowers the probability of a move. * */ public class RandomBiasedAI extends AI { static final double REGULAR_ACTION_WEIGHT = 1; static final double BIASED_ACTION_WEIGHT = 5; Random r = new Random(); public RandomBiasedAI(UnitTypeTable utt) { } public RandomBiasedAI() { } @Override public void reset() { } @Override public AI clone() { return new RandomBiasedAI(); } @Override public PlayerAction getAction(int player, GameState gs) { // attack, harvest and return have 5 times the probability of other actions PhysicalGameState pgs = gs.getPhysicalGameState(); PlayerAction pa = new PlayerAction(); if (!gs.canExecuteAnyAction(player)) return pa; // Generate the reserved resources: for(Unit u:pgs.getUnits()) { UnitActionAssignment uaa = gs.getActionAssignment(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); pa.getResourceUsage().merge(ru); } } for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { if (gs.getActionAssignment(u)==null) { List<UnitAction> l = u.getUnitActions(gs); UnitAction none = null; int nActions = l.size(); double []distribution = new double[nActions]; // Implement "bias": int i = 0; for(UnitAction a:l) { if (a.getType()==UnitAction.TYPE_NONE) none = a; if (a.getType()==UnitAction.TYPE_ATTACK_LOCATION || a.getType()==UnitAction.TYPE_HARVEST || a.getType()==UnitAction.TYPE_RETURN) { distribution[i]=BIASED_ACTION_WEIGHT; } else { distribution[i]=REGULAR_ACTION_WEIGHT; } i++; } try { UnitAction ua = l.get(Sampler.weighted(distribution)); if (ua.resourceUsage(u, pgs).consistentWith(pa.getResourceUsage(), gs)) { ResourceUsage ru = ua.resourceUsage(u, pgs); pa.getResourceUsage().merge(ru); pa.addUnitAction(u, ua); } else { pa.addUnitAction(u, none); } } catch (Exception ex) { ex.printStackTrace(); pa.addUnitAction(u, none); } } } } return pa; } @Override public List<ParameterSpecification> getParameters() { return new ArrayList<>(); } }
3,559
29.42735
102
java
MicroRTS
MicroRTS-master/src/ai/RandomBiasedSingleUnitAI.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.List; import java.util.Random; import rts.*; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Sampler; /** * * @author santi * * This AI is similar to the RandomBiasedAI, but instead of discarding "move" actions when there is an * attack available, it simply lowers the probability of a move. * */ public class RandomBiasedSingleUnitAI extends AI { static final double REGULAR_ACTION_WEIGHT = 1; static final double BIASED_ACTION_WEIGHT = 5; Random r = new Random(); public RandomBiasedSingleUnitAI(UnitTypeTable utt) { } public RandomBiasedSingleUnitAI() { } @Override public void reset() { } @Override public AI clone() { return new RandomBiasedSingleUnitAI(); } @Override public PlayerAction getAction(int player, GameState gs) { // attack, harvest and return have 5 times the probability of other actions PhysicalGameState pgs = gs.getPhysicalGameState(); PlayerAction pa = new PlayerAction(); if (!gs.canExecuteAnyAction(player)) return pa; // Generate the reserved resources: for(Unit u:pgs.getUnits()) { UnitActionAssignment uaa = gs.getActionAssignment(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); pa.getResourceUsage().merge(ru); } } List<Unit> unitsReadyForAction = new ArrayList<>(); for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { if (gs.getActionAssignment(u)==null) { unitsReadyForAction.add(u); } } } if (!unitsReadyForAction.isEmpty()) { Unit u = unitsReadyForAction.get(r.nextInt(unitsReadyForAction.size())); List<UnitAction> l = u.getUnitActions(gs); UnitAction none = null; int nActions = l.size(); double []distribution = new double[nActions]; // Implement "bias": int i = 0; for(UnitAction a:l) { if (a.getType()==UnitAction.TYPE_NONE) none = a; if (a.getType()==UnitAction.TYPE_ATTACK_LOCATION || a.getType()==UnitAction.TYPE_HARVEST || a.getType()==UnitAction.TYPE_RETURN) { distribution[i]=BIASED_ACTION_WEIGHT; } else { distribution[i]=REGULAR_ACTION_WEIGHT; } i++; } try { UnitAction ua = l.get(Sampler.weighted(distribution)); if (ua.resourceUsage(u, pgs).consistentWith(pa.getResourceUsage(), gs)) { ResourceUsage ru = ua.resourceUsage(u, pgs); pa.getResourceUsage().merge(ru); pa.addUnitAction(u, ua); } else { pa.addUnitAction(u, none); } } catch (Exception ex) { ex.printStackTrace(); pa.addUnitAction(u, none); } } pa.fillWithNones(gs, player, 10); return pa; } @Override public List<ParameterSpecification> getParameters() { return new ArrayList<>(); } }
3,644
28.16
102
java
MicroRTS
MicroRTS-master/src/ai/abstraction/AbstractAction.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.BFSPathFinding; import ai.abstraction.pathfinding.FloodFillPathFinding; import ai.abstraction.pathfinding.GreedyPathFinding; import ai.abstraction.pathfinding.PathFinding; import org.jdom.Element; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public abstract class AbstractAction { Unit unit; public AbstractAction(Unit a_unit) { unit = a_unit; } public Unit getUnit() { return unit; } public void setUnit(Unit u) { unit = u; } public abstract boolean completed(GameState pgs); public UnitAction execute(GameState pgs){ return execute(pgs,null); } public abstract void toxml(XMLWriter w); public static AbstractAction fromXML(Element e, PhysicalGameState gs, UnitTypeTable utt) { PathFinding pf = null; String pfString = e.getAttributeValue("pathfinding"); if (pfString != null) { if (pfString.equals("AStarPathFinding")) pf = new AStarPathFinding(); if (pfString.equals("BFSPathFinding")) pf = new BFSPathFinding(); if (pfString.equals("FloodFillPathFinding")) pf = new FloodFillPathFinding(); if (pfString.equals("GreedyPathFinding")) pf = new GreedyPathFinding(); } switch (e.getName()) { case "Attack": return new Attack(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID"))), gs.getUnit(Long.parseLong(e.getAttributeValue("target"))), pf); case "Build": return new Build(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID"))), utt.getUnitType(e.getAttributeValue("type")), Integer.parseInt(e.getAttributeValue("x")), Integer.parseInt(e.getAttributeValue("y")), pf); case "Harvest": return new Harvest(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID"))), gs.getUnit(Long.parseLong(e.getAttributeValue("target"))), gs.getUnit(Long.parseLong(e.getAttributeValue("base"))), pf); case "Idle": return new Idle(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID")))); case "Move": return new Move(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID"))), Integer.parseInt(e.getAttributeValue("x")), Integer.parseInt(e.getAttributeValue("y")), pf); case "Train": return new Train(gs.getUnit(Long.parseLong(e.getAttributeValue("unitID"))), utt.getUnitType(e.getAttributeValue("type"))); default: return null; } } public abstract UnitAction execute(GameState pgs, ResourceUsage ru); }
3,330
32.646465
93
java
MicroRTS
MicroRTS-master/src/ai/abstraction/AbstractTrace.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import org.jdom.Element; import rts.units.Unit; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class AbstractTrace { UnitTypeTable utt; List<AbstractTraceEntry> entries = new LinkedList<>(); protected HashMap<Unit,AbstractAction> currentActions = new LinkedHashMap<>(); public AbstractTrace(UnitTypeTable a_utt) { utt = a_utt; } public List<AbstractTraceEntry> getEntries() { return entries; } public UnitTypeTable getUnitTypeTable() { return utt; } public int getLength() { return entries.get(entries.size()-1).getTime(); } public void addEntry(AbstractTraceEntry te) { entries.add(te); } public AbstractAction getCurrentAbstractAction(Unit u) { return currentActions.get(u); } public AbstractAction setCurrentAbstractAction(Unit u, AbstractAction aa) { return currentActions.put(u, aa); } public void toxml(XMLWriter w) { w.tag(this.getClass().getName()); utt.toxml(w); w.tag("entries"); for(AbstractTraceEntry te:entries) te.toxml(w); w.tag("/entries"); w.tag("/" + this.getClass().getName()); } public AbstractTrace(Element e) throws Exception { utt = UnitTypeTable.fromXML(e.getChild(UnitTypeTable.class.getName())); Element entries_e = e.getChild("entries"); for(Object o:entries_e.getChildren()) { Element entry_e = (Element)o; entries.add(new AbstractTraceEntry(entry_e, utt)); } } // this loads a trace ignoring the UTT specified in the trace: public AbstractTrace(Element e, UnitTypeTable a_utt) throws Exception { utt = a_utt; Element entries_e = e.getChild("entries"); for(Object o:entries_e.getChildren()) { Element entry_e = (Element)o; entries.add(new AbstractTraceEntry(entry_e, utt)); } } }
2,326
24.855556
82
java
MicroRTS
MicroRTS-master/src/ai/abstraction/AbstractTraceEntry.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import java.util.LinkedList; import java.util.List; import org.jdom.Element; import rts.PhysicalGameState; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * * @author santi */ public class AbstractTraceEntry { int time; PhysicalGameState pgs; List<Pair<Unit,AbstractAction>> actions = new LinkedList<>(); public AbstractTraceEntry(PhysicalGameState a_pgs, int a_time) { pgs = a_pgs; time = a_time; } public void addAbstractAction(Unit u, AbstractAction a) { actions.add(new Pair<>(u,a)); } public void addAbstractActionIfNew(Unit u, AbstractAction a, AbstractTrace trace) { if (!a.equals(trace.getCurrentAbstractAction(u))) { addAbstractAction(u, a); trace.setCurrentAbstractAction(u, a); } else if (a instanceof Train) { // train actions do get repeated and need to be duplicated: addAbstractAction(u, a); trace.setCurrentAbstractAction(u, a); } } public PhysicalGameState getPhysicalGameState() { return pgs; } public List<Pair<Unit,AbstractAction>> getActions() { return actions; } public int getTime() { return time; } public void toxml(XMLWriter w) { w.tagWithAttributes(this.getClass().getName(), "time = \"" + time + "\""); pgs.toxml(w); w.tag("abstractactions"); for(Pair<Unit,AbstractAction> ua:actions) { w.tagWithAttributes("abstractaction", "unitID=\"" + ua.m_a.getID() + "\""); ua.m_b.toxml(w); w.tag("/abstractaction"); } w.tag("/abstractactions"); w.tag("/" + this.getClass().getName()); } public AbstractTraceEntry(Element e, UnitTypeTable utt) throws Exception { Element actions_e = e.getChild("abstractactions"); time = Integer.parseInt(e.getAttributeValue("time")); Element pgs_e = e.getChild(PhysicalGameState.class.getName()); pgs = PhysicalGameState.fromXML(pgs_e, utt); for(Object o:actions_e.getChildren()) { Element action_e = (Element)o; long ID = Long.parseLong(action_e.getAttributeValue("unitID")); AbstractAction a = AbstractAction.fromXML(action_e.getChild("abstractaction"), pgs, utt); Unit u = pgs.getUnit(ID); actions.add(new Pair<>(u,a)); } } }
2,675
29.067416
101
java
MicroRTS
MicroRTS-master/src/ai/abstraction/AbstractionLayerAI.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.PathFinding; import ai.core.AIWithComputationBudget; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import rts.*; import rts.units.Unit; import rts.units.UnitType; import util.Pair; /** * * @author santi */ public abstract class AbstractionLayerAI extends AIWithComputationBudget { // set this to true, if you believe there is a bug, and want to verify that actions // being generated are actually possible before sending to the game. public static boolean VERIFY_ACTION_CORRECTNESS = false; // functionality that this abstraction layer offers: // 1) You can forget about issuing actions to all units, just issue the ones you want, the rest are set to NONE automatically // 2) High level actions (using A*): // - move(x,y) // - train(type) // - build(type,x,y) // - harvest(target) // - attack(target) protected HashMap<Unit, AbstractAction> actions = new LinkedHashMap<>(); protected PathFinding pf; // In case the GameState is cloned, and the Unit pointers in the "actions" map change, this variable // saves a pointer to the previous GameState, if it's different than the current one, then we need to find a mapping // between the old units and the new ones protected GameState lastGameState; public AbstractionLayerAI(PathFinding a_pf) { super(-1, -1); pf = a_pf; } public AbstractionLayerAI(PathFinding a_pf, int timebudget, int cyclesbudget) { super(timebudget, cyclesbudget); pf = a_pf; } public void reset() { actions.clear(); } public PlayerAction translateActions(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); PlayerAction pa = new PlayerAction(); List<Pair<Unit, UnitAction>> desires = new ArrayList<>(); lastGameState = gs; // Execute abstract actions: List<Unit> toDelete = new ArrayList<>(); ResourceUsage ru = new ResourceUsage(); for (AbstractAction aa : actions.values()) { if (!pgs.getUnits().contains(aa.unit)) { // The unit is dead: toDelete.add(aa.unit); } else { if (aa.completed(gs)) { // the action is complete: toDelete.add(aa.unit); } else { if (gs.getActionAssignment(aa.unit) == null) { UnitAction ua = aa.execute(gs, ru); if (ua != null) { if (VERIFY_ACTION_CORRECTNESS) { // verify that the action is actually feasible: List<UnitAction> ual = aa.unit.getUnitActions(gs); if (ual.contains(ua)) { desires.add(new Pair<>(aa.unit, ua)); } } else { desires.add(new Pair<>(aa.unit, ua)); } ru.merge(ua.resourceUsage(aa.unit, pgs)); } } } } } for (Unit u : toDelete) { actions.remove(u); } // compose desires: ResourceUsage r = gs.getResourceUsage(); pa.setResourceUsage(r); for (Pair<Unit, UnitAction> desire : desires) { ResourceUsage r2 = desire.m_b.resourceUsage(desire.m_a, pgs); if (pa.consistentWith(r2, gs)) { pa.addUnitAction(desire.m_a, desire.m_b); pa.getResourceUsage().merge(r2); } } pa.fillWithNones(gs, player, 10); return pa; } public AbstractAction getAbstractAction(Unit u) { return actions.get(u); } public void move(Unit u, int x, int y) { actions.put(u, new Move(u, x, y, pf)); } public void train(Unit u, UnitType unit_type) { actions.put(u, new Train(u, unit_type)); } public void build(Unit u, UnitType unit_type, int x, int y) { actions.put(u, new Build(u, unit_type, x, y, pf)); } public void harvest(Unit u, Unit target, Unit base) { actions.put(u, new Harvest(u, target, base, pf)); } public void attack(Unit u, Unit target) { actions.put(u, new Attack(u, target, pf)); } public void idle(Unit u) { actions.put(u, new Idle(u)); } public int findBuildingPosition(List<Integer> reserved, int desiredX, int desiredY, Player p, PhysicalGameState pgs) { boolean[][] free = pgs.getAllFree(); int x, y; /* System.out.println("-" + desiredX + "," + desiredY + "-------------------"); for(int i = 0;i<free[0].length;i++) { for(int j = 0;j<free.length;j++) { System.out.print(free[j][i] + "\t"); } System.out.println(""); } */ for (int l = 1; l < Math.max(pgs.getHeight(), pgs.getWidth()); l++) { for (int side = 0; side < 4; side++) { switch (side) { case 0://up y = desiredY - l; if (y < 0) { continue; } for (int dx = -l; dx <= l; dx++) { x = desiredX + dx; if (x < 0 || x >= pgs.getWidth()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 1://right x = desiredX + l; if (x >= pgs.getWidth()) { continue; } for (int dy = -l; dy <= l; dy++) { y = desiredY + dy; if (y < 0 || y >= pgs.getHeight()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 2://down y = desiredY + l; if (y >= pgs.getHeight()) { continue; } for (int dx = -l; dx <= l; dx++) { x = desiredX + dx; if (x < 0 || x >= pgs.getWidth()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 3://left x = desiredX - l; if (x < 0) { continue; } for (int dy = -l; dy <= l; dy++) { y = desiredY + dy; if (y < 0 || y >= pgs.getHeight()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; } } } return -1; } public boolean buildIfNotAlreadyBuilding(Unit u, UnitType type, int desiredX, int desiredY, List<Integer> reservedPositions, Player p, PhysicalGameState pgs) { AbstractAction action = getAbstractAction(u); // System.out.println("buildIfNotAlreadyBuilding: action = " + action); if (!(action instanceof Build) || ((Build) action).type != type) { int pos = findBuildingPosition(reservedPositions, desiredX, desiredY, p, pgs); // System.out.println("pos = " + (pos % pgs.getWidth()) + "," + (pos / pgs.getWidth())); build(u, type, pos % pgs.getWidth(), pos / pgs.getWidth()); reservedPositions.add(pos); return true; } else { return false; } } @Override public String toString() { return getClass().getSimpleName() + "(" + pf + ")"; } public PathFinding getPathFinding() { return pf; } public void setPathFinding(PathFinding a_pf) { pf = a_pf; } }
9,312
34.819231
163
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Attack.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.XMLWriter; /** * * @author santi */ public class Attack extends AbstractAction { Unit target; PathFinding pf; public Attack(Unit u, Unit a_target, PathFinding a_pf) { super(u); target = a_target; pf = a_pf; } public boolean completed(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); return !pgs.getUnits().contains(target); } public boolean equals(Object o) { if (!(o instanceof Attack)) return false; Attack a = (Attack)o; return target.getID() == a.target.getID() && pf.getClass() == a.pf.getClass(); } public void toxml(XMLWriter w) { w.tagWithAttributes("Attack","unitID=\""+unit.getID()+"\" target=\""+target.getID()+"\" pathfinding=\""+pf.getClass().getSimpleName()+"\""); w.tag("/Attack"); } public UnitAction execute(GameState gs, ResourceUsage ru) { int dx = target.getX()-unit.getX(); int dy = target.getY()-unit.getY(); double d = Math.sqrt(dx*dx+dy*dy); if (d<=unit.getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION,target.getX(),target.getY()); } else { // move towards the unit: // System.out.println("AStarAttak returns: " + move); UnitAction move = pf.findPathToPositionInRange(unit, target.getX()+target.getY()*gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); if (move!=null && gs.isUnitActionAllowed(unit, move)) return move; return null; } } }
1,952
28.149254
162
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Build.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import util.XMLWriter; /** * * @author santi */ public class Build extends AbstractAction { UnitType type; int x,y; PathFinding pf; public Build(Unit u, UnitType a_type, int a_x, int a_y, PathFinding a_pf) { super(u); type = a_type; x = a_x; y = a_y; pf = a_pf; } public boolean completed(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit u = pgs.getUnitAt(x, y); return u != null; } public boolean equals(Object o) { if (!(o instanceof Build)) return false; Build a = (Build)o; return type == a.type && x == a.x && y == a.y && pf.getClass() == a.pf.getClass(); } public void toxml(XMLWriter w) { w.tagWithAttributes("Build","unitID=\""+unit.getID()+"\" type=\""+type.name+"\" x=\""+x+"\" y=\""+y+"\" pathfinding=\""+pf.getClass().getSimpleName()+"\""); w.tag("/Build"); } public UnitAction execute(GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); // System.out.println("findPathToAdjacentPosition to " + unit.getX() + "," + unit.getY() + " from Build: (" + x + "," + y + ")"); UnitAction move = pf.findPathToAdjacentPosition(unit, x+y*pgs.getWidth(), gs, ru); // System.out.println("Move: " + move); if (move!=null) { if (gs.isUnitActionAllowed(unit, move)) return move; return null; } // build: UnitAction ua = null; if (x == unit.getX() && y == unit.getY()-1) ua = new UnitAction(UnitAction.TYPE_PRODUCE,UnitAction.DIRECTION_UP,type); if (x == unit.getX()+1 && y == unit.getY()) ua = new UnitAction(UnitAction.TYPE_PRODUCE,UnitAction.DIRECTION_RIGHT,type); if (x == unit.getX() && y == unit.getY()+1) ua = new UnitAction(UnitAction.TYPE_PRODUCE,UnitAction.DIRECTION_DOWN,type); if (x == unit.getX()-1 && y == unit.getY()) ua = new UnitAction(UnitAction.TYPE_PRODUCE,UnitAction.DIRECTION_LEFT,type); if (ua!=null && gs.isUnitActionAllowed(unit, ua)) return ua; // System.err.println("Build.execute: something weird just happened " + unit + " builds at " + x + "," + y); return null; } }
2,685
32.575
164
java
MicroRTS
MicroRTS-master/src/ai/abstraction/EMRDeterministico.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author rubensolv */ public class EMRDeterministico extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType lightType; UnitType heavyType; int nWorkerBase = 3 * 2; // If we have any unit for attack: send it to attack to the nearest enemy unit // If we have a base: train worker until we have 6 workers per base. The 6ª unit send to build a new base. // If we have a barracks: train light, Ranged and Heavy in order // If we have a worker: go to resources closest, build barracks, build new base closest harvest resources public EMRDeterministico(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public EMRDeterministico(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); } @Override public PlayerAction getAction(int player, GameState gs) throws Exception { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of workers: List<Unit> workers = new ArrayList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player && u.getType() == workerType) { workers.add(u); } } workersBehavior(workers, p, pgs); // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } return translateActions(player, gs); } @Override public AI clone() { return new EconomyMilitaryRush(utt, pf); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } //calculo numero de bases e barracks int nBases = 0; int nBarracks = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nBases++; } else if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nBarracks++; } } int qtdWorkLim; if(nBarracks == 0){ qtdWorkLim = 4; }else{ qtdWorkLim = nWorkerBase * nBases; } if (nworkers < qtdWorkLim && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { int nLight = 0; int nRanged = 0; int nHeavy = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == lightType && u2.getPlayer() == p.getID()) { nLight++; } if (u2.getType() == rangedType && u2.getPlayer() == p.getID()) { nRanged++; } if (u2.getType() == heavyType && u2.getPlayer() == p.getID()) { nHeavy++; } } int sum = nLight + nHeavy + nRanged; if (sum%3 == 0 && p.getResources() >= lightType.cost) { train(u, lightType); } else if (sum%3 == 1 && p.getResources() >= rangedType.cost) { train(u, rangedType); } else if (sum%3 == 2 && p.getResources() >= heavyType.cost) { train(u, heavyType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; int nArmyUnits = 0; List<Unit> freeWorkers = new ArrayList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if ( (u2.getType() == lightType || u2.getType() == rangedType || u2.getType() == heavyType) && u2.getPlayer() == p.getID()) { nArmyUnits++; } } List<Integer> reservedPositions = new ArrayList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } }else if (nbarracks > 0 && !freeWorkers.isEmpty() && nArmyUnits > 2){ // build a new barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } } if (nbarracks != 0) { List<Unit> otherResources = new ArrayList<>(otherResourcePoint(p, pgs)); if (!otherResources.isEmpty()) { if (!freeWorkers.isEmpty()) { if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, otherResources.get(0).getX()+1, otherResources.get(0).getY()+1, reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } } } // harvest with all the free workers: harvestWorkers(freeWorkers, p, pgs); } protected List<Unit> otherResourcePoint(Player p, PhysicalGameState pgs) { List<Unit> bases = getMyBases(p, pgs); Set<Unit> myResources = new HashSet<>(); Set<Unit> otherResources = new HashSet<>(); for (Unit base : bases) { List<Unit> closestUnits = new ArrayList<>(pgs.getUnitsAround(base.getX(), base.getY(), 10)); for (Unit closestUnit : closestUnits) { if (closestUnit.getType().isResource) { myResources.add(closestUnit); } } } for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { if (!myResources.contains(u2)) { otherResources.add(u2); } } } return new ArrayList<>(otherResources); } protected List<Unit> getMyBases(Player p, PhysicalGameState pgs) { List<Unit> bases = new ArrayList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { bases.add(u2); } } return bases; } protected void harvestWorkers(List<Unit> freeWorkers, Player p, PhysicalGameState pgs) { for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } }
12,443
33.470914
154
java
MicroRTS
MicroRTS-master/src/ai/abstraction/EconomyMilitaryRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author rubensolv */ public class EconomyMilitaryRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType lightType; UnitType heavyType; int nWorkerBase = 4 * 2; // If we have any unit for attack: send it to attack to the nearest enemy unit // If we have a base: train worker until we have 8 workers per base. The 8ª unit send to build a new base. // If we have a barracks: train light, Ranged and Heavy in order // If we have a worker: go to resources closest, build barracks, build new base closest harvest resources public EconomyMilitaryRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public EconomyMilitaryRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); } @Override public PlayerAction getAction(int player, GameState gs) throws Exception { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of workers: List<Unit> workers = new ArrayList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player && u.getType() == workerType) { workers.add(u); } } workersBehavior(workers, p, pgs); // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } return translateActions(player, gs); } @Override public AI clone() { return new EconomyMilitaryRush(utt, pf); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } int nBases = 0; int nBarracks = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nBases++; } else if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nBarracks++; } } int qtdWorkLim; if(nBarracks == 0){ qtdWorkLim = 4; }else{ qtdWorkLim = nWorkerBase * nBases; } if (nworkers < qtdWorkLim && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { int nLight = 0; int nRanged = 0; int nHeavy = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == lightType && u.getPlayer() == p.getID()) { nLight++; } if (u2.getType() == rangedType && u.getPlayer() == p.getID()) { nRanged++; } if (u2.getType() == heavyType && u.getPlayer() == p.getID()) { nHeavy++; } } if (nLight == 0 && p.getResources() >= lightType.cost) { train(u, lightType); } else if (nRanged == 0 && p.getResources() >= rangedType.cost) { train(u, rangedType); } else if (nHeavy == 0 && p.getResources() >= heavyType.cost) { train(u, heavyType); } if (nLight != 0 && nRanged != 0 && nHeavy != 0) { int number = r.nextInt(3); switch (number) { case 0: if (p.getResources() >= (lightType.cost)) { train(u, lightType); } break; case 1: if (p.getResources() >= (rangedType.cost)) { train(u, rangedType); } break; case 2: if (p.getResources() >= (heavyType.cost)) { train(u, heavyType); } break; } } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; int nArmyUnits = 0; List<Unit> freeWorkers = new ArrayList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if ( (u2.getType() == lightType || u2.getType() == rangedType || u2.getType() == heavyType) && u2.getPlayer() == p.getID()) { nArmyUnits++; } } List<Integer> reservedPositions = new ArrayList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } }else if (nbarracks > 0 && !freeWorkers.isEmpty() && nArmyUnits > 2){ // build a new barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } } if (nbarracks != 0) { List<Unit> otherResources = new ArrayList<>(otherResourcePoint(p, pgs)); if (!otherResources.isEmpty()) { if (!freeWorkers.isEmpty()) { //envio para construção if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, otherResources.get(0).getX()+1, otherResources.get(0).getY()+1, reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } } } // harvest with all the free workers: harvestWorkers(freeWorkers, p, pgs); } protected List<Unit> otherResourcePoint(Player p, PhysicalGameState pgs) { List<Unit> bases = getMyBases(p, pgs); Set<Unit> myResources = new HashSet<>(); Set<Unit> otherResources = new HashSet<>(); for (Unit base : bases) { List<Unit> closestUnits = new ArrayList<>(pgs.getUnitsAround(base.getX(), base.getY(), 10)); for (Unit closestUnit : closestUnits) { if (closestUnit.getType().isResource) { myResources.add(closestUnit); } } } for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { if (!myResources.contains(u2)) { otherResources.add(u2); } } } return new ArrayList<>(otherResources); } protected List<Unit> getMyBases(Player p, PhysicalGameState pgs) { List<Unit> bases = new ArrayList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { bases.add(u2); } } return bases; } protected void harvestWorkers(List<Unit> freeWorkers, Player p, PhysicalGameState pgs) { for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } }
12,995
33.290237
154
java
MicroRTS
MicroRTS-master/src/ai/abstraction/EconomyRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author rubensolv */ public class EconomyRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType lightType; UnitType heavyType; int nWorkerBase = 4; int resourcesUsed; // If we have any unit for attack: send it to attack to the nearest enemy unit // If we have a base: train worker until we have 4 workers per base. The 4ª unit send to build a new base. // If we have a barracks: train light, Ranged and Heavy in order // If we have a worker: go to resources closest, build barracks, build new base closest harvest resources public EconomyRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public EconomyRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); } @Override public PlayerAction getAction(int player, GameState gs) throws Exception { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); resourcesUsed=gs.getResourceUsage().getResourcesUsed(player); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of workers: List<Unit> workers = new ArrayList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player && u.getType() == workerType) { workers.add(u); } } workersBehavior(workers, p, pgs); // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } return translateActions(player, gs); } @Override public AI clone() { return new EconomyRush(utt, pf); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } int nBases = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nBases++; } } int qtdWorkLim = nWorkerBase +nBases ;///* nBases; if (nworkers < qtdWorkLim && p.getResources() >= (workerType.cost + resourcesUsed)) { train(u, workerType); resourcesUsed += workerType.cost; } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { int nLight = 0; int nRanged = 0; int nHeavy = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == lightType && u.getPlayer() == p.getID()) { nLight++; } if (u2.getType() == rangedType && u.getPlayer() == p.getID()) { nRanged++; } if (u2.getType() == heavyType && u.getPlayer() == p.getID()) { nHeavy++; } } if (nLight == 0 && p.getResources() >= (lightType.cost + resourcesUsed)) { train(u, lightType); resourcesUsed += lightType.cost; } else if (nRanged == 0 && p.getResources() >= (rangedType.cost + resourcesUsed)) { train(u, rangedType); resourcesUsed += rangedType.cost; } else if (nHeavy == 0 && p.getResources() >= (heavyType.cost + resourcesUsed)) { train(u, heavyType); resourcesUsed += heavyType.cost; } if (p.getResources() >= baseType.cost && nLight != 0 && nRanged != 0 && nHeavy != 0) { int number = r.nextInt(3); switch (number) { case 0: if (p.getResources() >= (baseType.cost+lightType.cost)) { train(u, lightType); resourcesUsed += lightType.cost; } break; case 1: if (p.getResources() >= (baseType.cost+rangedType.cost)) { train(u, rangedType); resourcesUsed += rangedType.cost; } break; case 2: if (p.getResources() >= (baseType.cost+ heavyType.cost)) { train(u, heavyType); resourcesUsed += heavyType.cost; } break; } } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; List<Unit> freeWorkers = new ArrayList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new ArrayList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } } if (nbarracks != 0) { List<Unit> otherResources = new ArrayList<>(otherResourcePoint(p, pgs)); if (!otherResources.isEmpty()) { if (!freeWorkers.isEmpty()) { if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, otherResources.get(0).getX()-1, otherResources.get(0).getY()-1, reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } } } // harvest with all the free workers: harvestWorkers(freeWorkers, p, pgs); } protected List<Unit> otherResourcePoint(Player p, PhysicalGameState pgs) { List<Unit> bases = getMyBases(p, pgs); Set<Unit> myResources = new HashSet<>(); Set<Unit> otherResources = new HashSet<>(); for (Unit base : bases) { List<Unit> closestUnits = new ArrayList<>(pgs.getUnitsAround(base.getX(), base.getY(), 10)); for (Unit closestUnit : closestUnits) { if (closestUnit.getType().isResource) { myResources.add(closestUnit); } } } for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { if (!myResources.contains(u2)) { otherResources.add(u2); } } } if(!bases.isEmpty()){ return getOrderedResources(new ArrayList<>(otherResources), bases.get(0)); }else{ return new ArrayList<>(otherResources); } } protected List<Unit> getOrderedResources(List<Unit> resources, Unit base){ List<Unit> resReturn = new ArrayList<>(); HashMap<Integer, ArrayList<Unit>> map = new HashMap<>(); for (Unit res : resources) { int d = Math.abs(res.getX() - base.getX()) + Math.abs(res.getY() - base.getY()); if(map.containsKey(d)){ ArrayList<Unit> nResourc = map.get(d); nResourc.add(res); }else{ ArrayList<Unit> nResourc = new ArrayList<>(); nResourc.add(res); map.put(d, nResourc); } } ArrayList<Integer> keysOrdered = new ArrayList<>(map.keySet()); Collections.sort(keysOrdered); for (Integer key : keysOrdered) { resReturn.addAll(map.get(key)); } return resReturn; } protected List<Unit> getMyBases(Player p, PhysicalGameState pgs) { List<Unit> bases = new ArrayList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { bases.add(u2); } } return bases; } protected void harvestWorkers(List<Unit> freeWorkers, Player p, PhysicalGameState pgs) { for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } }
13,712
33.804569
154
java
MicroRTS
MicroRTS-master/src/ai/abstraction/EconomyRushBurster.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author rubensolv */ public class EconomyRushBurster extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType lightType; UnitType heavyType; int nWorkerBase = 3*2; // If we have any unit for attack: send it to attack to the nearest enemy unit // If we have a base: train worker until we have 6 workers per base. The 6ª unit send to build a new base. // If we have a barracks: train light, Ranged and Heavy in order // If we have a worker: go to resources closest, build barracks, build new base closest harvest resources public EconomyRushBurster(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public EconomyRushBurster(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); } @Override public PlayerAction getAction(int player, GameState gs) throws Exception { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of workers: List<Unit> workers = new ArrayList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player && u.getType() == workerType) { workers.add(u); } } workersBehavior(workers, p, pgs); // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } return translateActions(player, gs); } @Override public AI clone() { return new EconomyRushBurster(utt, pf); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } int nBases = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nBases++; } } int qtdWorkLim = nWorkerBase * nBases; if (nworkers < qtdWorkLim && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { int nLight = 0; int nRanged = 0; int nHeavy = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == lightType && u.getPlayer() == p.getID()) { nLight++; } if (u2.getType() == rangedType && u.getPlayer() == p.getID()) { nRanged++; } if (u2.getType() == heavyType && u.getPlayer() == p.getID()) { nHeavy++; } } if (nLight == 0 && p.getResources() >= lightType.cost) { train(u, lightType); } else if (nRanged == 0 && p.getResources() >= rangedType.cost) { train(u, rangedType); } else if (nHeavy == 0 && p.getResources() >= heavyType.cost) { train(u, heavyType); } if (nLight != 0 && nRanged != 0 && nHeavy != 0) { int number = r.nextInt(3); switch (number) { case 0: if (p.getResources() >= (lightType.cost)) { train(u, lightType); } break; case 1: if (p.getResources() >= (rangedType.cost)) { train(u, rangedType); } break; case 2: if (p.getResources() >= (heavyType.cost)) { train(u, heavyType); } break; } } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new ArrayList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new ArrayList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } } if (nbarracks != 0) { List<Unit> otherResources = new ArrayList<>(otherResourcePoint(p, pgs)); if (!otherResources.isEmpty()) { if (!freeWorkers.isEmpty()) { //envio para construção if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, otherResources.get(0).getX()-2, otherResources.get(0).getY()-2, reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } } } // harvest with all the free workers: harvestWorkers(freeWorkers, p, pgs); } protected List<Unit> otherResourcePoint(Player p, PhysicalGameState pgs) { List<Unit> bases = getMyBases(p, pgs); Set<Unit> myResources = new HashSet<>(); Set<Unit> otherResources = new HashSet<>(); for (Unit base : bases) { List<Unit> closestUnits = new ArrayList<>(pgs.getUnitsAround(base.getX(), base.getY(), 10)); for (Unit closestUnit : closestUnits) { if (closestUnit.getType().isResource) { myResources.add(closestUnit); } } } for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { if (!myResources.contains(u2)) { otherResources.add(u2); } } } return new ArrayList<>(otherResources); } protected List<Unit> getMyBases(Player p, PhysicalGameState pgs) { List<Unit> bases = new ArrayList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { bases.add(u2); } } return bases; } protected void harvestWorkers(List<Unit> freeWorkers, Player p, PhysicalGameState pgs) { for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } }
12,072
33.008451
154
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Harvest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.XMLWriter; /** * * @author santi */ public class Harvest extends AbstractAction { Unit target; Unit base; PathFinding pf; public Harvest(Unit u, Unit a_target, Unit a_base, PathFinding a_pf) { super(u); target = a_target; base = a_base; pf = a_pf; } public Unit getTarget() { return target; } public Unit getBase() { return base; } public boolean completed(GameState gs) { if (unit.getResources() > 0) { return !gs.getPhysicalGameState().getUnits().contains(base); } else { return !gs.getPhysicalGameState().getUnits().contains(target); } } public boolean equals(Object o) { if (!(o instanceof Harvest)) return false; Harvest a = (Harvest)o; if (target == null && a.target != null) return false; if (target != null && a.target == null) return false; if (target != null && target.getID() != a.target.getID()) return false; if (base == null && a.base != null) return false; if (base != null && a.base == null) return false; if (base != null && base.getID() != a.base.getID()) return false; return pf.getClass() == a.pf.getClass(); } public void toxml(XMLWriter w) { w.tagWithAttributes("Harvest","unitID=\""+unit.getID()+"\" target=\""+target.getID()+"\" base=\""+base.getID()+"\" pathfinding=\""+pf.getClass().getSimpleName()+"\""); w.tag("/Harvest"); } public UnitAction execute(GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); if (unit.getResources()==0) { if (target == null) return null; // go get resources: // System.out.println("findPathToAdjacentPosition from Harvest: (" + target.getX() + "," + target.getY() + ")"); UnitAction move = pf.findPathToAdjacentPosition(unit, target.getX()+target.getY()*gs.getPhysicalGameState().getWidth(), gs, ru); if (move!=null) { if (gs.isUnitActionAllowed(unit, move)) return move; return null; } // harvest: if (target.getX() == unit.getX() && target.getY() == unit.getY()-1) return new UnitAction(UnitAction.TYPE_HARVEST,UnitAction.DIRECTION_UP); if (target.getX() == unit.getX()+1 && target.getY() == unit.getY()) return new UnitAction(UnitAction.TYPE_HARVEST,UnitAction.DIRECTION_RIGHT); if (target.getX() == unit.getX() && target.getY() == unit.getY()+1) return new UnitAction(UnitAction.TYPE_HARVEST,UnitAction.DIRECTION_DOWN); if (target.getX() == unit.getX()-1 && target.getY() == unit.getY()) return new UnitAction(UnitAction.TYPE_HARVEST,UnitAction.DIRECTION_LEFT); } else { // return resources: if (base == null) return null; // System.out.println("findPathToAdjacentPosition from Return: (" + target.getX() + "," + target.getY() + ")"); UnitAction move = pf.findPathToAdjacentPosition(unit, base.getX()+base.getY()*gs.getPhysicalGameState().getWidth(), gs, ru); if (move!=null) { if (gs.isUnitActionAllowed(unit, move)) return move; return null; } // harvest: if (base.getX() == unit.getX() && base.getY() == unit.getY()-1) return new UnitAction(UnitAction.TYPE_RETURN,UnitAction.DIRECTION_UP); if (base.getX() == unit.getX()+1 && base.getY() == unit.getY()) return new UnitAction(UnitAction.TYPE_RETURN,UnitAction.DIRECTION_RIGHT); if (base.getX() == unit.getX() && base.getY() == unit.getY()+1) return new UnitAction(UnitAction.TYPE_RETURN,UnitAction.DIRECTION_DOWN); if (base.getX() == unit.getX()-1 && base.getY() == unit.getY()) return new UnitAction(UnitAction.TYPE_RETURN,UnitAction.DIRECTION_LEFT); } return null; } }
4,458
37.439655
175
java
MicroRTS
MicroRTS-master/src/ai/abstraction/HeavyDefense.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author Cleyton */ public class HeavyDefense extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType heavyType; // These strategies behave similarly to WD, //with the difference being that the defense line is formed by //heavy units for HD, respectively. public HeavyDefense(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public HeavyDefense(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); heavyType = utt.getUnitType("Heavy"); } public AI clone() { return new HeavyDefense(utt, pf); } /* This is the main function of the AI. It is called at each game cycle with the most up to date game state and returns which actions the AI wants to execute in this cycle. The input parameters are: - player: the player that the AI controls (0 or 1) - gs: the current game state This method returns the actions to be sent to each of the units in the gamestate controlled by the player, packaged as a PlayerAction. */ public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, pgs); // This method simply takes all the unit actions executed so far, and packages them into a PlayerAction return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= heavyType.cost) { train(u, heavyType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; int mybase = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } else if(u2.getPlayer()==p.getID() && u2.getType() == baseType) { mybase = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); } } if (closestEnemy!=null && (closestDistance < pgs.getHeight()/2 || mybase < pgs.getHeight()/2)) { attack(u,closestEnemy); } else { attack(u, null); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed && !freeWorkers.isEmpty()) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.getTarget() != closestResource || h_aa.getBase()!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } } } } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
8,566
32.33463
133
java
MicroRTS
MicroRTS-master/src/ai/abstraction/HeavyRush.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author santi */ public class HeavyRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType heavyType; // Strategy implemented by this class: // If we have any "heavy": send it to attack to the nearest enemy unit // If we have a base: train worker until we have 1 workers // If we have a barracks: train heavy // If we have a worker: do this if needed: build base, build barracks, harvest resources public HeavyRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public HeavyRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); heavyType = utt.getUnitType("Heavy"); } public AI clone() { return new HeavyRush(utt, pf); } /* This is the main function of the AI. It is called at each game cycle with the most up to date game state and returns which actions the AI wants to execute in this cycle. The input parameters are: - player: the player that the AI controls (0 or 1) - gs: the current game state This method returns the actions to be sent to each of the units in the gamestate controlled by the player, packaged as a PlayerAction. */ public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("HeavyRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, gs); // This method simply takes all the unit actions executed so far, and packages them into a PlayerAction return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= heavyType.cost) { train(u, heavyType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { // System.out.println("HeavyRushAI.meleeUnitBehavior: " + u + " attacks " + closestEnemy); attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed && !freeWorkers.isEmpty()) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: List<Unit> stillFreeWorkers = new LinkedList<>(); for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } boolean workerStillFree = true; if (u.getResources() > 0) { if (closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.base!=closestBase) harvest(u, null, closestBase); } else { harvest(u, null, closestBase); } workerStillFree = false; } } else { if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.target != closestResource || h_aa.base!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } workerStillFree = false; } } if (workerStillFree) stillFreeWorkers.add(u); } for(Unit u:stillFreeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
9,375
33.597786
127
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Idle.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.XMLWriter; /** * * @author santi */ public class Idle extends AbstractAction { public Idle(Unit u) { super(u); } public boolean completed(GameState gs) { return false; } public boolean equals(Object o) { return o instanceof Idle; } public void toxml(XMLWriter w) { w.tagWithAttributes("Idle","unitID=\""+unit.getID()+"\""); w.tag("/Idle"); } public UnitAction execute(GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); if (!unit.getType().canAttack) return null; for(Unit target:pgs.getUnits()) { if (target.getPlayer()!=-1 && target.getPlayer()!=unit.getPlayer()) { int dx = target.getX()-unit.getX(); int dy = target.getY()-unit.getY(); double d = Math.sqrt(dx*dx+dy*dy); if (d<=unit.getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION,target.getX(),target.getY()); } } } return null; } }
1,409
23.736842
103
java
MicroRTS
MicroRTS-master/src/ai/abstraction/LightDefense.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author Cleyton */ public class LightDefense extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType lightType; // These strategies behave similarly to WD, //with the difference being that the defense line is formed by //ranged and lights units for RD and LD, respectively. Since RD //and LD train ranged and lights units, they build a barracks with //their worker as soon as there is enough resources; the worker //returns to collecting resources once the barracks is built. public LightDefense(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public LightDefense(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); lightType = utt.getUnitType("Light"); } public AI clone() { return new LightDefense(utt, pf); } /* This is the main function of the AI. It is called at each game cycle with the most up to date game state and returns which actions the AI wants to execute in this cycle. The input parameters are: - player: the player that the AI controls (0 or 1) - gs: the current game state This method returns the actions to be sent to each of the units in the gamestate controlled by the player, packaged as a PlayerAction. */ public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, pgs); // This method simply takes all the unit actions executed so far, and packages them into a PlayerAction return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= lightType.cost) { train(u, lightType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; int mybase = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } else if(u2.getPlayer()==p.getID() && u2.getType() == baseType) { mybase = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); } } if (closestEnemy!=null && (closestDistance < pgs.getHeight()/2 || mybase < pgs.getHeight()/2)) { attack(u,closestEnemy); } else { attack(u, null); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed && !freeWorkers.isEmpty()) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.getTarget() != closestResource || h_aa.getBase()!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } } } } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
8,798
32.842308
133
java
MicroRTS
MicroRTS-master/src/ai/abstraction/LightRush.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author santi */ public class LightRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType lightType; // Strategy implemented by this class: // If we have any "light": send it to attack to the nearest enemy unit // If we have a base: train worker until we have 1 workers // If we have a barracks: train light // If we have a worker: do this if needed: build base, build barracks, harvest resources public LightRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public LightRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); lightType = utt.getUnitType("Light"); } public AI clone() { return new LightRush(utt, pf); } /* This is the main function of the AI. It is called at each game cycle with the most up to date game state and returns which actions the AI wants to execute in this cycle. The input parameters are: - player: the player that the AI controls (0 or 1) - gs: the current game state This method returns the actions to be sent to each of the units in the gamestate controlled by the player, packaged as a PlayerAction. */ public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, gs); // This method simply takes all the unit actions executed so far, and packages them into a PlayerAction return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= lightType.cost) { train(u, lightType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { // System.out.println("LightRushAI.meleeUnitBehavior: " + u + " attacks " + closestEnemy); attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed && !freeWorkers.isEmpty()) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: List<Unit> stillFreeWorkers = new LinkedList<>(); for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } boolean workerStillFree = true; if (u.getResources() > 0) { if (closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.base!=closestBase) harvest(u, null, closestBase); } else { harvest(u, null, closestBase); } workerStillFree = false; } } else { if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.target != closestResource || h_aa.base!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } workerStillFree = false; } } if (workerStillFree) stillFreeWorkers.add(u); } for(Unit u:stillFreeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
9,388
33.518382
127
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Move.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.XMLWriter; /** * * @author santi */ public class Move extends AbstractAction { int x,y; PathFinding pf; public Move(Unit u, int a_x, int a_y, PathFinding a_pf) { super(u); x = a_x; y = a_y; pf = a_pf; } public boolean completed(GameState gs) { return unit.getX() == x && unit.getY() == y; } public boolean equals(Object o) { if (!(o instanceof Move)) return false; Move a = (Move)o; return x == a.x && y == a.y && pf.getClass() == a.pf.getClass(); } public void toxml(XMLWriter w) { w.tagWithAttributes("Move","unitID=\""+unit.getID()+"\" x=\""+x+"\" y=\""+y+"\" pathfinding=\""+pf.getClass().getSimpleName()+"\""); w.tag("/Move"); } public UnitAction execute(GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); UnitAction move = pf.findPath(unit, x+y*pgs.getWidth(), gs, ru); // System.out.println("AStarAttak returns: " + move); if (move!=null && gs.isUnitActionAllowed(unit, move)) return move; return null; } }
1,471
23.949153
140
java
MicroRTS
MicroRTS-master/src/ai/abstraction/RangedDefense.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author Cleyton */ public class RangedDefense extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; // These strategies behave similarly to WD, //with the difference being that the defense line is formed by //ranged and lights units for RD and LD, respectively. Since RD //and LD train ranged and lights units, they build a barracks with //their worker as soon as there is enough resources; the worker //returns to collecting resources once the barracks is built. public RangedDefense(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public RangedDefense(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); } public AI clone() { return new RangedDefense(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, pgs); return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= rangedType.cost) { train(u, rangedType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; int mybase = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } else if(u2.getPlayer()==p.getID() && u2.getType() == baseType) { mybase = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); } } if (closestEnemy!=null && (closestDistance < pgs.getHeight()/2 || mybase < pgs.getHeight()/2)) { attack(u,closestEnemy); } else { attack(u, null); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.getTarget() != closestResource || h_aa.getBase()!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } } } } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
8,178
32.11336
133
java
MicroRTS
MicroRTS-master/src/ai/abstraction/RangedRush.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author santi */ public class RangedRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; // If we have any "light": send it to attack to the nearest enemy unit // If we have a base: train worker until we have 1 workers // If we have a barracks: train light // If we have a worker: do this if needed: build base, build barracks, harvest resources public RangedRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public RangedRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); } public AI clone() { return new RangedRush(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers, p, gs); return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (nworkers < 1 && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= rangedType.cost) { train(u, rangedType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { // System.out.println("LightRushAI.meleeUnitBehavior: " + u + " attacks " + closestEnemy); attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: List<Unit> stillFreeWorkers = new LinkedList<>(); for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } boolean workerStillFree = true; if (u.getResources() > 0) { if (closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.base!=closestBase) harvest(u, null, closestBase); } else { harvest(u, null, closestBase); } workerStillFree = false; } } else { if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.target != closestResource || h_aa.base!=closestBase) harvest(u, closestResource, closestBase); } else { harvest(u, closestResource, closestBase); } workerStillFree = false; } } if (workerStillFree) stillFreeWorkers.add(u); } for(Unit u:stillFreeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
8,720
32.802326
127
java
MicroRTS
MicroRTS-master/src/ai/abstraction/SimpleEconomyRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author rubensolv */ public class SimpleEconomyRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType lightType; UnitType heavyType; // If we have any unit for attack: send it to attack to the nearest enemy unit // If we have a base: train worker until we have 3 workers per base. // If we have a barracks: train light, Ranged and Heavy in order and before choose randomly a new unit for build // If we have a worker: go to resources closest, build barracks, build new base closest harvest resources public SimpleEconomyRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public SimpleEconomyRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); } @Override public PlayerAction getAction(int player, GameState gs) throws Exception { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { baseBehavior(u, p, pgs); } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of workers: List<Unit> workers = new ArrayList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player && u.getType() == workerType) { workers.add(u); } } workersBehavior(workers, p, pgs); // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { meleeUnitBehavior(u, p, gs); } } return translateActions(player, gs); } @Override public AI clone() { return new SimpleEconomyRush(utt, pf); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nworkers = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } //calculo numero de bases int nBases = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nBases++; } } int qtdWorkLim = 3 * nBases; if (nworkers < qtdWorkLim && p.getResources() >= workerType.cost) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { int nLight = 0; int nRanged = 0; int nHeavy = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType() == lightType && u.getPlayer() == p.getID()) { nLight++; } if (u2.getType() == rangedType && u.getPlayer() == p.getID()) { nRanged++; } if (u2.getType() == heavyType && u.getPlayer() == p.getID()) { nHeavy++; } } //check if I already have some light, if not, create. if (nLight == 0 && p.getResources() >= lightType.cost) { train(u, lightType); }else if (nRanged == 0 && p.getResources() >= rangedType.cost) { // check if I already have some Ranged, if not, create train(u, rangedType); }else if (nHeavy == 0 && p.getResources() >= heavyType.cost) { //check if I already have some Heavy, if not, create. train(u, heavyType); } //if you already have a unit of each, randomly select any one to generate if (nLight != 0 && nRanged != 0 && nHeavy != 0) { int number = r.nextInt(3); switch (number) { case 0: if (p.getResources() >= lightType.cost) { train(u, lightType); } break; case 1: if (p.getResources() >= rangedType.cost) { train(u, rangedType); } break; case 2: if (p.getResources() >= heavyType.cost) { train(u, heavyType); } break; } } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int resourcesUsed = 0; List<Unit> freeWorkers = new ArrayList<>(workers); if (workers.isEmpty()) { return; } for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } } List<Integer> reservedPositions = new ArrayList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += baseType.cost; } } if (nbarracks == 0 && !freeWorkers.isEmpty()) { // build a barracks: if (p.getResources() >= barracksType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; } } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } }
10,356
33.069079
116
java
MicroRTS
MicroRTS-master/src/ai/abstraction/Train.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import util.XMLWriter; /** * * @author santi */ public class Train extends AbstractAction { UnitType type; boolean completed = false; public Train(Unit u, UnitType a_type) { super(u); type = a_type; } public boolean completed(GameState pgs) { return completed; } public boolean equals(Object o) { if (!(o instanceof Train)) return false; Train a = (Train)o; return type == a.type; } public void toxml(XMLWriter w) { w.tagWithAttributes("Train","unitID=\""+unit.getID()+"\" type=\""+type.name+"\""); w.tag("/Train"); } public UnitAction execute(GameState gs, ResourceUsage ru) { // find the best location for the unit: PhysicalGameState pgs = gs.getPhysicalGameState(); int x = unit.getX(); int y = unit.getY(); int best_direction = -1; int best_score = -1; if (y>0 && gs.free(x,y-1)) { int score = score(x,y-1, type, unit.getPlayer(), pgs); if (score>best_score || best_direction==-1) { best_score = score; best_direction = UnitAction.DIRECTION_UP; } } if (x<pgs.getWidth()-1 && gs.free(x+1,y)) { int score = score(x+1,y, type, unit.getPlayer(), pgs); if (score>best_score || best_direction==-1) { best_score = score; best_direction = UnitAction.DIRECTION_RIGHT; } } if (y<pgs.getHeight()-1 && gs.free(x,y+1)) { int score = score(x,y+1, type, unit.getPlayer(), pgs); if (score>best_score || best_direction==-1) { best_score = score; best_direction = UnitAction.DIRECTION_DOWN; } } if (x>0 && gs.free(x-1,y)) { int score = score(x-1,y, type, unit.getPlayer(), pgs); if (score>best_score || best_direction==-1) { best_score = score; best_direction = UnitAction.DIRECTION_LEFT; } } completed = true; // System.out.println("Executing train: " + type + " best direction " + best_direction); if (best_direction!=-1) { UnitAction ua = new UnitAction(UnitAction.TYPE_PRODUCE,best_direction, type); if (gs.isUnitActionAllowed(unit, ua)) return ua; } return null; } public int score(int x, int y, UnitType type, int player, PhysicalGameState pgs) { int distance = 0; boolean first = true; if (type.canHarvest) { // score is minus distance to closest resource for(Unit u:pgs.getUnits()) { if (u.getType().isResource) { int d = Math.abs(u.getX() - x) + Math.abs(u.getY() - y); if (first || d<distance) { distance = d; first = false; } } } } else { // score is minus distance to closest enemy for(Unit u:pgs.getUnits()) { if (u.getPlayer()>=0 && u.getPlayer()!=player) { int d = Math.abs(u.getX() - x) + Math.abs(u.getY() - y); if (first || d<distance) { distance = d; first = false; } } } } return -distance; } }
3,878
28.838462
95
java
MicroRTS
MicroRTS-master/src/ai/abstraction/WorkerDefense.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author Cleyton */ public class WorkerDefense extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracks; //This strategy assigns the first worker to collect //resources while the base trains more workers. The workers //stand at a distance from their base equal to the height of the //map divided by two, forming a defense line. If an enemy unit //e gets within a distance of also the height of the map divided //by two from the workers, all units are sent to attack e public WorkerDefense(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public WorkerDefense(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; if (utt!=null) { workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracks = utt.getUnitType("Barracks"); } } public AI clone() { return new WorkerDefense(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for(Unit u:pgs.getUnits()) { if (u.getType()==baseType && u.getPlayer() == player && gs.getActionAssignment(u)==null) { baseBehavior(u,p,pgs); } } // behavior of melee units: for(Unit u:pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u)==null) { meleeUnitBehavior(u,p,gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for(Unit u:pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers,p,gs); return translateActions(player,gs); } public void baseBehavior(Unit u,Player p, PhysicalGameState pgs) { if (p.getResources()>=workerType.cost) train(u, workerType); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; Unit closestMeleeEnemy = null; int closestDistance = 0; int enemyDistance = 0; int mybase = 0; for(Unit u2:pgs.getUnits()) { if (u2.getPlayer()>=0 && u2.getPlayer()!=p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy==null || d<closestDistance) { closestEnemy = u2; closestDistance = d; } } else if(u2.getPlayer()==p.getID() && u2.getType() == baseType) { mybase = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); } } if (closestEnemy!=null && (closestDistance < pgs.getHeight()/2 || mybase < pgs.getHeight()/2)) { attack(u,closestEnemy); } else { attack(u, null); } } public void workersBehavior(List<Unit> workers,Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int resourcesUsed = 0; Unit harvestWorker = null; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) return; for(Unit u2:pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) nbases++; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases==0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources()>=baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed+=baseType.cost; } } if (freeWorkers.size()>0) harvestWorker = freeWorkers.remove(0); // harvest with the harvest worker: if (harvestWorker!=null) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestResource==null || d<closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestBase==null || d<closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(harvestWorker); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.getTarget() != closestResource || h_aa.getBase()!=closestBase) { harvest(harvestWorker, closestResource, closestBase); } else { } } else { harvest(harvestWorker, closestResource, closestBase); } } } for(Unit u:freeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
7,575
32.522124
116
java
MicroRTS
MicroRTS-master/src/ai/abstraction/WorkerRush.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author santi */ public class WorkerRush extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; // Strategy implemented by this class: // If we have more than 1 "Worker": send the extra workers to attack to the nearest enemy unit // If we have a base: train workers non-stop // If we have a worker: do this if needed: build base, harvest resources public WorkerRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public WorkerRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; if (utt!=null) { workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); } } public AI clone() { return new WorkerRush(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for(Unit u:pgs.getUnits()) { if (u.getType()==baseType && u.getPlayer() == player && gs.getActionAssignment(u)==null) { baseBehavior(u,p,pgs); } } // behavior of melee units: for(Unit u:pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u)==null) { meleeUnitBehavior(u,p,gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for(Unit u:pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers,p,gs); return translateActions(player,gs); } public void baseBehavior(Unit u,Player p, PhysicalGameState pgs) { if (p.getResources()>=workerType.cost) train(u, workerType); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getPlayer()>=0 && u2.getPlayer()!=p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy==null || d<closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy!=null) { attack(u,closestEnemy); } } public void workersBehavior(List<Unit> workers,Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int resourcesUsed = 0; Unit harvestWorker = null; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) return; for(Unit u2:pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) nbases++; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases==0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources()>=baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed+=baseType.cost; } } if (freeWorkers.size()>0) harvestWorker = freeWorkers.remove(0); // harvest with the harvest worker: if (harvestWorker!=null) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestResource==null || d<closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestBase==null || d<closestDistance) { closestBase = u2; closestDistance = d; } } } boolean harestWorkerFree = true; if (harvestWorker.getResources() > 0) { if (closestBase!=null) { AbstractAction aa = getAbstractAction(harvestWorker); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.base!=closestBase) harvest(harvestWorker, null, closestBase); } else { harvest(harvestWorker, null, closestBase); } harestWorkerFree = false; } } else { if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(harvestWorker); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.target != closestResource || h_aa.base!=closestBase) harvest(harvestWorker, closestResource, closestBase); } else { harvest(harvestWorker, closestResource, closestBase); } harestWorkerFree = false; } } if (harestWorkerFree) freeWorkers.add(harvestWorker); } for(Unit u:freeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
7,462
33.391705
139
java
MicroRTS
MicroRTS-master/src/ai/abstraction/WorkerRushPlusPlus.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author Cleyton */ public class WorkerRushPlusPlus extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracks; boolean resourse = true; // Strategy implemented by this class: // If we have more than 1 "Worker": send the extra workers to attack to the nearest enemy unit //attack base and barracks first // If we have a base: train workers non-stop // If we have a worker: do this if needed: build base, harvest resources public WorkerRushPlusPlus(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public WorkerRushPlusPlus(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; if (utt!=null) { workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracks = utt.getUnitType("Barracks"); } } public AI clone() { return new WorkerRushPlusPlus(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); PlayerAction pa = new PlayerAction(); // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); // behavior of bases: for(Unit u:pgs.getUnits()) { if (u.getType()==baseType && u.getPlayer() == player && gs.getActionAssignment(u)==null) { baseBehavior(u,p,pgs); } } // behavior of melee units: for(Unit u:pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u)==null) { meleeUnitBehavior(u,p,gs); } } // behavior of workers: List<Unit> workers = new LinkedList<>(); for(Unit u:pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } workersBehavior(workers,p,gs); return translateActions(player,gs); } public void baseBehavior(Unit u,Player p, PhysicalGameState pgs) { if (p.getResources()>=workerType.cost) train(u, workerType); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; Unit closestMeleeEnemy = null; int closestDistance = 0; int enemyDistance = 0; int mybase = 0; for(Unit u2:pgs.getUnits()) { if (u2.getPlayer()>=0 && u2.getPlayer()!=p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy==null || d<closestDistance) { closestEnemy = u2; closestDistance = d; } } else if(u2.getPlayer()==p.getID() && u2.getType() == baseType) { mybase = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); } } if (closestEnemy!=null) { attack(u,closestEnemy); } else { attack(u, null); } } public void workersBehavior(List<Unit> workers,Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int nbases = 0; int resourcesUsed = 0; Unit harvestWorker = null; List<Unit> freeWorkers = new LinkedList<>(workers); if (workers.isEmpty()) return; for(Unit u2:pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) nbases++; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases==0 && !freeWorkers.isEmpty() && resourse) { // build a base: if (p.getResources()>=baseType.cost + resourcesUsed) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,baseType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed+=baseType.cost; } } if (freeWorkers.size()>0 && resourse) harvestWorker = freeWorkers.remove(0); // harvest with the harvest worker: if (harvestWorker!=null) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestResource==null || d<closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for(Unit u2:pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer()==p.getID()) { int d = Math.abs(u2.getX() - harvestWorker.getX()) + Math.abs(u2.getY() - harvestWorker.getY()); if (closestBase==null || d<closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource!=null && closestBase!=null) { AbstractAction aa = getAbstractAction(harvestWorker); if (aa instanceof Harvest) { Harvest h_aa = (Harvest)aa; if (h_aa.getTarget() != closestResource || h_aa.getBase()!=closestBase) { harvest(harvestWorker, closestResource, closestBase); } else { } } else { harvest(harvestWorker, closestResource, closestBase); } } else if((closestResource==null) && (p.getResources() == 0) && (freeWorkers.isEmpty())) { freeWorkers.add(harvestWorker); resourse = false; } } for(Unit u:freeWorkers) meleeUnitBehavior(u, p, gs); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
7,690
32.585153
116
java
MicroRTS
MicroRTS-master/src/ai/abstraction/cRush/CRanged_Tactic.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.cRush; import ai.abstraction.AbstractAction; import ai.abstraction.Attack; import ai.abstraction.pathfinding.PathFinding; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author Cristiano D'Angelo */ public class CRanged_Tactic extends AbstractAction { Unit target; PathFinding pf; Unit home; Unit enemyBase; UnitType workerType; UnitType rangedType; UnitType heavyType; UnitType baseType; UnitType barracksType; UnitType resourceType; UnitType lightType; UnitTypeTable utt; Player p; public CRanged_Tactic(Unit u, Unit a_target, Unit h, Unit eb, PathFinding a_pf, UnitTypeTable ut, Player pl) { super(u); target = a_target; pf = a_pf; home = h; utt = ut; p = pl; workerType = utt.getUnitType("Worker"); rangedType = utt.getUnitType("Ranged"); heavyType = utt.getUnitType("Heavy"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); resourceType = utt.getUnitType("Resource"); lightType = utt.getUnitType("Light"); enemyBase = eb; } public boolean completed(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); return !pgs.getUnits().contains(target); } public boolean equals(Object o) { if (!(o instanceof Attack)) { return false; } CRanged_Tactic a = (CRanged_Tactic) o; return target.getID() == a.target.getID() && pf.getClass() == a.pf.getClass(); } public void toxml(XMLWriter w) { w.tagWithAttributes("Attack", "unitID=\"" + getUnit().getID() + "\" target=\"" + target.getID() + "\" pathfinding=\"" + pf.getClass().getSimpleName() + "\""); w.tag("/Attack"); } public UnitAction execute(GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit unit = getUnit(); boolean timeToAttack = false; if (home == null) { home = unit; } if (enemyBase == null) { enemyBase = target; } //Determining distances double rd = 0.0; if (home != null) { rd = distance(unit, home); } double d = distance(unit, target); //Counting enemy units List<Unit> gameUnites = pgs.getUnits(); int nEnemyBases = 0; int enemyAttackUnits = 0; int enemyWorkers = 0; int cutoffTime = 5000; if ((pgs.getWidth() * pgs.getHeight()) > 3000) { cutoffTime = 15000; } for (Unit u2 : gameUnites) { if (u2 != null && u2.getPlayer() != p.getID() && u2.getType() == baseType) { nEnemyBases++; } if (u2 != null && u2.getPlayer() != p.getID() && (u2.getType() == rangedType || u2.getType() == heavyType || u2.getType() == lightType)) { enemyAttackUnits++; } if (u2 != null && u2.getPlayer() != p.getID() && u2.getType() == workerType) { enemyWorkers++; } } //Determining if its time to attack if ((enemyWorkers < (2 * nEnemyBases) || nEnemyBases == 0) && enemyAttackUnits == 0) { timeToAttack = true; } if (gs.getTime() > cutoffTime) { timeToAttack = true; } //Finding ranged ally and distance from ally to target Unit ally = nearestRangedAlly(enemyBase, gameUnites, gs); double ad = 0.0; if (ally != null) { ad = distance(ally, target); } //Action for workers if (unit.getType() == workerType) { UnitAction move = null; if (d <= unit.getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, target.getX(), target.getY()); } else if (timeToAttack) { move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } else if (ally != null) { if (d > ad) { move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } else { move = pf.findPathToPositionInRange(unit, ally.getX() + ally.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } if (move == null) { move = pf.findPathToPositionInRange(unit, (ally.getX() - 1) + (ally.getY()) * gs.getPhysicalGameState().getWidth(), unit.getAttackRange() + 1, gs, ru); } if (move == null) { move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } } else { move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } //Action for ranged units if (d <= unit.getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, target.getX(), target.getY()); } //If the unit is the ally closest to enemy base else if ((ally == null || ally.getID() == unit.getID())) { UnitAction move = null; if (timeToAttack && (target.getType() == baseType)) { move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } else if (rd < 5 || (distance(unit, enemyBase) > distance(home, enemyBase))) { move = pf.findPathToPositionInRange(unit, enemyBase.getX() + enemyBase.getY() * gs.getPhysicalGameState().getWidth(), unit.getAttackRange(), gs, ru); } if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } else if (timeToAttack) { //Attack behavior if (d <= (unit.getAttackRange()) - 1 && rd > 2 && unit.getMoveTime() < target.getMoveTime()) { UnitAction move = pf.findPathToPositionInRange(unit, home.getX() + home.getY() * gs.getPhysicalGameState().getWidth(), getUnit().getAttackRange(), gs, ru); if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } else if (d <= unit.getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, target.getX(), target.getY()); } else { // move towards the unit: UnitAction move = pf.findPathToPositionInRange(unit, target.getX() + target.getY() * gs.getPhysicalGameState().getWidth(), getUnit().getAttackRange(), gs, ru); if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } } //Behavior for ranged units to move into a position next to the leading ranged unit (ally) else { Unit atUp = pgs.getUnitAt(ally.getX(), ally.getY() - 1); Unit atUpLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY() - 1); Unit atLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY()); Unit atDown = pgs.getUnitAt(ally.getX(), ally.getY() + 1); Unit atDownRight = pgs.getUnitAt(ally.getX() + 1, ally.getY() + 1); Unit atRight = pgs.getUnitAt(ally.getX() + 1, ally.getY()); boolean positionFound = false; if ((distanceWithoutUnits(ally.getX(), (ally.getY() + 1), enemyBase.getX(), enemyBase.getY()) > distance(ally, enemyBase))) { while (!positionFound) { if ((atDown != null && unit != atDown) && (atDownRight != null && unit != atDownRight) && (atRight != null && unit != atRight)) { ally = atRight; } else { positionFound = true; } atDown = pgs.getUnitAt(ally.getX(), ally.getY() + 1); atDownRight = pgs.getUnitAt(ally.getX() + 1, ally.getY() + 1); atRight = pgs.getUnitAt(ally.getX() + 1, ally.getY()); if (atDown == null || atDownRight == null || atRight == null) { positionFound = true; } } } else { while (!positionFound) { if ((atUp != null && unit != atUp) && (atUpLeft != null && unit != atUpLeft) && (atLeft != null && unit != atLeft)) { ally = atLeft; } else { positionFound = true; } atUp = pgs.getUnitAt(ally.getX(), ally.getY() - 1); atUpLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY() - 1); atLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY()); if (atUp == null || atUpLeft == null || atLeft == null) { positionFound = true; } } } return squareMove(gs, ru, ally); } } //Calculates distance between unit a and unit b public double distance(Unit a, Unit b) { if (a == null || b == null) { return 0.0; } int dx = b.getX() - a.getX(); int dy = b.getY() - a.getY(); double toReturn = Math.sqrt(dx * dx + dy * dy); return toReturn; } //Calculates distance bewteen positions a and b using x,y coordinates public double distanceWithoutUnits(int xa, int ya, int xb, int yb) { int dx = xb - xa; int dy = yb - ya; double toReturn = Math.sqrt(dx * dx + dy * dy); return toReturn; } //Figures out correct move action for a square unit formation public UnitAction squareMove(GameState gs, ResourceUsage ru, Unit targetUnit) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit unit = getUnit(); Unit ally = targetUnit; Unit atUp = pgs.getUnitAt(ally.getX(), ally.getY() - 1); Unit atUpLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY() - 1); Unit atLeft = pgs.getUnitAt(ally.getX() - 1, ally.getY()); Unit atDown = pgs.getUnitAt(ally.getX(), ally.getY() + 1); Unit atDownRight = pgs.getUnitAt(ally.getX() + 1, ally.getY() + 1); Unit atRight = pgs.getUnitAt(ally.getX() + 1, ally.getY()); UnitAction moveToUp = pf.findPath(unit, (ally.getX()) + (ally.getY() - 1) * gs.getPhysicalGameState().getWidth(), gs, ru); UnitAction moveToUpLeft = pf.findPath(unit, (ally.getX() - 1) + (ally.getY() - 1) * gs.getPhysicalGameState().getWidth(), gs, ru); UnitAction moveToLeft = pf.findPath(unit, (ally.getX() - 1) + (ally.getY()) * gs.getPhysicalGameState().getWidth(), gs, ru); UnitAction moveToDown = pf.findPath(unit, (ally.getX()) + (ally.getY() + 1) * gs.getPhysicalGameState().getWidth(), gs, ru); UnitAction moveToDownRight = pf.findPath(unit, (ally.getX() + 1) + (ally.getY() + 1) * gs.getPhysicalGameState().getWidth(), gs, ru); UnitAction moveToRight = pf.findPath(unit, (ally.getX() + 1) + (ally.getY()) * gs.getPhysicalGameState().getWidth(), gs, ru); if (distanceWithoutUnits(ally.getX(), (ally.getY() + 1), enemyBase.getX(), enemyBase.getY()) > distance(ally, enemyBase)) { UnitAction move = null; if (unit == atDown || unit == atDownRight || unit == atRight) { return null; } if (atDown == null) { move = moveToDown; } else if (atRight == null) { move = moveToRight; } else if (atDownRight == null) { move = moveToDownRight; } if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } else { UnitAction move = null; if (unit == atUp || unit == atUpLeft || unit == atLeft) { return null; } if (atUp == null) { move = moveToUp; } else if (atLeft == null) { move = moveToLeft; } else if (atUpLeft == null) { move = moveToUpLeft; } if (move != null && gs.isUnitActionAllowed(unit, move)) { return move; } return null; } } //Finds farthest ranged unit from starting point public Unit farthestRangedAlly(Unit start, List<Unit> unites, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit farthestUnit = null; double farthestDistance = 0; for (Unit u2 : unites) { if (u2.getType() == rangedType && u2.getPlayer() == p.getID() && home != null) { int dx = start.getX() - u2.getX(); int dy = start.getY() - u2.getY(); double d = Math.sqrt(dx * dx + dy * dy); if (d > farthestDistance) { farthestDistance = d; farthestUnit = u2; } } } return farthestUnit; } //Finds nearest ranged unit from starting point public Unit nearestRangedAlly(Unit start, List<Unit> unites, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit nearestUnit = null; double nearestDistance = -1; if (start != null) { for (Unit u2 : unites) { if (u2 != null && u2.getPlayer() == p.getID() && u2.getType() == rangedType) { int dx = start.getX() - u2.getX(); int dy = start.getY() - u2.getY(); double d = Math.sqrt(dx * dx + dy * dy); if (d < nearestDistance || nearestDistance == -1) { nearestDistance = d; nearestUnit = u2; } } } } return nearestUnit; } }
15,030
37.344388
175
java
MicroRTS
MicroRTS-master/src/ai/abstraction/cRush/CRush_V1.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.cRush; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author Cristiano D'Angelo */ public class CRush_V1 extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType heavyType; UnitType lightType; public CRush_V1(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public CRush_V1(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); } public AI clone() { return new CRush_V1(utt, pf); } boolean buildingRacks = false; int resourcesUsed = 0; public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); boolean isRush = false; if ((pgs.getWidth() * pgs.getHeight()) <= 144){ isRush = true; } // System.out.println("LightRushAI for player " + player + " (cycle " + gs.getTime() + ")"); List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } if(isRush){ rushWorkersBehavior(workers, p, pgs, gs); } else { workersBehavior(workers, p, pgs, gs); } // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { if(isRush){ rushBaseBehavior(u, p, pgs); }else { baseBehavior(u, p, pgs); } } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { if (u.getType() == rangedType) { rangedUnitBehavior(u, p, gs); } else { meleeUnitBehavior(u, p, gs); } } } return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs) { int nbases = 0; int nbarracks = 0; int nworkers = 0; int resources = p.getResources(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } } if (nworkers < (nbases + 1) && p.getResources() >= workerType.cost) { train(u, workerType); } //Buffers the resources that are being used for barracks if (resourcesUsed != barracksType.cost * nbarracks) { resources = resources - barracksType.cost; } if (buildingRacks && (resources >= workerType.cost + rangedType.cost)) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= rangedType.cost) { train(u, rangedType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { // System.out.println("LightRushAI.meleeUnitBehavior: " + u + " attacks " + closestEnemy); attack(u, closestEnemy); } } public void rangedUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; Unit closestRacks = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestRacks == null || d < closestDistance) { closestRacks = u2; closestDistance = d; } } } if (closestEnemy != null) { // System.out.println("LightRushAI.meleeUnitBehavior: " + u + " attacks " + closestEnemy); rangedAttack(u, closestEnemy, closestRacks); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs, GameState gs) { int nbases = 0; int nbarracks = 0; int nworkers = 0; resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(); List<Unit> battleWorkers = new LinkedList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (workers.size() > (nbases + 1)) { for (int n = 0; n < (nbases + 1); n++) { freeWorkers.add(workers.get(0)); workers.remove(0); } battleWorkers.addAll(workers); } else { freeWorkers.addAll(workers); } if (workers.isEmpty()) { return; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); //resourcesUsed += baseType.cost; } } if ((nbarracks == 0) && (!freeWorkers.isEmpty()) && nworkers > 1 && p.getResources() >= barracksType.cost) { int resources = p.getResources(); Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u,barracksType,u.getX(),u.getY(),reservedPositions,p,pgs); resourcesUsed += barracksType.cost; buildingRacks = true; //The problem with this right now is that we can only track when a build command is sent //Not when it actually starts building the building. } else { resourcesUsed = barracksType.cost * nbarracks; } if (nbarracks > 1) { buildingRacks = true; } for (Unit u : battleWorkers) { meleeUnitBehavior(u, p, gs); } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } public void rushBaseBehavior(Unit u,Player p, PhysicalGameState pgs) { if (p.getResources()>=workerType.cost) train(u, workerType); } public void rushWorkersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs, GameState gs) { int nbases = 0; int nworkers = 0; resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(); List<Unit> battleWorkers = new LinkedList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (p.getResources() == 0){ battleWorkers.addAll(workers); } else if (workers.size() > (nbases)) { for (int n = 0; n < (nbases); n++) { freeWorkers.add(workers.get(0)); workers.remove(0); } battleWorkers.addAll(workers); } else { freeWorkers.addAll(workers); } if (workers.isEmpty()) { return; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); //resourcesUsed += baseType.cost; } } for (Unit u : battleWorkers) { meleeUnitBehavior(u, p, gs); } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } public void rangedAttack(Unit u, Unit target, Unit racks) { actions.put(u, new RangedAttack(u, target, racks, pf)); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
14,780
32.823799
109
java
MicroRTS
MicroRTS-master/src/ai/abstraction/cRush/CRush_V2.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.cRush; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.AStarPathFinding; import ai.core.AI; import ai.abstraction.pathfinding.PathFinding; import ai.core.ParameterSpecification; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.units.*; /** * * @author Cristiano D'Angelo */ public class CRush_V2 extends AbstractionLayerAI { Random r = new Random(); protected UnitTypeTable utt; UnitType workerType; UnitType baseType; UnitType barracksType; UnitType rangedType; UnitType heavyType; UnitType lightType; boolean buildingRacks = false; int resourcesUsed = 0; boolean isRush = false; public CRush_V2(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public CRush_V2(UnitTypeTable a_utt, PathFinding a_pf) { super(a_pf); reset(a_utt); } public void reset() { super.reset(); } public void reset(UnitTypeTable a_utt) { utt = a_utt; workerType = utt.getUnitType("Worker"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); rangedType = utt.getUnitType("Ranged"); lightType = utt.getUnitType("Light"); } public AI clone() { return new CRush_V2(utt, pf); } public PlayerAction getAction(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Player p = gs.getPlayer(player); if ((pgs.getWidth() * pgs.getHeight()) <= 144) { isRush = true; } List<Unit> workers = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getType().canHarvest && u.getPlayer() == player) { workers.add(u); } } if (isRush) { rushWorkersBehavior(workers, p, pgs, gs); } else { workersBehavior(workers, p, pgs, gs); } // behavior of bases: for (Unit u : pgs.getUnits()) { if (u.getType() == baseType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { if (isRush) { rushBaseBehavior(u, p, pgs); } else { baseBehavior(u, p, pgs, gs); } } } // behavior of barracks: for (Unit u : pgs.getUnits()) { if (u.getType() == barracksType && u.getPlayer() == player && gs.getActionAssignment(u) == null) { barracksBehavior(u, p, pgs); } } // behavior of melee units: for (Unit u : pgs.getUnits()) { if (u.getType().canAttack && !u.getType().canHarvest && u.getPlayer() == player && gs.getActionAssignment(u) == null) { if (u.getType() == rangedType) { rangedUnitBehavior(u, p, gs); } else { meleeUnitBehavior(u, p, gs); } } } return translateActions(player, gs); } public void baseBehavior(Unit u, Player p, PhysicalGameState pgs, GameState gs) { int nbases = 0; int nbarracks = 0; int nworkers = 0; int nranged = 0; int resources = p.getResources(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == rangedType && u2.getPlayer() == p.getID()) { nranged++; } } if ((nworkers < (nbases + 1) && p.getResources() >= workerType.cost) || nranged > 6) { train(u, workerType); } //Buffers the resources that are being used for barracks if (resourcesUsed != barracksType.cost * nbarracks) { resources = resources - barracksType.cost; } if (buildingRacks && (resources >= workerType.cost + rangedType.cost)) { train(u, workerType); } } public void barracksBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= rangedType.cost) { train(u, rangedType); } } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; Unit closestRacks = null; Unit closestBase = null; Unit closestEnemyBase = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestRacks == null || d < closestDistance) { closestRacks = u2; closestDistance = d; } } if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } if (u2.getType() == baseType && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemyBase == null || d < closestDistance) { closestEnemyBase = u2; closestDistance = d; } } } if (closestEnemy != null) { if (gs.getTime() < 400 || isRush) { attack(u, closestEnemy); } else { rangedTactic(u, closestEnemy, closestBase, closestEnemyBase, utt, p); } } } public void rangedUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; Unit closestRacks = null; Unit closestBase = null; Unit closestEnemyBase = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestRacks == null || d < closestDistance) { closestRacks = u2; closestDistance = d; } } if (u2.getType() == baseType && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemyBase == null || d < closestDistance) { closestEnemyBase = u2; closestDistance = d; } } } if (closestEnemy != null) { rangedTactic(u, closestEnemy, closestBase, closestEnemyBase, utt, p); } } public void workersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs, GameState gs) { int nbases = 0; int nbarracks = 0; int nworkers = 0; resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(); List<Unit> battleWorkers = new LinkedList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == barracksType && u2.getPlayer() == p.getID()) { nbarracks++; } if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (workers.size() > (nbases + 1)) { for (int n = 0; n < (nbases + 1); n++) { freeWorkers.add(workers.get(0)); workers.remove(0); } battleWorkers.addAll(workers); } else { freeWorkers.addAll(workers); } if (workers.isEmpty()) { return; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); } } if ((nbarracks == 0) && (!freeWorkers.isEmpty()) && nworkers > 1 && p.getResources() >= barracksType.cost) { //The problem with this right now is that we can only track when a build command is sent //Not when it actually starts building the building. int resources = p.getResources(); Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, barracksType, u.getX(), u.getY(), reservedPositions, p, pgs); resourcesUsed += barracksType.cost; buildingRacks = true; } else { resourcesUsed = barracksType.cost * nbarracks; } if (nbarracks > 1) { buildingRacks = true; } for (Unit u : battleWorkers) { meleeUnitBehavior(u, p, gs); } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; Unit closestEnemyBase = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } if (u2.getType() == baseType && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemyBase == null || d < closestDistance) { closestEnemyBase = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource == null || distance(closestResource, closestEnemyBase) < distance(closestResource, closestBase)) { //Do nothing } else { if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } } public void rushBaseBehavior(Unit u, Player p, PhysicalGameState pgs) { if (p.getResources() >= workerType.cost) { train(u, workerType); } } public void rushWorkersBehavior(List<Unit> workers, Player p, PhysicalGameState pgs, GameState gs) { int nbases = 0; int nworkers = 0; resourcesUsed = 0; List<Unit> freeWorkers = new LinkedList<>(); List<Unit> battleWorkers = new LinkedList<>(); for (Unit u2 : pgs.getUnits()) { if (u2.getType() == baseType && u2.getPlayer() == p.getID()) { nbases++; } if (u2.getType() == workerType && u2.getPlayer() == p.getID()) { nworkers++; } } if (p.getResources() == 0) { battleWorkers.addAll(workers); } else if (workers.size() > (nbases)) { for (int n = 0; n < (nbases); n++) { freeWorkers.add(workers.get(0)); workers.remove(0); } battleWorkers.addAll(workers); } else { freeWorkers.addAll(workers); } if (workers.isEmpty()) { return; } List<Integer> reservedPositions = new LinkedList<>(); if (nbases == 0 && !freeWorkers.isEmpty()) { // build a base: if (p.getResources() >= baseType.cost) { Unit u = freeWorkers.remove(0); buildIfNotAlreadyBuilding(u, baseType, u.getX(), u.getY(), reservedPositions, p, pgs); } } for (Unit u : battleWorkers) { meleeUnitBehavior(u, p, gs); } // harvest with all the free workers: for (Unit u : freeWorkers) { Unit closestBase = null; Unit closestResource = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestResource == null || d < closestDistance) { closestResource = u2; closestDistance = d; } } } closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } if (closestResource != null && closestBase != null) { AbstractAction aa = getAbstractAction(u); if (aa instanceof Harvest) { Harvest h_aa = (Harvest) aa; if (h_aa.getTarget() != closestResource || h_aa.getBase() != closestBase) { harvest(u, closestResource, closestBase); } } else { harvest(u, closestResource, closestBase); } } } } public void rangedTactic(Unit u, Unit target, Unit home, Unit enemyBase, UnitTypeTable utt, Player p) { actions.put(u, new CRanged_Tactic(u, target, home, enemyBase, pf, utt, p)); } //Calculates distance between unit a and unit b public double distance(Unit a, Unit b) { if (a == null || b == null) { return 0.0; } int dx = b.getX() - a.getX(); int dy = b.getY() - a.getY(); double toReturn = Math.sqrt(dx * dx + dy * dy); return toReturn; } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("PathFinding", PathFinding.class, new AStarPathFinding())); return parameters; } }
17,612
34.155689
130
java
MicroRTS
MicroRTS-master/src/ai/abstraction/cRush/RangedAttack.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.cRush; import ai.abstraction.AbstractAction; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import util.XMLWriter; /** * * @author Cristiano D'Angelo */ public class RangedAttack extends AbstractAction { Unit target; PathFinding pf; Unit racks; UnitType workerType; UnitType rangedType; UnitType heavyType; public RangedAttack(Unit u, Unit a_target, Unit r, PathFinding a_pf) { super(u); target = a_target; pf = a_pf; racks = r; } public boolean completed(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); return !pgs.getUnits().contains(target); } public boolean equals(Object o) { if (!(o instanceof RangedAttack)) return false; RangedAttack a = (RangedAttack)o; return target.getID() == a.target.getID() && pf.getClass() == a.pf.getClass() && racks.getID() == a.racks.getID(); } public void toxml(XMLWriter w) { w.tagWithAttributes("RangedAttack","unitID=\""+getUnit().getID()+"\" target=\""+target.getID()+"\" pathfinding=\""+pf.getClass().getSimpleName()+"\" racks=\""+racks.getID()+"\""); w.tag("/RangedAttack"); } public UnitAction execute(GameState gs, ResourceUsage ru) { int rdx = 0; int rdy = 0; double rd = 0.0; if(racks != null){ rdx = racks.getX()-getUnit().getX(); rdy = racks.getY()-getUnit().getY(); rd = Math.sqrt(rdx*rdx+rdy*rdy); } int dx = target.getX()-getUnit().getX(); int dy = target.getY()-getUnit().getY(); double d = Math.sqrt(dx*dx+dy*dy); if(d <= (getUnit().getAttackRange()) - 1 && rd > 2 && getUnit().getMoveTime() < target.getMoveTime()){ UnitAction move = pf.findPathToPositionInRange(getUnit(), racks.getX()+racks.getY()*gs.getPhysicalGameState().getWidth(), getUnit().getAttackRange(), gs, ru); if (move!=null && gs.isUnitActionAllowed(getUnit(), move)) return move; return null; } else if (d<=getUnit().getAttackRange()) { return new UnitAction(UnitAction.TYPE_ATTACK_LOCATION,target.getX(),target.getY()); } else { // move towards the unit: // System.out.println("AStarAttak returns: " + move); UnitAction move = pf.findPathToPositionInRange(getUnit(), target.getX()+target.getY()*gs.getPhysicalGameState().getWidth(), getUnit().getAttackRange(), gs, ru); if (move!=null && gs.isUnitActionAllowed(getUnit(), move)) return move; return null; } } }
2,989
31.857143
187
java
MicroRTS
MicroRTS-master/src/ai/abstraction/partialobservability/POHeavyRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.partialobservability; import ai.abstraction.HeavyRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.Player; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author santi */ public class POHeavyRush extends HeavyRush { public POHeavyRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public POHeavyRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_utt, a_pf); } public void reset() { super.reset(); } public AI clone() { return new POHeavyRush(utt, pf); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } else if (gs instanceof PartiallyObservableGameState) { PartiallyObservableGameState pogs = (PartiallyObservableGameState)gs; // there are no enemies, so we need to explore (find the nearest non-observable place): int closest_x = 0; int closest_y = 0; closestDistance = -1; for(int i = 0;i<pgs.getHeight();i++) { for(int j = 0;j<pgs.getWidth();j++) { if (!pogs.observable(j, i)) { int d = (u.getX() - j)*(u.getX() - j) + (u.getY() - i)*(u.getY() - i); if (closestDistance == -1 || d<closestDistance) { closest_x = j; closest_y = i; closestDistance = d; } } } } if (closestDistance!=-1) { move(u, closest_x, closest_y); } } } }
2,612
30.865854
99
java
MicroRTS
MicroRTS-master/src/ai/abstraction/partialobservability/POLightRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.partialobservability; import ai.abstraction.LightRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.Player; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author santi */ public class POLightRush extends LightRush { public POLightRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public POLightRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_utt, a_pf); } public void reset() { super.reset(); } public AI clone() { return new POLightRush(utt, pf); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } else if (gs instanceof PartiallyObservableGameState) { PartiallyObservableGameState pogs = (PartiallyObservableGameState)gs; // there are no enemies, so we need to explore (find the nearest non-observable place): int closest_x = 0; int closest_y = 0; closestDistance = -1; for(int i = 0;i<pgs.getHeight();i++) { for(int j = 0;j<pgs.getWidth();j++) { if (!pogs.observable(j, i)) { int d = (u.getX() - j)*(u.getX() - j) + (u.getY() - i)*(u.getY() - i); if (closestDistance == -1 || d<closestDistance) { closest_x = j; closest_y = i; closestDistance = d; } } } } if (closestDistance!=-1) { move(u, closest_x, closest_y); } } } }
2,612
30.865854
99
java
MicroRTS
MicroRTS-master/src/ai/abstraction/partialobservability/PORangedRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.partialobservability; import ai.abstraction.RangedRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.Player; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author santi */ public class PORangedRush extends RangedRush { public PORangedRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public PORangedRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_utt, a_pf); } public void reset() { super.reset(); } public AI clone() { return new PORangedRush(utt, pf); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } else if (gs instanceof PartiallyObservableGameState) { PartiallyObservableGameState pogs = (PartiallyObservableGameState)gs; // there are no enemies, so we need to explore (find the nearest non-observable place): int closest_x = 0; int closest_y = 0; closestDistance = -1; for(int i = 0;i<pgs.getHeight();i++) { for(int j = 0;j<pgs.getWidth();j++) { if (!pogs.observable(j, i)) { int d = (u.getX() - j)*(u.getX() - j) + (u.getY() - i)*(u.getY() - i); if (closestDistance == -1 || d<closestDistance) { closest_x = j; closest_y = i; closestDistance = d; } } } } if (closestDistance!=-1) { move(u, closest_x, closest_y); } } } }
2,618
30.939024
99
java
MicroRTS
MicroRTS-master/src/ai/abstraction/partialobservability/POWorkerRush.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.partialobservability; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.core.AI; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.Player; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author santi */ public class POWorkerRush extends WorkerRush { public POWorkerRush(UnitTypeTable a_utt) { this(a_utt, new AStarPathFinding()); } public POWorkerRush(UnitTypeTable a_utt, PathFinding a_pf) { super(a_utt, a_pf); } public void reset() { super.reset(); } public AI clone() { return new POWorkerRush(utt, pf); } public void meleeUnitBehavior(Unit u, Player p, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != p.getID()) { int d = Math.abs(u2.getX() - u.getX()) + Math.abs(u2.getY() - u.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } if (closestEnemy != null) { attack(u, closestEnemy); } else if (gs instanceof PartiallyObservableGameState) { PartiallyObservableGameState pogs = (PartiallyObservableGameState)gs; // there are no enemies, so we need to explore (find the nearest non-observable place): int closest_x = 0; int closest_y = 0; closestDistance = -1; for(int i = 0;i<pgs.getHeight();i++) { for(int j = 0;j<pgs.getWidth();j++) { if (!pogs.observable(j, i)) { int d = (u.getX() - j)*(u.getX() - j) + (u.getY() - i)*(u.getY() - i); if (closestDistance == -1 || d<closestDistance) { closest_x = j; closest_y = i; closestDistance = d; } } } } if (closestDistance!=-1) { move(u, closest_x, closest_y); } } } }
2,618
30.939024
99
java
MicroRTS
MicroRTS-master/src/ai/abstraction/pathfinding/AStarPathFinding.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.pathfinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; /** * * @author santi * * A* pathfinding. * * The code looks a bit weird, since this version of A* uses static data structures to avoid any * memory allocation penalty. It only reallocates memory when asked to path-find for first time, * or in a map that is bigger than the previous time. * */ public class AStarPathFinding extends PathFinding { public static int iterations = 0; // this is a debugging variable public static int accumlength = 0; // this is a debugging variable Boolean free[][]; int closed[]; int open[]; // open list int heuristic[]; // heuristic value of the elements in 'open' int parents[]; int cost[]; // cost of reaching a given position so far int inOpenOrClosed[]; int openinsert = 0; // This fucntion finds the shortest path from 'start' to 'targetpos' and then returns // a UnitAction of the type 'actionType' with the direction of the first step in the shorteet path public UnitAction findPath(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start,targetpos,0,gs,ru); } /* * This function is like the previous one, but doesn't try to reach 'target', but just to * reach a position that is at most 'range' far away from 'target' */ public UnitAction findPathToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); int w = pgs.getWidth(); int h = pgs.getHeight(); if (free==null || free.length<w*h) { free = new Boolean[w][h]; closed = new int[w*h]; open = new int[w*h]; heuristic = new int[w*h]; parents = new int[w*h]; inOpenOrClosed = new int[w*h]; cost = new int[w*h]; } for(int y = 0, i = 0;y<h;y++) { for(int x = 0;x<w;x++,i++) { free[x][y] = null; closed[i] = -1; inOpenOrClosed[i] = 0; } } if (ru!=null) { for(int pos:ru.getPositionsUsed()) { free[pos%w][pos/w] = false; } } int targetx = targetpos%w; int targety = targetpos/w; int sq_range = range*range; int startPos = start.getY()*w + start.getX(); assert(targetx>=0); assert(targetx<w); assert(targety>=0); assert(targety<h); assert(start.getX()>=0); assert(start.getX()<w); assert(start.getY()>=0); assert(start.getY()<h); openinsert = 0; open[openinsert] = startPos; heuristic[openinsert] = manhattanDistance(start.getX(), start.getY(), targetx, targety); parents[openinsert] = startPos; inOpenOrClosed[startPos] = 1; cost[startPos] = 0; openinsert++; // System.out.println("Looking for path from: " + start.getX() + "," + start.getY() + " to " + targetx + "," + targety); while(openinsert>0) { // debugging code: /* System.out.println("open: "); for(int i = 0;i<openinsert;i++) { System.out.print(" [" + (open[i]%w) + "," + (open[i]/w) + " -> "+ cost[open[i]] + "+" + heuristic[i] + "]"); } System.out.println(""); for(int i = 0;i<h;i++) { for(int j = 0;j<w;j++) { if (j==start.getX() && i==start.getY()) { System.out.print("s"); } else if (j==targetx && i==targety) { System.out.print("t"); } else if (!free[j][i]) { System.out.print("X"); } else { if (inOpenOrClosed[j+i*w]==0) { System.out.print("."); } else { System.out.print("o"); } } } System.out.println(""); } */ iterations++; openinsert--; int pos = open[openinsert]; int parent = parents[openinsert]; if (closed[pos]!=-1) continue; closed[pos] = parent; int x = pos%w; int y = pos/w; if (((x-targetx)*(x-targetx)+(y-targety)*(y-targety))<=sq_range) { // path found, backtrack: int last = pos; // System.out.println("- Path from " + start.getX() + "," + start.getY() + " to " + targetpos%w + "," + targetpos/w + " (range " + range + ") in " + iterations + " iterations"); while(parent!=pos) { last = pos; pos = parent; parent = closed[pos]; accumlength++; // System.out.println(" " + pos%w + "," + pos/w); } if (last == pos+w) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_DOWN); if (last == pos-1) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_LEFT); if (last == pos-w) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_UP); if (last == pos+1) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_RIGHT); return null; } if (y>0 && inOpenOrClosed[pos-w] == 0) { if (free[x][y-1]==null) free[x][y-1]=gs.free(x, y-1); assert(free[x][y-1]!=null); if (free[x][y-1]) { addToOpen(x,y-1,pos-w,pos,manhattanDistance(x, y-1, targetx, targety)); } } if (x<pgs.getWidth()-1 && inOpenOrClosed[pos+1] == 0) { if (free[x+1][y]==null) free[x+1][y]=gs.free(x+1, y); assert(free[x+1][y]!=null); if (free[x+1][y]) { addToOpen(x+1,y,pos+1,pos,manhattanDistance(x+1, y, targetx, targety)); } } if (y<pgs.getHeight()-1 && inOpenOrClosed[pos+w] == 0) { if (free[x][y+1]==null) free[x][y+1]=gs.free(x, y+1); assert(free[x][y+1]!=null); if (free[x][y+1]) { addToOpen(x,y+1,pos+w,pos,manhattanDistance(x, y+1, targetx, targety)); } } if (x>0 && inOpenOrClosed[pos-1] == 0) { if (free[x-1][y]==null) free[x-1][y]=gs.free(x-1, y); assert(free[x-1][y]!=null); if (free[x-1][y]) { addToOpen(x-1,y,pos-1,pos,manhattanDistance(x-1, y, targetx, targety)); } } } return null; } /* * This function is like the previous one, but doesn't try to reach 'target', but just to * reach a position adjacent to 'target' */ public UnitAction findPathToAdjacentPosition(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start, targetpos, 1, gs, ru); } public boolean pathExists(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return start.getPosition(gs.getPhysicalGameState()) == targetpos || findPath(start, targetpos, gs, ru) != null; } public boolean pathToPositionInRangeExists(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { int x = targetpos%gs.getPhysicalGameState().getWidth(); int y = targetpos/gs.getPhysicalGameState().getWidth(); int d = (x-start.getX())*(x-start.getX()) + (y-start.getY())*(y-start.getY()); return d <= range * range || findPathToPositionInRange(start, targetpos, range, gs, ru) != null; } // and keep the "open" list sorted: void addToOpen(int x, int y, int newPos, int oldPos, int h) { cost[newPos] = cost[oldPos]+1; // find the right position for the insert: for(int i = openinsert-1;i>=0;i--) { if (heuristic[i]+cost[open[i]]>=h+cost[newPos]) { // System.out.println("Inserting at " + (i+1) + " / " + openinsert); // shift all the elements: for(int j = openinsert;j>=i+1;j--) { open[j] = open[j-1]; heuristic[j] = heuristic[j-1]; parents[j] = parents[j-1]; } // insert at i+1: open[i+1] = newPos; heuristic[i+1] = h; parents[i+1] = oldPos; openinsert++; inOpenOrClosed[newPos] = 1; return; } } // i = -1; // System.out.println("Inserting at " + 0 + " / " + openinsert); // shift all the elements: for(int j = openinsert;j>=1;j--) { open[j] = open[j-1]; heuristic[j] = heuristic[j-1]; parents[j] = parents[j-1]; } // insert at i+1: open[0] = newPos; heuristic[0] = h; parents[0] = oldPos; openinsert++; inOpenOrClosed[newPos] = 1; } int manhattanDistance(int x, int y, int x2, int y2) { return Math.abs(x-x2) + Math.abs(y-y2); } public int findDistToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); int w = pgs.getWidth(); int h = pgs.getHeight(); if (free==null || free.length<w*h) { free = new Boolean[pgs.getWidth()][pgs.getHeight()]; closed = new int[pgs.getWidth()*pgs.getHeight()]; open = new int[pgs.getWidth()*pgs.getHeight()]; heuristic = new int[pgs.getWidth()*pgs.getHeight()]; parents = new int[pgs.getWidth()*pgs.getHeight()]; inOpenOrClosed = new int[pgs.getWidth()*pgs.getHeight()]; cost = new int[pgs.getWidth()*pgs.getHeight()]; } for(int y = 0, i = 0;y<pgs.getHeight();y++) { for(int x = 0;x<w;x++,i++) { free[x][y] = null; closed[i] = -1; inOpenOrClosed[i] = 0; } } if (ru!=null) { for(int pos:ru.getPositionsUsed()) { free[pos%w][pos/w] = false; } } int targetx = targetpos%w; int targety = targetpos/w; int sq_range = range*range; int startPos = start.getY()*w + start.getX(); assert(targetx>=0); assert(targetx<w); assert(targety>=0); assert(targety<h); assert(start.getX()>=0); assert(start.getX()<w); assert(start.getY()>=0); assert(start.getY()<h); openinsert = 0; open[openinsert] = startPos; heuristic[openinsert] = manhattanDistance(start.getX(), start.getY(), targetx, targety); parents[openinsert] = startPos; inOpenOrClosed[startPos] = 1; cost[startPos] = 0; openinsert++; // System.out.println("Looking for path from: " + start.getX() + "," + start.getY() + " to " + targetx + "," + targety); while(openinsert>0) { // debugging code: /* System.out.println("open: "); for(int i = 0;i<openinsert;i++) { System.out.print(" [" + (open[i]%w) + "," + (open[i]/w) + " -> "+ cost[open[i]] + "+" + heuristic[i] + "]"); } System.out.println(""); for(int i = 0;i<h;i++) { for(int j = 0;j<w;j++) { if (j==start.getX() && i==start.getY()) { System.out.print("s"); } else if (j==targetx && i==targety) { System.out.print("t"); } else if (!free[j][i]) { System.out.print("X"); } else { if (inOpenOrClosed[j+i*w]==0) { System.out.print("."); } else { System.out.print("o"); } } } System.out.println(""); } */ iterations++; openinsert--; int pos = open[openinsert]; int parent = parents[openinsert]; if (closed[pos]!=-1) continue; closed[pos] = parent; int x = pos%w; int y = pos/w; if (((x-targetx)*(x-targetx)+(y-targety)*(y-targety))<=sq_range) { // path found, backtrack: //System.out.println("- Path from " + start.getX() + "," + start.getY() + " to " + targetpos%w + "," + targetpos/w + " (range " + range + ") in " + iterations + " iterations"); int temp = 0; while(parent!=pos) { pos = parent; parent = closed[pos]; accumlength++; temp++; //System.out.println(" " + pos%w + "," + pos/w); } return temp; } if (y>0 && inOpenOrClosed[pos-w] == 0) { if (free[x][y-1]==null) free[x][y-1]=gs.free(x, y-1); assert(free[x][y-1]!=null); if (free[x][y-1]) { addToOpen(x,y-1,pos-w,pos,manhattanDistance(x, y-1, targetx, targety)); } } if (x<pgs.getWidth()-1 && inOpenOrClosed[pos+1] == 0) { if (free[x+1][y]==null) free[x+1][y]=gs.free(x+1, y); assert(free[x+1][y]!=null); if (free[x+1][y]) { addToOpen(x+1,y,pos+1,pos,manhattanDistance(x+1, y, targetx, targety)); } } if (y<pgs.getHeight()-1 && inOpenOrClosed[pos+w] == 0) { if (free[x][y+1]==null) free[x][y+1]=gs.free(x, y+1); assert(free[x][y+1]!=null); if (free[x][y+1]) { addToOpen(x,y+1,pos+w,pos,manhattanDistance(x, y+1, targetx, targety)); } } if (x>0 && inOpenOrClosed[pos-1] == 0) { if (free[x-1][y]==null) free[x-1][y]=gs.free(x-1, y); assert(free[x-1][y]!=null); if (free[x-1][y]) { addToOpen(x-1,y,pos-1,pos,manhattanDistance(x-1, y, targetx, targety)); } } } return -1; } }
15,228
38.762402
192
java
MicroRTS
MicroRTS-master/src/ai/abstraction/pathfinding/BFSPathFinding.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.pathfinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; /** * * @author santi */ public class BFSPathFinding extends PathFinding { public static int iterations = 0; // this is a debugging variable public static int accumlength = 0; // this is a debugging variable Boolean free[][]; int closed[]; int open[]; int inOpenOrClosed[]; int parents[]; int openinsert = 0; int openremove = 0; // This fucntion finds the shortest path from 'start' to 'targetpos' and then returns // a UnitAction of the type 'actionType' with the direction of the first step in the shorteet path public UnitAction findPath(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start,targetpos,0,gs,ru); } /* * This function is like the previous one, but doesn't try to reach 'target', but just to * reach a position that is at most 'range' far away from 'target' */ public UnitAction findPathToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); int w = pgs.getWidth(); int h = pgs.getHeight(); if (free==null || free.length<w*h) { free = new Boolean[pgs.getWidth()][pgs.getHeight()]; closed = new int[pgs.getWidth()*pgs.getHeight()]; open = new int[pgs.getWidth()*pgs.getHeight()]; inOpenOrClosed = new int[pgs.getWidth()*pgs.getHeight()]; parents = new int[pgs.getWidth()*pgs.getHeight()]; } for(int y = 0, i = 0;y<pgs.getHeight();y++) { for(int x = 0;x<w;x++,i++) { free[x][y] = null; closed[i] = -1; inOpenOrClosed[i] = 0; } } if (ru!=null) { for(int pos:ru.getPositionsUsed()) { free[pos%w][pos/w] = false; } } int targetx = targetpos%w; int targety = targetpos/w; int sq_range = range*range; int startPos = start.getY()*w + start.getX(); openinsert = 0; openremove = 0; open[openinsert] = startPos; parents[openinsert] = startPos; inOpenOrClosed[startPos] = 1; openinsert++; while(openinsert!=openremove) { iterations++; int pos = open[openremove]; int parent = parents[openremove]; openremove++; if (openremove>=open.length) openremove = 0; if (closed[pos]!=-1) continue; closed[pos] = parent; int x = pos%w; int y = pos/w; if (((x-targetx)*(x-targetx)+(y-targety)*(y-targety))<=sq_range) { // path found, backtrack: int last = pos; // System.out.println("- Path from " + start.getX() + "," + start.getY() + " to " + targetpos%w + "," + targetpos/w + " (range " + range + ")"); while(parent!=pos) { last = pos; pos = parent; parent = closed[pos]; accumlength++; // System.out.println(" " + pos%w + "," + pos/w); } if (last == pos+w) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_DOWN); if (last == pos-1) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_LEFT); if (last == pos-w) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_UP); if (last == pos+1) return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_RIGHT); return null; } if (y>0 && inOpenOrClosed[pos-w] == 0) { if (free[x][y-1]==null) free[x][y-1]=gs.free(x, y-1); if (free[x][y-1]) { open[openinsert] = (pos-w); parents[openinsert] = (pos); openinsert++; if (openinsert>=open.length) openinsert = 0; inOpenOrClosed[pos-w] = 1; } } if (x<pgs.getWidth()-1 && inOpenOrClosed[pos+1] == 0) { if (free[x+1][y]==null) free[x+1][y]=gs.free(x+1, y); if (free[x+1][y]) { open[openinsert] = (pos+1); parents[openinsert] = (pos); openinsert++; if (openinsert>=open.length) openinsert = 0; inOpenOrClosed[pos+1] = 1; } } if (y<pgs.getHeight()-1 && inOpenOrClosed[pos+w] == 0) { if (free[x][y+1]==null) free[x][y+1]=gs.free(x, y+1); if (free[x][y+1]) { open[openinsert] = (pos+w); parents[openinsert] = (pos); openinsert++; if (openinsert>=open.length) openinsert = 0; inOpenOrClosed[pos+w] = 1; } } if (x>0 && inOpenOrClosed[pos-1] == 0) { if (free[x-1][y]==null) free[x-1][y]=gs.free(x-1, y); if (free[x-1][y]) { open[openinsert] = (pos-1); parents[openinsert] = (pos); openinsert++; if (openinsert>=open.length) openinsert = 0; inOpenOrClosed[pos-1] = 1; } } } return null; } /* * This function is like the previous one, but doesn't try to reach 'target', but just to * reach a position adjacent to 'target' */ public UnitAction findPathToAdjacentPosition(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start, targetpos, 1, gs, ru); } public boolean pathExists(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return start.getPosition(gs.getPhysicalGameState()) == targetpos || findPath(start, targetpos, gs, ru) != null; } public boolean pathToPositionInRangeExists(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { int x = targetpos%gs.getPhysicalGameState().getWidth(); int y = targetpos/gs.getPhysicalGameState().getWidth(); int d = (x-start.getX())*(x-start.getX()) + (y-start.getY())*(y-start.getY()); return d <= range * range || findPathToPositionInRange(start, targetpos, range, gs, ru) != null; } }
6,906
39.156977
159
java
MicroRTS
MicroRTS-master/src/ai/abstraction/pathfinding/FloodFillPathFinding.java
package ai.abstraction.pathfinding; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.Pair; public class FloodFillPathFinding extends PathFinding { PathFinding altPF=new AStarPathFinding(); private static final int ALT_THRESHOLD = 0; HashMap<Integer,int[][]> cache= new HashMap<>(); boolean free[][]; int distances[][]; int w,h; int lastFrame=-1; @Override public boolean pathExists(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return start.getPosition(gs.getPhysicalGameState()) == targetpos || findPath(start, targetpos, gs, ru) != null; } @Override public boolean pathToPositionInRangeExists(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { int x = targetpos%gs.getPhysicalGameState().getWidth(); int y = targetpos/gs.getPhysicalGameState().getWidth(); int d = (x-start.getX())*(x-start.getX()) + (y-start.getY())*(y-start.getY()); return d <= range * range || findPathToPositionInRange(start, targetpos, range, gs, ru) != null; } @Override public UnitAction findPath(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start,targetpos,0,gs,ru); } private boolean bounds(int x, int y){ return x>=0&&y>=0&&x<w&&y<h; } private void doFloodFill(int x, int y, GameState gs, int finalX, int finalY){ assert(distances[x][y]!=Integer.MAX_VALUE); boolean gsFree[][]=gs.getAllFree(); int index=0; ArrayList<Pair<Integer,Integer>> fringe= new ArrayList<>(h * w); fringe.add(new Pair<>(x, y)); boolean reached=false; while(index<fringe.size()){ x=fringe.get(index).m_a; y=fringe.get(index).m_b; //left int nextX=x-1; int nextY=y; if(nextX==finalX&&nextY==finalY)reached=true; if(bounds(nextX,nextY)&&distances[nextX][nextY]==Integer.MAX_VALUE&&free[nextX][nextY]&&gsFree[nextX][nextY]){ distances[nextX][nextY]=distances[x][y]+1; fringe.add(new Pair<>(nextX, nextY)); } //up nextX=x; nextY=y-1; if(nextX==finalX&&nextY==finalY)reached=true; if(bounds(nextX,nextY)&&distances[nextX][nextY]==Integer.MAX_VALUE&&free[nextX][nextY]&&gsFree[nextX][nextY]){ distances[nextX][nextY]=distances[x][y]+1; fringe.add(new Pair<>(nextX, nextY)); } //right nextX=x+1; nextY=y; if(nextX==finalX&&nextY==finalY)reached=true; if(bounds(nextX,nextY)&&distances[nextX][nextY]==Integer.MAX_VALUE&&free[nextX][nextY]&&gsFree[nextX][nextY]){ distances[nextX][nextY]=distances[x][y]+1; fringe.add(new Pair<>(nextX, nextY)); } //down nextX=x; nextY=y+1; if(nextX==finalX&&nextY==finalY)reached=true; if(bounds(nextX,nextY)&&distances[nextX][nextY]==Integer.MAX_VALUE&&free[nextX][nextY]&&gsFree[nextX][nextY]){ distances[nextX][nextY]=distances[x][y]+1; fringe.add(new Pair<>(nextX, nextY)); } if(reached){ // System.out.println("breaking early"); break; } index++; } } private UnitAction calculateDistances(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru){ int x=targetpos%w; int y= targetpos/w; if(Math.abs(start.getX()-x) +Math.abs(start.getY()-y) <= ALT_THRESHOLD){ return altPF.findPathToPositionInRange(start, targetpos, range, gs, ru); } // if (distances==null || distances.length<w || distances[0].length<h) { distances = new int[w][h]; // } for (int[] row: distances){ Arrays.fill(row, Integer.MAX_VALUE); } distances[x][y]=0; doFloodFill(x, y, gs, start.getX(), start.getY()); cache.put(targetpos, distances); return getAction(start); } private void initFree( GameState gs, ResourceUsage ru){ if (free==null || free.length<w || free[0].length<h) { free = new boolean[w][h]; } for(boolean row[]:free){ Arrays.fill(row, true); } if (ru!=null) { for(int pos:ru.getPositionsUsed()) { free[pos%w][pos/w] = false; } } } private UnitAction getAction(Unit start){ int x=start.getX(); int y=start.getY(); int dists[]={bounds(x-1,y)?distances[x-1][y]:Integer.MAX_VALUE, bounds(x,y-1)?distances[x][y-1]:Integer.MAX_VALUE, bounds(x+1,y)?distances[x+1][y]:Integer.MAX_VALUE, bounds(x,y+1)?distances[x][y+1]:Integer.MAX_VALUE}; int index=0,min=dists[0]; for(int i=1;i<dists.length;i++){ if(dists[i]<min){ index=i; min=dists[i]; } } if(min==Integer.MAX_VALUE){ return null; } switch(index){ case 0: return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_LEFT); case 1: return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_UP); case 2: return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_RIGHT); case 3: return new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_DOWN); } return null; } //this is not necessarily correct. Following the shortest path to a specific location and stopping when //in range is not the same as getting the shortest path to any position in range. @Override public UnitAction findPathToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { // System.out.println(range); PhysicalGameState pgs = gs.getPhysicalGameState(); w = pgs.getWidth(); h = pgs.getHeight(); int x=targetpos%w; int y= targetpos/w; // System.out.print(x+" "+y+" "); if((start.getX()-x)*(start.getX()-x) +(start.getY()-y)*(start.getY()-y) <= range*range){//already there // System.out.println("Already in range"); return null; } if(gs.getTime()<lastFrame){//new game cache.clear(); // System.out.println("Removed, new game"); } lastFrame=gs.getTime(); initFree(gs,ru); if(cache.containsKey(targetpos)){ distances=cache.get(targetpos); UnitAction action=getAction(start); if(action!=null){ ResourceUsage r=action.resourceUsage(start, pgs); for(int pos:r.getPositionsUsed()){ if(!free[pos%w][pos/w]||!gs.free(pos%w, pos/w)){ cache.remove(targetpos); // System.out.println("In cache, invalid, calculating"); return calculateDistances(start, targetpos, range,gs,ru); } } }else{ // System.out.println("found null action"); //this is to fix cases where there used to be no path to get somewhere, but now there is cache.remove(targetpos); return calculateDistances(start, targetpos, range,gs,ru); } // System.out.println("In cache, OK"); return action; }else{ // System.out.println("Not in cache, calculating"); return calculateDistances(start, targetpos,range,gs,ru); } } @Override public UnitAction findPathToAdjacentPosition(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start, targetpos, 1, gs, ru); } }
6,944
30.712329
116
java
MicroRTS
MicroRTS-master/src/ai/abstraction/pathfinding/GreedyPathFinding.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.pathfinding; import rts.GameState; import rts.PhysicalGameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; /** * * @author santi */ public class GreedyPathFinding extends PathFinding { public UnitAction findPath(Unit start, int targetpos, GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); int w = pgs.getWidth(); int dx[] = { 0, 1, 0,-1}; int dy[] = {-1, 0, 1, 0}; int x1 = start.getX(); int y1 = start.getY(); int x2 = targetpos%pgs.getWidth(); int y2 = targetpos/pgs.getWidth(); int min_d = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1); int direction = -1; for(int i = 0;i<dx.length;i++) { int x = x1 + dx[i]; int y = y1 + dy[i]; if (x>=0 && x<pgs.getWidth() && y>=0 && y<pgs.getHeight() && gs.free(x,y)) { if (ru!=null && ru.getPositionsUsed().contains(x+y*w)) continue; int d = (x2 - x)*(x2 - x) + (y2 - y)*(y2 - y); if (direction==-1 || d<min_d) { min_d = d; direction = i; } } } // System.out.println("Going " + direction + " from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")"); if (direction==-1) return null; return new UnitAction(UnitAction.TYPE_MOVE, direction); } // In this greedy algorithm, both functions are implemented identically: public UnitAction findPathToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { PhysicalGameState pgs = gs.getPhysicalGameState(); int w = pgs.getWidth(); int dx[] = { 0, 1, 0,-1}; int dy[] = {-1, 0, 1, 0}; int x1 = start.getX(); int y1 = start.getY(); int x2 = targetpos%pgs.getWidth(); int y2 = targetpos/pgs.getWidth(); int min_d = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1); int direction = -1; if (min_d <= range) return null; // we are already in range! for(int i = 0;i<dx.length;i++) { int x = x1 + dx[i]; int y = y1 + dy[i]; if (x>=0 && x<pgs.getWidth() && y>=0 && y<pgs.getHeight() && gs.free(x,y)) { if (ru!=null && ru.getPositionsUsed().contains(x+y*w)) continue; int d = (x2 - x)*(x2 - x) + (y2 - y)*(y2 - y); if (direction==-1 || d<min_d) { min_d = d; direction = i; } } } // System.out.println("Going " + direction + " from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")"); if (direction==-1) return null; return new UnitAction(UnitAction.TYPE_MOVE, direction); } public UnitAction findPathToAdjacentPosition(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return findPathToPositionInRange(start, targetpos, 1, gs, ru); } public boolean pathExists(Unit start, int targetpos, GameState gs, ResourceUsage ru) { return start.getPosition(gs.getPhysicalGameState()) == targetpos || findPath(start, targetpos, gs, ru) != null; } public boolean pathToPositionInRangeExists(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru) { int x = targetpos%gs.getPhysicalGameState().getWidth(); int y = targetpos/gs.getPhysicalGameState().getWidth(); int d = (x-start.getX())*(x-start.getX()) + (y-start.getY())*(y-start.getY()); return d <= range * range || findPathToPositionInRange(start, targetpos, range, gs, ru) != null; } }
4,031
34.681416
119
java
MicroRTS
MicroRTS-master/src/ai/abstraction/pathfinding/PathFinding.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.abstraction.pathfinding; import rts.GameState; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; /** * * @author santi */ public abstract class PathFinding { public abstract boolean pathExists(Unit start, int targetpos, GameState gs, ResourceUsage ru); public abstract boolean pathToPositionInRangeExists(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru); public abstract UnitAction findPath(Unit start, int targetpos, GameState gs, ResourceUsage ru); public abstract UnitAction findPathToPositionInRange(Unit start, int targetpos, int range, GameState gs, ResourceUsage ru); public abstract UnitAction findPathToAdjacentPosition(Unit start, int targetpos, GameState gs, ResourceUsage ru); public String toString() { return getClass().getSimpleName(); } }
951
34.259259
127
java
MicroRTS
MicroRTS-master/src/ai/ahtn/AHTNAI.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn; import ai.abstraction.WorkerRush; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.UnitAction; import rts.units.Unit; import util.Pair; import ai.ahtn.domain.DomainDefinition; import ai.ahtn.domain.MethodDecomposition; import ai.ahtn.domain.PredefinedOperators; import ai.ahtn.domain.Term; import ai.ahtn.planner.AdversarialBoundedDepthPlannerAlphaBeta; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ParameterSpecification; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction3; import java.util.ArrayList; import rts.units.UnitTypeTable; /** * * @author santi * */ public class AHTNAI extends AIWithComputationBudget { public static int DEBUG = 0; String domainFileName; DomainDefinition dd; EvaluationFunction ef; AI playoutAI; public int PLAYOUT_LOOKAHEAD = 100; List<MethodDecomposition> actionsBeingExecuted; public AHTNAI(UnitTypeTable utt) throws Exception { this("data/ahtn/microrts-ahtn-definition-flexible-single-target-portfolio.lisp", 100, -1, 100, new SimpleSqrtEvaluationFunction3(), new WorkerRush(utt)); } public AHTNAI(String a_domainFileName, int available_time, int max_playouts, int playoutLookahead, EvaluationFunction a_ef, AI a_playoutAI) throws Exception { super(available_time, max_playouts); domainFileName = a_domainFileName; dd = DomainDefinition.fromLispFile(domainFileName); PLAYOUT_LOOKAHEAD = playoutLookahead; ef = a_ef; playoutAI = a_playoutAI; actionsBeingExecuted = new LinkedList<>(); } public void reset() { actionsBeingExecuted = new LinkedList<>(); AdversarialBoundedDepthPlannerAlphaBeta.clearStatistics(); } public PlayerAction getAction(int player, GameState gs) throws Exception { Term goal1 = Term.fromString("(destroy-player "+player+" "+(1-player)+")"); Term goal2 = Term.fromString("(destroy-player "+(1-player)+" "+player+")"); if (gs.canExecuteAnyAction(player)) { Pair<MethodDecomposition,MethodDecomposition> plan = AdversarialBoundedDepthPlannerAlphaBeta.getBestPlanIterativeDeepening(goal1, goal2, player, TIME_BUDGET, ITERATIONS_BUDGET, PLAYOUT_LOOKAHEAD, gs, dd, ef, playoutAI); PlayerAction pa = new PlayerAction(); if (plan!=null) { MethodDecomposition toExecute = plan.m_a; List<Pair<Integer,List<Term>>> l = (toExecute!=null ? toExecute.convertToOperatorList():new LinkedList<>()); if (DEBUG>=1) { List<Pair<Integer,List<Term>>> l2 = (plan.m_b!=null ? plan.m_b.convertToOperatorList():new LinkedList<>()); System.out.println("---- ---- ---- ----"); System.out.println(gs); System.out.println("Max plan:"); for(Pair<Integer, List<Term>> a:l) System.out.println(" " + a.m_a + ": " + a.m_b); System.out.println("Min plan:"); for(Pair<Integer, List<Term>> a:l2) System.out.println(" " + a.m_a + ": " + a.m_b); } if (DEBUG>=2) { System.out.println("Detailed Max plan:"); plan.m_a.printDetailed(); } actionsBeingExecuted.clear(); while(!l.isEmpty()) { Pair<Integer,List<Term>> tmp = l.remove(0); if (tmp.m_a!=gs.getTime()) break; List<Term> actions = tmp.m_b; for(Term action:actions) { MethodDecomposition md = new MethodDecomposition(action); actionsBeingExecuted.add(md); } } } if (DEBUG>=1) { System.out.println("Actions being executed:"); for(MethodDecomposition md:actionsBeingExecuted) { System.out.println(" " + md.getTerm()); } } List<MethodDecomposition> toDelete = new LinkedList<>(); for(MethodDecomposition md:actionsBeingExecuted) { if (PredefinedOperators.execute(md, gs, pa)) toDelete.add(md); for(Pair<Unit,UnitAction> ua:pa.getActions()) { if (gs.getUnit(ua.m_a.getID())==null) { pa.removeUnitAction(ua.m_a, ua.m_b); } } } actionsBeingExecuted.removeAll(toDelete); if (DEBUG>=1) { System.out.println("Result in the following unit actions:"); System.out.println(" " + pa); } pa.fillWithNones(gs, player, 10); return pa; } else { return new PlayerAction(); } } @Override public AI clone() { try { return new AHTNAI(domainFileName, TIME_BUDGET, ITERATIONS_BUDGET, PLAYOUT_LOOKAHEAD, ef, playoutAI); }catch(Exception e) { e.printStackTrace(); return null; } } @Override public String toString() { return getClass().getSimpleName() + "(" + domainFileName + ", " + TIME_BUDGET + ", " + ITERATIONS_BUDGET + ", " + PLAYOUT_LOOKAHEAD + ", " + ef + ", " + playoutAI + ")"; } public String statisticsString() { return "Max depth: " + AdversarialBoundedDepthPlannerAlphaBeta.max_iterative_deepening_depth + ", Average depth: " + (AdversarialBoundedDepthPlannerAlphaBeta.average_iterative_deepening_depth/AdversarialBoundedDepthPlannerAlphaBeta.n_iterative_deepening_runs) + ", Max tree leaves: " + AdversarialBoundedDepthPlannerAlphaBeta.max_tree_leaves + ", Average tree leaves: " + (AdversarialBoundedDepthPlannerAlphaBeta.average_tree_leaves/AdversarialBoundedDepthPlannerAlphaBeta.n_trees) + ", Max tree nodes: " + AdversarialBoundedDepthPlannerAlphaBeta.max_tree_nodes + ", Average tree nodes: " + (AdversarialBoundedDepthPlannerAlphaBeta.average_tree_nodes/AdversarialBoundedDepthPlannerAlphaBeta.n_trees) + ", Max tree depth: " + AdversarialBoundedDepthPlannerAlphaBeta.max_tree_depth + ", Average tree depth: " + (AdversarialBoundedDepthPlannerAlphaBeta.average_tree_depth/AdversarialBoundedDepthPlannerAlphaBeta.n_trees) + ", Max time depth: " + AdversarialBoundedDepthPlannerAlphaBeta.max_time_depth + ", Average time depth: " + (AdversarialBoundedDepthPlannerAlphaBeta.average_time_depth/AdversarialBoundedDepthPlannerAlphaBeta.n_trees); } @Override public List<ParameterSpecification> getParameters() { List<ParameterSpecification> parameters = new ArrayList<>(); parameters.add(new ParameterSpecification("DomainFileName",String.class,"data/ahtn/microrts-ahtn-definition-flexible-single-target-portfolio.lisp")); parameters.add(new ParameterSpecification("TimeBudget",int.class,100)); parameters.add(new ParameterSpecification("IterationsBudget",int.class,-1)); parameters.add(new ParameterSpecification("PlayoutLookahead",int.class,100)); parameters.add(new ParameterSpecification("PlayoutAI",AI.class, playoutAI)); parameters.add(new ParameterSpecification("EvaluationFunction", EvaluationFunction.class, new SimpleSqrtEvaluationFunction3())); return parameters; } public String getDomainFileName() { return domainFileName; } public void setDomainFileName(String a_domainFileName) throws Exception { domainFileName = a_domainFileName; dd = DomainDefinition.fromLispFile(domainFileName); } public int getPlayoutLookahead() { return PLAYOUT_LOOKAHEAD; } public void setPlayoutLookahead(int a_pla) { PLAYOUT_LOOKAHEAD = a_pla; } public AI getPlayoutAI() { return playoutAI; } public void setPlayoutAI(AI a_poAI) { playoutAI = a_poAI; } public EvaluationFunction getEvaluationFunction() { return ef; } public void setEvaluationFunction(EvaluationFunction a_ef) { ef = a_ef; } }
8,847
36.974249
231
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Binding.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; /** * * @author santi */ public class Binding { public Variable v; public Parameter p; public Binding(Variable a_v, Parameter a_p) { v = a_v; p = a_p; } public String toString() { return "(" + v + " -> " + p + ")"; } public boolean equals(Object o) { return o instanceof Binding && v.equals(((Binding) o).v) && p.equals(((Binding) o).p); } }
635
20.2
94
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Clause.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.HashMap; import java.util.ArrayList; import java.util.List; import rts.GameState; import ai.ahtn.domain.LispParser.LispElement; /** * * @author santi */ public class Clause { public static int DEBUG = 0; public static final int CLAUSE_TERM = 0; public static final int CLAUSE_AND = 1; public static final int CLAUSE_OR = 2; public static final int CLAUSE_NOT = 3; public static final int CLAUSE_TRUE = 4; public static final int CLAUSE_FALSE = 5; int type = CLAUSE_AND; Term term; Clause clauses[]; // variables to continue finding matches after the first: List<List<Binding>> matches_left; int matches_current; int matches_previous; List<Binding> matches_l; Clause[] matches_resolved; int[] matches_trail; public static Clause fromLispElement(LispElement e) throws Exception { LispElement head = e.children.get(0); switch (head.element) { case "and": { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_AND; c.clauses = new ai.ahtn.domain.Clause[e.children.size() - 1]; for (int i = 0; i < e.children.size() - 1; i++) { c.clauses[i] = ai.ahtn.domain.Clause.fromLispElement(e.children.get(i + 1)); } return c; } case "or": { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_OR; c.clauses = new ai.ahtn.domain.Clause[e.children.size() - 1]; for (int i = 0; i < e.children.size() - 1; i++) { c.clauses[i] = ai.ahtn.domain.Clause.fromLispElement(e.children.get(i + 1)); } return c; } case "not": { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_NOT; c.clauses = new ai.ahtn.domain.Clause[1]; c.clauses[0] = ai.ahtn.domain.Clause.fromLispElement(e.children.get(1)); return c; } case "true": { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_TRUE; return c; } case "false": { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_FALSE; return c; } default: { ai.ahtn.domain.Clause c = new ai.ahtn.domain.Clause(); c.type = CLAUSE_TERM; c.term = ai.ahtn.domain.Term.fromLispElement(e); return c; } } } public String toString() { switch(type) { case CLAUSE_TERM: return term.toString(); case CLAUSE_AND: { StringBuilder sb = new StringBuilder(); sb.append("(and"); for (Clause clause : clauses) { sb.append(" "); sb.append(clause); } sb.append(")"); return sb.toString(); } case CLAUSE_OR: { StringBuilder sb = new StringBuilder(); sb.append("(or"); for (Clause clause : clauses) { sb.append(" "); sb.append(clause); } sb.append(")"); return sb.toString(); } case CLAUSE_NOT: { StringBuilder sb = new StringBuilder(); sb.append("(not"); for (Clause clause : clauses) { sb.append(" "); sb.append(clause); } sb.append(")"); return sb.toString(); } case CLAUSE_TRUE: return "(true)"; case CLAUSE_FALSE: return "(false)"; } return null; } // applies all the bindings and evaluates in case it is a function: public Clause resolve(List<Binding> l, GameState gs) throws Exception { if (l.isEmpty()) return this; Clause c = new Clause(); c.type = type; if (term!=null) c.term = term.resolve(l, gs); if (clauses!=null) { c.clauses = new Clause[clauses.length]; for(int i = 0;i<clauses.length;i++) { c.clauses[i] = clauses[i].resolve(l, gs); } } else { c.clauses = null; } return c; } public Clause clone() { Clause c = new Clause(); c.type = type; if (term!=null) c.term = term.clone(); if (clauses!=null) { c.clauses = new Clause[clauses.length]; for(int i = 0;i<clauses.length;i++) { c.clauses[i] = clauses[i].clone(); } } else { c.clauses = null; } return c; } public void renameVariables(int renamingIndex) { if (term!=null) term.renameVariables(renamingIndex); if (clauses!=null) { for (Clause clause : clauses) { clause.renameVariables(renamingIndex); } } } // applies all the bindings public void applyBindings(List<Binding> l) throws Exception { if (l.isEmpty()) return; if (term!=null) term.applyBindings(l); if (clauses!=null) { for (Clause clause : clauses) { clause.applyBindings(l); } } } // returns the first match, and sets up the internal state to return the subsequent matches later on: public List<Binding> firstMatch(GameState gs) throws Exception { if (DEBUG>=1) System.out.println("Clause.firstMatch"); switch(type) { case CLAUSE_TERM: matches_left = PredefinedPredicates.allMatches(term,gs); if (matches_left.isEmpty()) return null; return matches_left.remove(0); case CLAUSE_AND: { matches_left = new ArrayList<>(); matches_current = 0; matches_previous = -1; matches_l = new ArrayList<>(); matches_resolved = new Clause[clauses.length]; matches_trail = new int[clauses.length]; while(true) { if (DEBUG>=1) System.out.println("Clause.firstMatch(AND): current = " + matches_current + " (previous: " + matches_previous + ")"); Clause c = clauses[matches_current]; List<Binding> l2; if (matches_previous<matches_current) { // trying a clause for first time with the new bindings: matches_resolved[matches_current] = c; if (matches_l!=null) matches_resolved[matches_current] = c.resolve(matches_l, gs); if (DEBUG>=1) System.out.println("Clause.firstMatch(AND): resolved clause = " + matches_resolved[matches_current]); l2 = matches_resolved[matches_current].firstMatch(gs); // if (l2==null) System.out.println("Failed: " + matches_resolved[matches_current]); if (DEBUG>=1) System.out.println("Clause.firstMatch(AND): match = " + l2); } else { // backtracking: l2 = matches_resolved[matches_current].nextMatch(gs); if (DEBUG>=1) System.out.println("Clause.firstMatch(AND): match = " + l2); } matches_previous = matches_current; if (l2==null) { // backtracking: matches_current--; if (matches_current<0) { matches_left = null; return null; } // undo bindings: while(matches_l.size()>matches_trail[matches_current]) matches_l.remove(matches_l.size()-1); } else { // success: matches_trail[matches_current] = matches_l.size(); matches_l.addAll(l2); matches_current++; if (matches_current>=clauses.length) { return matches_l; } } } } case CLAUSE_OR: { matches_left = new ArrayList<>(); matches_current = 0; for(;matches_current<clauses.length;matches_current++) { List<Binding> l = clauses[matches_current].firstMatch(gs); if (l!=null) return l; } matches_left = null; return null; } case CLAUSE_NOT: List<Binding> l = clauses[0].firstMatch(gs); matches_left = new ArrayList<>(); if (l==null) { return new ArrayList<>(); } else { return null; } case CLAUSE_TRUE: matches_left = new ArrayList<>(); return new ArrayList<>(); case CLAUSE_FALSE: matches_left = new ArrayList<>(); return null; } return null; } public List<Binding> nextMatch(GameState gs) throws Exception { if (DEBUG>=1) System.out.println("Clause.nextMatch"); if (matches_left==null) return firstMatch(gs); switch(type) { case CLAUSE_TERM: if (matches_left.isEmpty()) { matches_left = null; return null; } return matches_left.remove(0); case CLAUSE_AND: { if (matches_current>=clauses.length) { matches_current--; while(matches_l.size()>matches_trail[matches_current]) matches_l.remove(matches_l.size()-1); } while(true) { Clause c = clauses[matches_current]; List<Binding> l2; if (matches_previous<matches_current) { // trying a clause for first time with the new bindings: matches_resolved[matches_current] = c; if (matches_l!=null) matches_resolved[matches_current] = c.resolve(matches_l, gs); l2 = matches_resolved[matches_current].firstMatch(gs); } else { // backtracking: l2 = matches_resolved[matches_current].nextMatch(gs); } matches_previous = matches_current; if (l2==null) { // backtracking: matches_current--; if (matches_current<0) { matches_left = null; return null; } // undo bindings: while(matches_l.size()>matches_trail[matches_current]) matches_l.remove(matches_l.size()-1); } else { // success: matches_trail[matches_current] = matches_l.size(); matches_l.addAll(l2); matches_current++; if (matches_current>=clauses.length) { return matches_l; } } } } case CLAUSE_OR: { for(;matches_current<clauses.length;matches_current++) { List<Binding> l = clauses[matches_current].nextMatch(gs); if (l!=null) return l; } matches_left = null; return null; } case CLAUSE_NOT: matches_left = null; return null; case CLAUSE_TRUE: matches_left = null; return null; case CLAUSE_FALSE: matches_left = null; return null; } return null; } public void countVariableAppearances(HashMap<Symbol,Integer> appearances) throws Exception { if (term!=null) term.countVariableAppearances(appearances); if (clauses!=null) { for(Clause c:clauses) { c.countVariableAppearances(appearances); } } } public void replaceSingletonsByWildcards(List<Symbol> singletons) throws Exception { if (term!=null) term.replaceSingletonsByWildcards(singletons); if (clauses!=null) { for(Clause c:clauses) { c.replaceSingletonsByWildcards(singletons); } } } }
14,219
37.328841
155
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/DomainDefinition.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; import ai.ahtn.domain.LispParser.LispParser; import java.util.HashMap; import java.util.LinkedList; import java.util.List; /** * * @author santi */ public class DomainDefinition { public static int DEBUG = 0; String name; List<HTNOperator> operators = new LinkedList<>(); List<HTNMethod> methods = new LinkedList<>(); HashMap<Symbol,List<HTNMethod>> methodsPerGoal = new HashMap<>(); public List<HTNOperator> getOperators() { return operators; } public List<HTNMethod> getMethods() { return methods; } public void addMethod(HTNMethod m) { methods.add(m); Symbol goal = m.head.getFunctor(); List<HTNMethod> l = methodsPerGoal.get(goal); if (l==null) { l = new LinkedList<>(); methodsPerGoal.put(goal,l); } l.add(m); } public static DomainDefinition fromLispFile(String fileName) throws Exception { List<LispElement> l = LispParser.parseLispFile(fileName); if (DEBUG>=1) { for(LispElement e:l) System.out.println(e); } if (l.isEmpty()) return null; return fromLispElement(l.get(0)); } public static DomainDefinition fromLispElement(LispElement e) throws Exception { DomainDefinition dd = new DomainDefinition(); // verify it's a domain definition: if (e.children.size()!=3) throw new Exception("Lisp domain definition does not have 3 arguments"); LispElement defdomain = e.children.get(0); if (defdomain.element==null || !defdomain.element.equals("defdomain")) throw new Exception("Lisp domain definition does not start by 'defdomain'"); LispElement name_e = e.children.get(1); if (name_e.element==null) throw new Exception("second parameter of defdomain is not a domain name"); dd.name = name_e.element; LispElement rest_e = e.children.get(2); if (rest_e.children==null) throw new Exception("third parameter of defdomain is not a list"); for(LispElement def_e:rest_e.children) { // load operators and methods: if (def_e.children!=null && def_e.children.size()>0) { LispElement head = def_e.children.get(0); if (head.element!=null && head.element.equals(":operator")) { HTNOperator op = HTNOperator.fromLispElement(def_e); dd.operators.add(op); } else if (head.element!=null && head.element.equals(":method")) { HTNMethod m = HTNMethod.fromLispElement(def_e); dd.addMethod(m); } else { throw new Exception("Element in domain definition is not an operator nor method"); } } else { throw new Exception("Element in domain definition is not an operator nor method"); } } // remove singletons: for(HTNMethod m:dd.getMethods()) { if (DEBUG>=1) { List<Symbol> l = m.findSingletons(); if (!l.isEmpty()) System.out.println("Singletons in '" + m.getName() + "': " + l); } m.replaceSingletonsByWildcards(); } return dd; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Domain: ").append(name).append("\n").append("Operators:\n"); for(HTNOperator op:operators) { sb.append(" ").append(op).append("\n"); } sb.append("Methods:\n"); for(HTNMethod m:methods) { sb.append(" ").append(m).append("\n"); } return sb.toString(); } public List<HTNMethod> getMethodsForGoal(Symbol functor) { return methodsPerGoal.get(functor); } }
4,210
32.688
155
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Function.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; import java.util.List; import rts.GameState; /** * * @author santi */ public class Function extends Term implements Parameter { public static int DEBUG = 0; public static Function fromLispElement(LispElement e) throws Exception { // this is a hack (load a term, and just copy it over to a function): Term t = Term.fromLispElement(e); Function f = new Function(); f.functor = t.functor; f.parameters = t.parameters; return f; } public List<Binding> match(int v) { System.err.println("Function.match not implemented yet"); return null; } public List<Binding> match(String s) { System.err.println("Function.match not implemented yet"); return null; } public Term clone() { Function t = new Function(); t.functor = functor; t.parameters = new Parameter[parameters.length]; for(int i = 0;i<t.parameters.length;i++) { t.parameters[i] = parameters[i].cloneParameter(); } return t; } public Parameter cloneParameter() { return (Function)clone(); } public Parameter resolveParameter(List<Binding> l, GameState gs) throws Exception { Function f = this; if (l!=null && !l.isEmpty()) { f = new Function(); f.functor = functor; f.parameters = new Parameter[parameters.length]; for(int i = 0;i<f.parameters.length;i++) { f.parameters[i] = parameters[i].resolveParameter(l, gs); } } if (f.isGround()) { Parameter p = PredefinedFunctions.evaluate(f, gs); if (DEBUG>=1) System.out.println("Function.resolveParameter: " + this + " -> " + p); return p; } else { return f; } } public Parameter applyBindingsParameter(List<Binding> l) throws Exception { Function f = this; if (!l.isEmpty()) { f = new Function(); f.functor = functor; f.parameters = new Parameter[parameters.length]; for(int i = 0;i<f.parameters.length;i++) { f.parameters[i] = parameters[i].applyBindingsParameter(l); } } return f; } }
2,647
27.170213
96
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/HTNMethod.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; import ai.ahtn.planner.AdversarialChoicePoint; import java.util.HashMap; import java.util.ArrayList; import java.util.List; import rts.GameState; /** * * @author santi */ public class HTNMethod { String name; Term head; MethodDecomposition method; public HTNMethod(String n, Term h, MethodDecomposition m) { name = n; head = h; method = m; } public String getName() { return name; } public Term getHead() { return head; } public MethodDecomposition getDecomposition() { return method; } public HTNMethod clone() { HTNMethod c = new HTNMethod(name, head.clone(), method.clone()); return c; } public HTNMethod cloneTrackingDescendants(MethodDecomposition descendantsToTrack[], MethodDecomposition newDescendants[]) { HTNMethod c = new HTNMethod(name, head.clone(), method.cloneTrackingDescendants(descendantsToTrack,newDescendants)); return c; } /* public HTNMethod clone(int renamingIndex) { HTNMethod c = new HTNMethod(name, head.clone(), method.clone()); c.renameVariables(renamingIndex); return c; } */ public void renameVariables(int renamingIndex) { head.renameVariables(renamingIndex); method.renameVariables(renamingIndex); } public void applyBindings(List<Binding> l) throws Exception { head.applyBindings(l); method.applyBindings(l); } public static HTNMethod fromLispElement(LispElement e) throws Exception { LispElement name_e = e.children.get(1); LispElement head_e = e.children.get(2); LispElement method_e = e.children.get(3); String name = name_e.element; Term head = Term.fromLispElement(head_e); MethodDecomposition m = MethodDecomposition.fromLispElement(method_e); return new HTNMethod(name,head,m); } public void replaceSingletonsByWildcards() throws Exception { List<Symbol> singletons = findSingletons(); head.replaceSingletonsByWildcards(singletons); method.replaceSingletonsByWildcards(singletons); } public List<Symbol> findSingletons() throws Exception { HashMap<Symbol,Integer> appearances = new HashMap<>(); countVariableAppearances(appearances); List<Symbol> l = new ArrayList<>(); for(Symbol v:appearances.keySet()) { if (appearances.get(v)==1) l.add(v); } return l; } public void countVariableAppearances(HashMap<Symbol,Integer> appearances) throws Exception { head.countVariableAppearances(appearances); method.countVariableAppearances(appearances); } public String toString() { return "method("+name+"): " + head + ", decomposition: " + method; } public int executionCycle(GameState gs, List<MethodDecomposition> actions, List<MethodDecomposition> choicePoints) { return method.executionCycle(gs, actions, choicePoints); } public int executionCycle(GameState gs, List<MethodDecomposition> actions, List<MethodDecomposition> choicePoints, AdversarialChoicePoint previous_cp) { return method.executionCycle(gs, actions, choicePoints, previous_cp); } }
3,630
29.008264
156
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/HTNOperator.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; /** * * @author santi */ public class HTNOperator { Term head; Clause precondition; // postconditions are not defined in the operators, but directly as part of the simulator public HTNOperator(Term a_head, Clause a_prec) { head = a_head; precondition = a_prec; } public Term getHead() { return head; } public Clause getPrecondition() { return precondition; } public static HTNOperator fromLispElement(LispElement e) throws Exception { LispElement head_e = e.children.get(1); LispElement precondition_e = e.children.get(2); Term head = Term.fromLispElement(head_e); Clause prec = Clause.fromLispElement(precondition_e); return new HTNOperator(head,prec); } public String toString() { return "operator: " + head + ", precondition: " + precondition; } }
1,188
23.770833
93
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/IntegerConstant.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.ArrayList; import java.util.List; import rts.GameState; /** * * @author santi */ public class IntegerConstant implements Parameter { public int value; public IntegerConstant(int v) { value = v; } public String toString() { return "" + value; } public List<Binding> match(int v) { if (value==v) return new ArrayList<>(); return null; } public List<Binding> match(String s) { return null; } public Parameter cloneParameter() { // constants do not need to be cloned: return this; } public Parameter resolveParameter(List<Binding> l, GameState gs) { return this; } public Parameter applyBindingsParameter(List<Binding> l) { return this; } public boolean equals(Object o) { return o instanceof IntegerConstant && ((IntegerConstant) o).value == value; } }
1,189
19.877193
84
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/MethodDecomposition.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; import ai.ahtn.planner.AdversarialChoicePoint; import java.util.Comparator; import java.util.HashMap; import java.util.ArrayList; import java.util.List; import rts.GameState; import util.Pair; /** * * @author santi */ public class MethodDecomposition { public static int DEBUG = 0; public static final int METHOD_CONDITION = 0; public static final int METHOD_OPERATOR = 1; public static final int METHOD_METHOD = 2; public static final int METHOD_SEQUENCE = 3; public static final int METHOD_PARALLEL = 4; public static final int METHOD_NON_BRANCHING_CONDITION = 5; // a condition only to verify, the first binding found will be taken // and won't result in a choicepoint public static final int EXECUTION_SUCCESS = 0; public static final int EXECUTION_FAILURE = 1; public static final int EXECUTION_ACTION_ISSUE = 2; public static final int EXECUTION_WAITING_FOR_ACTION = 3; public static final int EXECUTION_CHOICE_POINT = 4; protected int type = METHOD_CONDITION; protected Clause clause; protected Term term; protected MethodDecomposition[] subelements; HTNMethod method; /* executionState: - METHOD_CONDITION: 0: not tested (return as choice point), 1: already tested with success, 2: already tested with failure - METHOD_OPERATOR: 0: not sent, 1: waiting for completion, 2: success - METHOD_METHOD: - - METHOD_SEQUENCE: stores the index of the current subelement being executed - METHOD_PARALLEL: - */ int executionState = 0; int operatorExecutingState = 0; List<MethodDecomposition> operatorsBeingExecuted; Term updatedTerm; int updatedTermCycle = -1; // at which game cycle did we update the term last time public MethodDecomposition() { } public MethodDecomposition(Term t, HTNMethod m) { type = METHOD_METHOD; term = t; method = m; } public MethodDecomposition(Term t) { type = METHOD_OPERATOR; term = t; } public int getType() { return type; } public void setType(int a_type) { type = a_type; } public Clause getClause() { return clause; } public Term getTerm() { return term; } public Term getUpdatedTerm() { return updatedTerm; } public void setUpdatedTerm(Term ut) { updatedTerm = ut; } public int getUpdatedTermCycle() { return updatedTermCycle; } public void setUpdatedTermCycle(int utc) { updatedTermCycle = utc; } public HTNMethod getMethod() { return method; } public MethodDecomposition[] getSubparts() { return subelements; } public void setSubparts(MethodDecomposition[] se) { subelements = se; } public int getExecutionState() { return executionState; } public int getOperatorExecutingState() { return operatorExecutingState; } public List<MethodDecomposition> getOperatorsBeingExecuted() { return operatorsBeingExecuted; } public void setOperatorsBeingExecuted(List<MethodDecomposition> l) { operatorsBeingExecuted = l; } public void setOperatorExecutingState(int s) { operatorExecutingState = s; } public void setMethod(HTNMethod m) { method = m; } public void setExecutionState(int es) { executionState = es; } public static MethodDecomposition fromLispElement(LispElement e) throws Exception { LispElement head = e.children.get(0); switch (head.element) { case ":condition": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_CONDITION; d.clause = ai.ahtn.domain.Clause.fromLispElement(e.children.get(1)); return d; } case ":!condition": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_NON_BRANCHING_CONDITION; d.clause = ai.ahtn.domain.Clause.fromLispElement(e.children.get(1)); return d; } case ":operator": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_OPERATOR; d.term = ai.ahtn.domain.Term.fromLispElement(e.children.get(1)); return d; } case ":method": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_METHOD; d.term = ai.ahtn.domain.Term.fromLispElement(e.children.get(1)); return d; } case ":sequence": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_SEQUENCE; d.subelements = new ai.ahtn.domain.MethodDecomposition[e.children.size() - 1]; for (int i = 0; i < e.children.size() - 1; i++) { d.subelements[i] = ai.ahtn.domain.MethodDecomposition .fromLispElement(e.children.get(i + 1)); } return d; } case ":parallel": { ai.ahtn.domain.MethodDecomposition d = new ai.ahtn.domain.MethodDecomposition(); d.type = METHOD_PARALLEL; d.subelements = new ai.ahtn.domain.MethodDecomposition[e.children.size() - 1]; for (int i = 0; i < e.children.size() - 1; i++) { d.subelements[i] = ai.ahtn.domain.MethodDecomposition .fromLispElement(e.children.get(i + 1)); } return d; } default: throw new Exception("unrecognized method decomposition!: " + head.element); } } public String toString() { switch(type) { case METHOD_CONDITION: return "(:condition " + clause + ")"; case METHOD_NON_BRANCHING_CONDITION: return "(:!condition " + clause + ")"; case METHOD_OPERATOR: if (updatedTerm!=null) { return "(:operator " + updatedTerm + ")"; } else { return "(:operator " + term + ")"; } case METHOD_METHOD: if (method==null) { return "(:method " + term + ")"; } else { return "(" + method +")"; } case METHOD_SEQUENCE: { StringBuilder sb = new StringBuilder(); sb.append("(:sequence"); for (MethodDecomposition subelement : subelements) { sb.append(" "); sb.append(subelement); } sb.append(")"); return sb.toString(); } case METHOD_PARALLEL: { StringBuilder sb = new StringBuilder(); sb.append("(:parallel"); for (MethodDecomposition subelement : subelements) { sb.append(" "); sb.append(subelement); } sb.append(")"); return sb.toString(); } } return null; } public void printDetailed() { printDetailed(0); } public void printDetailed(int tabs) { for(int j = 0;j<tabs;j++) System.out.print(" "); switch(type) { case METHOD_CONDITION: System.out.println(this.hashCode() + " - "+executionState+" - (:condition " + clause + ")"); break; case METHOD_NON_BRANCHING_CONDITION: System.out.println(this.hashCode() + " - "+executionState+" - (:!condition " + clause + ")"); break; case METHOD_OPERATOR: if (updatedTerm!=null) { System.out.println(this.hashCode() + " - "+executionState+" - (:operator " + updatedTerm + ")"); } else { System.out.println(this.hashCode() + " - "+executionState+" - (:operator " + term + ")"); } break; case METHOD_METHOD: if (method!=null) { System.out.println(this.hashCode() + " - "+executionState+" - (:method " + method.head + ")"); for(int j = 0;j<tabs;j++) System.out.print(" "); System.out.println("Decomposition:"); method.getDecomposition().printDetailed(tabs+1); } else { System.out.println(this.hashCode() + " - "+executionState+" - (:method " + term + ")"); } break; case METHOD_SEQUENCE: { System.out.println(this.hashCode() + " - "+executionState+" - (:sequence"); for (MethodDecomposition subelement : subelements) { subelement.printDetailed(tabs + 1); } for(int j = 0;j<tabs;j++) System.out.print(" "); System.out.println(")"); } break; case METHOD_PARALLEL: { System.out.println(this.hashCode() + " - "+executionState+" - (:parallel"); for (MethodDecomposition subelement : subelements) { subelement.printDetailed(tabs + 1); } for(int j = 0;j<tabs;j++) System.out.print(" "); System.out.println(")"); } break; } } public List<MethodDecomposition> getLeaves() { List<MethodDecomposition> l = new ArrayList<>(); if (subelements==null) { if (method!=null) { l.addAll(method.getDecomposition().getLeaves()); } else { l.add(this); } } else { for(MethodDecomposition md:subelements) { l.addAll(md.getLeaves()); } } return l; } // note: operatorsBeingExecuted is not cloned by this method public MethodDecomposition clone() { MethodDecomposition c = new MethodDecomposition(); c.type = type; if (clause!=null) c.clause = clause.clone(); if (term!=null) c.term = term.clone(); if (updatedTerm!=null) c.updatedTerm = updatedTerm.clone(); c.updatedTermCycle = updatedTermCycle; c.executionState = executionState; c.operatorExecutingState = operatorExecutingState; if (subelements!=null) { c.subelements = new MethodDecomposition[subelements.length]; for(int i = 0;i<subelements.length;i++) { c.subelements[i] = subelements[i].clone(); } } if (method!=null) { c.method = method.clone(); } return c; } public MethodDecomposition cloneTrackingDescendants(MethodDecomposition descendantsToTrack[], MethodDecomposition newDescendants[]) { MethodDecomposition c = new MethodDecomposition(); for(int i = 0;i<descendantsToTrack.length;i++) { if (descendantsToTrack[i]==this) newDescendants[i] = c; } c.type = type; if (clause!=null) c.clause = clause.clone(); if (term!=null) c.term = term.clone(); if (updatedTerm!=null) c.updatedTerm = updatedTerm.clone(); c.updatedTermCycle = updatedTermCycle; c.executionState = executionState; c.operatorExecutingState = operatorExecutingState; if (subelements!=null) { c.subelements = new MethodDecomposition[subelements.length]; for(int i = 0;i<subelements.length;i++) { c.subelements[i] = subelements[i].cloneTrackingDescendants(descendantsToTrack, newDescendants); } } if (method!=null) { c.method = method.cloneTrackingDescendants(descendantsToTrack, newDescendants); } return c; } public void renameVariables(int renamingIndex) { if (clause!=null) clause.renameVariables(renamingIndex); if (term!=null) term.renameVariables(renamingIndex); if (updatedTerm!=null) updatedTerm.renameVariables(renamingIndex); if (subelements!=null) { for (MethodDecomposition subelement : subelements) { subelement.renameVariables(renamingIndex); } } if (method!=null) method.renameVariables(renamingIndex); } public void applyBindings(List<Binding> l) throws Exception { if (clause!=null) clause.applyBindings(l); if (term!=null) term.applyBindings(l); if (updatedTerm!=null) updatedTerm.applyBindings(l); if (subelements!=null) { for (MethodDecomposition subelement : subelements) { subelement.applyBindings(l); } } if (method!=null) method.applyBindings(l); } public void executionReset() { executionState = 0; operatorExecutingState = 0; operatorsBeingExecuted = null; if (subelements!=null) { for (MethodDecomposition subelement : subelements) { subelement.executionReset(); } } if (method!=null) { method.getDecomposition().executionReset(); } } public int executionCycle(GameState gs, List<MethodDecomposition> actions, List<MethodDecomposition> choicePoints) { switch(type) { case METHOD_CONDITION: case METHOD_NON_BRANCHING_CONDITION: if (executionState==0) { choicePoints.add(this); return EXECUTION_CHOICE_POINT; } else if (executionState==1) { return EXECUTION_SUCCESS; } else { return EXECUTION_FAILURE; } case METHOD_OPERATOR: if (executionState==0) { // we rely on external code to set the executionSTate to 1 and // to fill in the waitingForUnit actions.add(this); return EXECUTION_ACTION_ISSUE; } else if (executionState==1) { // test whether the operator is complete (this will be updated externally) return EXECUTION_WAITING_FOR_ACTION; } else { return EXECUTION_SUCCESS; } case METHOD_METHOD: if (method==null) { // return choice point choicePoints.add(this); return EXECUTION_CHOICE_POINT; } else { // recursive call: return method.executionCycle(gs, actions, choicePoints); } case METHOD_SEQUENCE: do { if (executionState>=subelements.length) return EXECUTION_SUCCESS; int tmp = subelements[executionState].executionCycle(gs, actions, choicePoints); if (tmp==EXECUTION_SUCCESS) { executionState++; } else { return tmp; } }while(true); case METHOD_PARALLEL: { boolean allSuccess = true; boolean anyActionIssue = false; for (MethodDecomposition subelement : subelements) { int tmp = subelement.executionCycle(gs, actions, choicePoints); if (tmp == EXECUTION_ACTION_ISSUE) anyActionIssue = true; if (tmp == EXECUTION_CHOICE_POINT || tmp == EXECUTION_FAILURE) return tmp; if (tmp != EXECUTION_SUCCESS) allSuccess = false; } if (allSuccess) return EXECUTION_SUCCESS; if (anyActionIssue) return EXECUTION_ACTION_ISSUE; return EXECUTION_WAITING_FOR_ACTION; } } return EXECUTION_SUCCESS; } /* This method is the same as the one above, but every time a MethodDecompositinn changes, it stores its previous execution state in 'previous_cp' */ public int executionCycle(GameState gs, List<MethodDecomposition> actions, List<MethodDecomposition> choicePoints, AdversarialChoicePoint previous_cp) { switch(type) { case METHOD_CONDITION: case METHOD_NON_BRANCHING_CONDITION: if (executionState==0) { choicePoints.add(this); return EXECUTION_CHOICE_POINT; } else if (executionState==1) { return EXECUTION_SUCCESS; } else { return EXECUTION_FAILURE; } case METHOD_OPERATOR: if (executionState==0) { previous_cp.captureExecutionStateNonRecursive(this); // we rely on external code to set the executionSTate to 1 and // to fill in the waitingForUnit actions.add(this); return EXECUTION_ACTION_ISSUE; } else if (executionState==1) { // test whether the operator is complete (this will be updated externally) return EXECUTION_WAITING_FOR_ACTION; } else { return EXECUTION_SUCCESS; } case METHOD_METHOD: if (method==null) { // return choice point choicePoints.add(this); return EXECUTION_CHOICE_POINT; } else { // recursive call: return method.executionCycle(gs, actions, choicePoints, previous_cp); } case METHOD_SEQUENCE: do { if (executionState>=subelements.length) return EXECUTION_SUCCESS; int tmp = subelements[executionState].executionCycle(gs, actions, choicePoints, previous_cp); if (tmp==EXECUTION_SUCCESS) { previous_cp.captureExecutionStateNonRecursive(this); executionState++; } else { return tmp; } }while(true); case METHOD_PARALLEL: { boolean allSuccess = true; boolean anyActionIssue = false; for (MethodDecomposition subelement : subelements) { int tmp = subelement.executionCycle(gs, actions, choicePoints, previous_cp); if (tmp == EXECUTION_ACTION_ISSUE) anyActionIssue = true; if (tmp == EXECUTION_CHOICE_POINT || tmp == EXECUTION_FAILURE) return tmp; if (tmp != EXECUTION_SUCCESS) allSuccess = false; } if (allSuccess) return EXECUTION_SUCCESS; if (anyActionIssue) return EXECUTION_ACTION_ISSUE; return EXECUTION_WAITING_FOR_ACTION; } } return EXECUTION_SUCCESS; } public List<Pair<Integer,List<Term>>> convertToOperatorList() throws Exception { List<Pair<Integer,List<Term>>> l = new ArrayList<>(); convertToOperatorList(l); // sort the list: l.sort(new Comparator<Pair<Integer, List<Term>>>() { public int compare(Pair<Integer, List<Term>> o1, Pair<Integer, List<Term>> o2) { return Integer.compare(o1.m_a, o2.m_a); } }); return l; } public void convertToOperatorList(List<Pair<Integer,List<Term>>> l) throws Exception { switch(type) { case METHOD_CONDITION: return; case METHOD_NON_BRANCHING_CONDITION: return; case METHOD_OPERATOR: if (updatedTerm!=null) { if (l.isEmpty()) { Pair<Integer,List<Term>> tmp = new Pair<>(updatedTermCycle, new ArrayList<>()); tmp.m_b.add(updatedTerm); l.add(tmp); } else { Pair<Integer,List<Term>> tmp = l.get(l.size()-1); if (tmp.m_a == updatedTermCycle) { tmp.m_b.add(updatedTerm); } else { tmp = new Pair<>(updatedTermCycle, new ArrayList<>()); tmp.m_b.add(updatedTerm); l.add(tmp); } } } break; case METHOD_METHOD: if (method!=null) method.getDecomposition().convertToOperatorList(l); break; case METHOD_SEQUENCE: case METHOD_PARALLEL: if (subelements!=null) { for (MethodDecomposition subelement : subelements) { subelement.convertToOperatorList(l); } } break; } } public void countVariableAppearances(HashMap<Symbol,Integer> appearances) throws Exception { if (clause!=null) clause.countVariableAppearances(appearances); if (term!=null) term.countVariableAppearances(appearances); if (subelements!=null) { for(MethodDecomposition md:subelements) { md.countVariableAppearances(appearances); } } } public void replaceSingletonsByWildcards(List<Symbol> singletons) throws Exception { if (clause!=null) clause.replaceSingletonsByWildcards(singletons); if (term!=null) term.replaceSingletonsByWildcards(singletons); if (subelements!=null) { for(MethodDecomposition md:subelements) { md.replaceSingletonsByWildcards(singletons); } } } }
23,431
36.915858
156
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Parameter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.List; import rts.GameState; /** * * @author santi */ public interface Parameter { // If a match is found: // - the return value is a list with the required bindings // If a match is not found: return null List<Binding> match(int v) throws Exception; List<Binding> match(String s) throws Exception; Parameter cloneParameter(); Parameter applyBindingsParameter(List<Binding> l) throws Exception; // applies all the bindings and evaluates in case it is a function: Parameter resolveParameter(List<Binding> l, GameState gs) throws Exception; }
819
26.333333
79
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/PredefinedFunctions.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.HashMap; import rts.GameState; import rts.UnitAction; /** * * @author santi */ public class PredefinedFunctions { public static int DEBUG = 0; public interface FunctionEvaluator { Parameter evaluate(Function f, GameState gs) throws Exception; } static final HashMap<Symbol, FunctionEvaluator> functions = new HashMap<>(); static { try { functions.put(new Symbol("neighbor-position"), new FunctionEvaluator() { public Parameter evaluate(Function f, GameState gs) throws Exception { if (f.parameters.length!=2) return null; if ((f.parameters[0] instanceof IntegerConstant) && (f.parameters[1] instanceof IntegerConstant)) { int pos = ((IntegerConstant)f.parameters[0]).value; int dir = ((IntegerConstant)f.parameters[1]).value; switch(dir) { case UnitAction.DIRECTION_UP: return new IntegerConstant(pos - gs.getPhysicalGameState().getWidth()); case UnitAction.DIRECTION_RIGHT: return new IntegerConstant(pos + 1); case UnitAction.DIRECTION_DOWN: return new IntegerConstant(pos + gs.getPhysicalGameState().getWidth()); case UnitAction.DIRECTION_LEFT: return new IntegerConstant(pos - 1); } } return null; } }); functions.put(new Symbol("+"), new FunctionEvaluator() { public Parameter evaluate(Function f, GameState gs) throws Exception { if (f.parameters.length!=2) return null; if ((f.parameters[0] instanceof IntegerConstant) && (f.parameters[1] instanceof IntegerConstant)) { int p1 = ((IntegerConstant)f.parameters[0]).value; int p2 = ((IntegerConstant)f.parameters[1]).value; return new IntegerConstant(p1 + p2); } return null; } }); }catch(Exception e) { e.printStackTrace(); } } public static Parameter evaluate(Function f, GameState gs) throws Exception { FunctionEvaluator fe = functions.get(f.functor); if (fe==null) { System.err.println("PredefinedFunctions.evaluate: undefined function " + f); return null; } return fe.evaluate(f, gs); } }
3,289
40.125
111
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/PredefinedOperators.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import java.util.HashMap; import rts.GameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import util.Pair; /** * * @author santi */ public class PredefinedOperators { public static int DEBUG = 0; public interface OperatorExecutor { // return true, when the action is over, and false when it's not over yet // if pa == null, the actions are issued directly to the game state // if pa != null, they are added to pa boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception; } // static PathFinding pf = new GreedyPathFinding(); static PathFinding pf = new AStarPathFinding(); static final HashMap<Symbol, OperatorExecutor> operators = new HashMap<>(); static { try { operators.put(new Symbol("!wait"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int time = ((IntegerConstant)t.parameters[0]).value; if (state.getOperatorExecutingState()==1) { // we submitted an action before, so, now we just have to wait the right amount of time: return (gs.getTime() - state.getUpdatedTermCycle()) >= time; } else { state.setOperatorExecutingState(1); return false; } } }); operators.put(new Symbol("!wait-for-free-unit"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int player = ((IntegerConstant)t.parameters[0]).value; // boolean anyunit = false; for(Unit u:gs.getUnits()) { if (u.getPlayer()==player) { // anyunit = true; if (gs.getUnitAction(u)==null) return true; } } return false; } }); operators.put(new Symbol("!fill-with-idles"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int player = ((IntegerConstant)t.parameters[0]).value; if (pa==null) { pa = new PlayerAction(); for(Unit u:gs.getUnits()) { if (u.getPlayer()==player) { if (gs.getUnitAction(u)==null) { pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE, 10)); } } } gs.issue(pa); } else { for(Unit u:gs.getUnits()) { if (u.getPlayer()==player) { if (pa.getAction(u)==null && gs.getUnitAction(u)==null) { pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_NONE, 10)); } } } } return true; } }); operators.put(new Symbol("!idle"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); if (u1==null) return true; if (state.getOperatorExecutingState()==1) { // we submitted an action before, so, now we just have to wait: return gs.getUnitAction(u1) == null; } else { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_NONE, 10)); gs.issue(pa); } else { pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_NONE, 10)); } state.setOperatorExecutingState(1); return false; } } }); operators.put(new Symbol("!attack"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); if (u1==null) return true; // unit still doing something: if (gs.getUnitAction(u1)!=null) return false; if (state.getOperatorExecutingState()==1) { // we submitted an action before, so, now we just have to wait: return gs.getUnitAction(u1) == null; } else { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); if (u2==null) return true; if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_ATTACK_LOCATION,u2.getX(),u2.getY())); gs.issue(pa); } else { pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_ATTACK_LOCATION,u2.getX(),u2.getY())); } state.setOperatorExecutingState(1); return false; } } }); operators.put(new Symbol("!harvest"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); if (u1==null) return true; // unit still doing something: if (gs.getUnitAction(u1)!=null) return false; if (state.getOperatorExecutingState()==1) { // we submitted an action before, so, now we just have to wait: return gs.getUnitAction(u1) == null; } else { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); if (u2==null) return true; if (pa==null) { pa = new PlayerAction(); if (u1.getX() == u2.getX()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_RIGHT)); if (u1.getX() == u2.getX()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_LEFT)); if (u1.getY() == u2.getY()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_DOWN)); if (u1.getY() == u2.getY()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_UP)); gs.issue(pa); } else { if (u1.getX() == u2.getX()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_RIGHT)); if (u1.getX() == u2.getX()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_LEFT)); if (u1.getY() == u2.getY()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_DOWN)); if (u1.getY() == u2.getY()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_UP)); } state.setOperatorExecutingState(1); return false; } } }); operators.put(new Symbol("!return"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); if (u1==null) return true; // unit still doing something: if (gs.getUnitAction(u1)!=null) return false; if (state.getOperatorExecutingState()==1) { // we submitted an action before, so, now we just have to wait: return gs.getUnitAction(u1) == null; } else { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); if (u2==null) return true; if (pa==null) { pa = new PlayerAction(); if (u1.getX() == u2.getX()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_RIGHT)); if (u1.getX() == u2.getX()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_LEFT)); if (u1.getY() == u2.getY()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_DOWN)); if (u1.getY() == u2.getY()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_UP)); gs.issue(pa); } else { if (u1.getX() == u2.getX()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_RIGHT)); if (u1.getX() == u2.getX()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_LEFT)); if (u1.getY() == u2.getY()-1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_DOWN)); if (u1.getY() == u2.getY()+1) pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_UP)); } state.setOperatorExecutingState(1); return false; } } }); operators.put(new Symbol("!produce"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); if (u1==null) { // System.out.println("PRODUCE FAIL: unit " + uID1 + " does not exits!"); return true; } // unit still doing something: if (gs.getUnitAction(u1)!=null) { // System.out.println("PRODUCE FAIL: unit " + uID1 + " is already doing something!"); return false; } if (state.getOperatorExecutingState()==1) { // System.out.println("PRODUCE already executing for" + uID1 + "!"); // we submitted an action before, so, now we just have to wait: return gs.getUnitAction(u1) == null; } else { // System.out.println("PRODUCE working fine for " + uID1 + "!"); int direction = ((IntegerConstant)t.parameters[1]).value; String type = ((SymbolConstant)t.parameters[2]).get(); UnitType ut = gs.getUnitTypeTable().getUnitType(type); ResourceUsage ru = gs.getResourceUsage(); if (pa!=null) { for(Pair<Unit, UnitAction> tmp:pa.getActions()) { ru.merge(tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState())); } } int posx = u1.getX() + UnitAction.DIRECTION_OFFSET_X[direction]; int posy = u1.getY() + UnitAction.DIRECTION_OFFSET_Y[direction]; if (posx>=0 && posx<gs.getPhysicalGameState().getWidth() && posy>=0 && posy<gs.getPhysicalGameState().getHeight() && gs.free(posx, posy) && gs.getPlayer(u1.getPlayer()).getResources()-ru.getResourcesUsed(u1.getPlayer())>=ut.cost) { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, new UnitAction(UnitAction.TYPE_PRODUCE, direction, ut)); gs.issue(pa); } else { UnitAction ua = new UnitAction(UnitAction.TYPE_PRODUCE, direction, ut); ResourceUsage ru2 = ua.resourceUsage(u1, gs.getPhysicalGameState()); pa.getResourceUsage().merge(ru2); pa.addUnitAction(u1, ua); } state.setOperatorExecutingState(1); // } else { // System.out.println("PRODUCE out of range for " + uID1 + "!: " + posx + ", " + posy); } return false; } } }); operators.put(new Symbol("!move"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { ResourceUsage ru = gs.getResourceUsage(); if (pa!=null) { for(Pair<Unit, UnitAction> tmp:pa.getActions()) { ru.merge(tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState())); } } int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); // if u1 == null, the unit is dead, so the action is over: if (u1==null) return true; if (gs.getUnitAction(u1)==null) { Parameter p = t.parameters[1].resolveParameter(null, gs); int pos2 = ((IntegerConstant)p).value; UnitAction ua = pf.findPath(u1, pos2, gs, ru); if (ua!=null) { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, ua); gs.issue(pa); } else { ResourceUsage ru2 = ua.resourceUsage(u1, gs.getPhysicalGameState()); pa.getResourceUsage().merge(ru2); pa.addUnitAction(u1, ua); } return false; } else { return true; } } else { // unit is still doing something: return false; } } }); operators.put(new Symbol("!move-into-attack-range"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { ResourceUsage ru = gs.getResourceUsage(); if (pa!=null) { for(Pair<Unit, UnitAction> tmp:pa.getActions()) { ru.merge(tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState())); } } int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); // if u1 == null, the unit is dead, so the action is over: if (u1==null) return true; if (gs.getUnitAction(u1)==null) { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); // if u2 == null, the unit is dead, so the action is over: if (u2==null) return true; UnitAction ua = pf.findPathToPositionInRange(u1, u2.getPosition(gs.getPhysicalGameState()), u1.getType().attackRange, gs, ru); if (ua!=null) { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, ua); gs.issue(pa); } else { ResourceUsage ru2 = ua.resourceUsage(u1, gs.getPhysicalGameState()); pa.getResourceUsage().merge(ru2); pa.addUnitAction(u1, ua); } return false; } else { return true; } } else { // unit is still doing something: return false; } } }); operators.put(new Symbol("!move-into-harvest-range"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { ResourceUsage ru = gs.getResourceUsage(); if (pa!=null) { for(Pair<Unit, UnitAction> tmp:pa.getActions()) { ru.merge(tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState())); } } int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); // if u1 == null, the unit is dead, so the action is over: if (u1==null) return true; if (gs.getUnitAction(u1)==null) { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); // if u2 == null, the unit is dead, so the action is over: if (u2==null) return true; UnitAction ua = pf.findPathToPositionInRange(u1, u2.getPosition(gs.getPhysicalGameState()), 1, gs, ru); if (ua!=null) { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, ua); gs.issue(pa); } else { ResourceUsage ru2 = ua.resourceUsage(u1, gs.getPhysicalGameState()); pa.getResourceUsage().merge(ru2); pa.addUnitAction(u1, ua); } return false; } else { return true; } } else { // unit is still doing something: return false; } } }); operators.put(new Symbol("!move-into-return-range"), new OperatorExecutor() { public boolean execute(Term t, MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { ResourceUsage ru = gs.getResourceUsage(); if (pa!=null) { for(Pair<Unit, UnitAction> tmp:pa.getActions()) { ru.merge(tmp.m_b.resourceUsage(tmp.m_a, gs.getPhysicalGameState())); } } int uID1 = ((IntegerConstant)t.parameters[0]).value; Unit u1 = gs.getUnit(uID1); // if u1 == null, the unit is dead, so the action is over: if (u1==null) return true; if (gs.getUnitAction(u1)==null) { int uID2 = ((IntegerConstant)t.parameters[1]).value; Unit u2 = gs.getUnit(uID2); // if u2 == null, the unit is dead, so the action is over: if (u2==null) return true; UnitAction ua = pf.findPathToPositionInRange(u1, u2.getPosition(gs.getPhysicalGameState()), 1, gs, ru); if (ua!=null) { if (pa==null) { pa = new PlayerAction(); pa.addUnitAction(u1, ua); gs.issue(pa); } else { ResourceUsage ru2 = ua.resourceUsage(u1, gs.getPhysicalGameState()); pa.getResourceUsage().merge(ru2); pa.addUnitAction(u1, ua); } return false; } else { return true; } } else { // unit is still doing something: return false; } } }); } catch(Exception e) { e.printStackTrace(); } } public static boolean execute(MethodDecomposition state, GameState gs) throws Exception { Term t = state.updatedTerm; if (t==null) t = state.term; OperatorExecutor oe = operators.get(t.functor); if (oe==null) throw new Exception("PredefinedFunctions.evaluate: undefined operator " + t); return oe.execute(t, state, gs, null); } public static boolean execute(MethodDecomposition state, GameState gs, PlayerAction pa) throws Exception { Term t = state.updatedTerm; if (t==null) t = state.term; OperatorExecutor oe = operators.get(t.functor); if (oe==null) throw new Exception("PredefinedFunctions.evaluate: undefined operator " + t); return oe.execute(t, state, gs, pa); } }
27,012
58.5
158
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/PredefinedPredicates.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.Player; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; /** * * @author santi */ public class PredefinedPredicates { public static int DEBUG = 0; public interface PredicateTester { List<Binding> firstMatch(Term term, GameState gs) throws Exception; List<List<Binding>> allMatches(Term term, GameState gs) throws Exception; } // static PathFinding pf = new GreedyPathFinding(); static PathFinding pf = new AStarPathFinding(); static final HashMap<Symbol, PredicateTester> predicates = new HashMap<>(); static { try { predicates.put(new Symbol("="), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { List<Binding> l = new LinkedList<>(); Parameter p1 = term.parameters[0].resolveParameter(null, gs); Parameter p2 = term.parameters[1].resolveParameter(null, gs); if (p1 instanceof Variable) { if (!((p2 instanceof Variable) && p2.equals(p1))) { if (!((Variable)p1).ignore()) l.add(new Binding((Variable)p1, p2)); } } else { if (p2 instanceof Variable) { if (!((Variable)p2).ignore()) l.add(new Binding((Variable)p2, p1)); } else { // otherwise, they are constants, and must be identical: if (!p1.equals(p2)) return null; } } return l; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("unit"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { for(Unit u:gs.getUnits()) { List<Binding> b = term.parameters[0].match((int)u.getID()); if (b==null) continue; { Parameter p = term.parameters[1].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getType().name); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[2].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPlayer()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[3].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getResources()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[4].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPosition(gs.getPhysicalGameState())); if (b2==null) continue; b.addAll(b2); } return b; } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<List<Binding>> ll = new LinkedList<>(); for(Unit u:gs.getUnits()) { List<Binding> b = term.parameters[0].match((int)u.getID()); if (b==null) continue; { Parameter p = term.parameters[1].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getType().name); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[2].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPlayer()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[3].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getResources()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[4].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPosition(gs.getPhysicalGameState())); if (b2==null) continue; b.addAll(b2); } ll.add(b); } return ll; } }); predicates.put(new Symbol("closest-unit-to"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { List<Binding> closest = null; int distance = 0; Parameter p0 = term.parameters[0]; Unit referenceUnit = null; if (p0 instanceof IntegerConstant) { referenceUnit = gs.getUnit(((IntegerConstant)p0).value); } if (referenceUnit==null) return null; for(Unit u:gs.getUnits()) { List<Binding> b = term.parameters[1].match((int)u.getID()); if (b==null) continue; { Parameter p = term.parameters[2].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getType().name); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[3].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPlayer()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[4].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getResources()); if (b2==null) continue; b.addAll(b2); } { Parameter p = term.parameters[5].resolveParameter(b, gs); List<Binding> b2 = p.match(u.getPosition(gs.getPhysicalGameState())); if (b2==null) continue; b.addAll(b2); } int d = Math.abs(u.getX()-referenceUnit.getX()) + Math.abs(u.getY()-referenceUnit.getY()); if (closest==null || d<distance) { closest = b; distance = d; } } return closest; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("can-move"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p = term.parameters[0]; if (p instanceof SymbolConstant) { UnitType ut = gs.getUnitTypeTable().getUnitType(p.toString()); if (ut!=null && ut.canMove) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("can-attack"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p = term.parameters[0]; if (p instanceof SymbolConstant) { UnitType ut = gs.getUnitTypeTable().getUnitType(p.toString()); if (ut!=null && ut.canAttack) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("can-harvest"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p = term.parameters[0]; if (p instanceof SymbolConstant) { UnitType ut = gs.getUnitTypeTable().getUnitType(p.toString()); if (ut!=null && ut.canHarvest) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("can-produce"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { if (DEBUG>=1) System.out.println("can-produce.firstMatch: " + Arrays.toString(term.parameters)); Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof SymbolConstant)) { UnitType ut1 = gs.getUnitTypeTable().getUnitType(p1.toString()); if (ut1!=null) { if ((p2 instanceof SymbolConstant)) { UnitType ut2 = gs.getUnitTypeTable().getUnitType(p1.toString()); if (ut1!=null && ut2!=null && ut1.produces.contains(ut2)) return new LinkedList<>(); } else if ((p2 instanceof Variable)) { for(UnitType t:ut1.produces) { List<Binding> l = new LinkedList<>(); if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2,new SymbolConstant(t.name))); } return l; } } } } else if ((p1 instanceof Variable)) { if ((p2 instanceof SymbolConstant)) { UnitType ut2 = gs.getUnitTypeTable().getUnitType(p1.toString()); for(UnitType t:gs.getUnitTypeTable().getUnitTypes()) { if (t.produces.contains(ut2)) { List<Binding> l = new LinkedList<>(); if (!((Variable)p1).ignore()) { l.add(new Binding((Variable)p1,new SymbolConstant(t.name))); } return l; } } } else if ((p2 instanceof Variable)) { for(UnitType t:gs.getUnitTypeTable().getUnitTypes()) { for(UnitType t2:t.produces) { List<Binding> l = new LinkedList<>(); if (!((Variable)p1).ignore()) { l.add(new Binding((Variable)p1,new SymbolConstant(t.name))); } if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2,new SymbolConstant(t2.name))); } return l; } } } } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { if (DEBUG>=1) System.out.println("can-produce.allMatches: " + Arrays.toString(term.parameters)); List<List<Binding>> ll = new LinkedList<>(); Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof SymbolConstant)) { UnitType ut1 = gs.getUnitTypeTable().getUnitType(p1.toString()); if (ut1!=null) { if ((p2 instanceof SymbolConstant)) { UnitType ut2 = gs.getUnitTypeTable().getUnitType(p1.toString()); if (ut1!=null && ut2!=null && ut1.produces.contains(ut2)) ll.add(new LinkedList<>()); } else if ((p2 instanceof Variable)) { for(UnitType t:ut1.produces) { List<Binding> l = new LinkedList<>(); if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2,new SymbolConstant(t.name))); } ll.add(l); } } } } else if ((p1 instanceof Variable)) { if ((p2 instanceof SymbolConstant)) { UnitType ut2 = gs.getUnitTypeTable().getUnitType(p1.toString()); for(UnitType t:gs.getUnitTypeTable().getUnitTypes()) { if (t.produces.contains(ut2)) { List<Binding> l = new LinkedList<>(); if (!((Variable)p1).ignore()) { l.add(new Binding((Variable)p1,new SymbolConstant(t.name))); } ll.add(l); } } } else if ((p2 instanceof Variable)) { for(UnitType t:gs.getUnitTypeTable().getUnitTypes()) { for(UnitType t2:t.produces) { List<Binding> l = new LinkedList<>(); if (!((Variable)p1).ignore()) { l.add(new Binding((Variable)p1,new SymbolConstant(t.name))); } if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2,new SymbolConstant(t2.name))); } ll.add(l); } } } } return ll; } }); predicates.put(new Symbol("in-attack-range"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof IntegerConstant) && (p2 instanceof IntegerConstant)) { Unit u1 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p1).value); Unit u2 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p2).value); if (u1==null || u2==null) return null; int sq_ar = u1.getAttackRange()*u1.getAttackRange(); int dx = u1.getX() - u2.getX(); int dy = u1.getY() - u2.getY(); if ((dx*dx + dy*dy)<=sq_ar) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("in-harvest-range"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof IntegerConstant) && (p2 instanceof IntegerConstant)) { Unit u1 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p1).value); Unit u2 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p2).value); int sq_ar = 1; int dx = u1.getX() - u2.getX(); int dy = u1.getY() - u2.getY(); if ((dx*dx + dy*dy)<=sq_ar) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("in-return-range"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof IntegerConstant) && (p2 instanceof IntegerConstant)) { Unit u1 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p1).value); Unit u2 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p2).value); int sq_ar = 1; int dx = u1.getX() - u2.getX(); int dy = u1.getY() - u2.getY(); if ((dx*dx + dy*dy)<=sq_ar) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("has-resources-to-produce"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { if (DEBUG>=1) System.out.println("has-resources-to-produce.firstMatch"); Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof IntegerConstant) && (p2 instanceof SymbolConstant)) { Player player1 = gs.getPlayer(((IntegerConstant)p1).value); UnitType ut = gs.getUnitTypeTable().getUnitType(((SymbolConstant)p2).toString()); ResourceUsage ru = gs.getResourceUsage(); if (player1.getResources()-ru.getResourcesUsed(player1.getID())>=ut.cost) return new LinkedList<>(); } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { if (DEBUG>=1) System.out.println("has-resources-to-produce.allMatches"); List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("direction"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p = term.parameters[0]; if (p instanceof IntegerConstant) { int d = ((IntegerConstant)p).value; if (d==UnitAction.DIRECTION_UP || d==UnitAction.DIRECTION_RIGHT || d==UnitAction.DIRECTION_DOWN || d==UnitAction.DIRECTION_LEFT) { return new LinkedList<>(); } } else { // TODO this list is populated, but never used List<Binding> l = new LinkedList<>(); if (!((Variable)p).ignore()) { l.add(new Binding((Variable)p,new IntegerConstant(UnitAction.DIRECTION_UP))); } } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<List<Binding>> ll = new LinkedList<>(); Parameter p = term.parameters[0]; if (p instanceof IntegerConstant) { int d = ((IntegerConstant)p).value; if (d==UnitAction.DIRECTION_UP || d==UnitAction.DIRECTION_RIGHT || d==UnitAction.DIRECTION_DOWN || d==UnitAction.DIRECTION_LEFT) { ll.add(new LinkedList<>()); } } else { List<Binding> l = new LinkedList<>(); if (!((Variable)p).ignore()) { l.add(new Binding((Variable)p,new IntegerConstant(UnitAction.DIRECTION_UP))); } ll.add(l); l = new LinkedList<>(); if (!((Variable)p).ignore()) { l.add(new Binding((Variable)p,new IntegerConstant(UnitAction.DIRECTION_RIGHT))); } ll.add(l); l = new LinkedList<>(); if (!((Variable)p).ignore()) { l.add(new Binding((Variable)p,new IntegerConstant(UnitAction.DIRECTION_DOWN))); } ll.add(l); l = new LinkedList<>(); if (!((Variable)p).ignore()) { l.add(new Binding((Variable)p,new IntegerConstant(UnitAction.DIRECTION_LEFT))); } ll.add(l); } return ll; } }); predicates.put(new Symbol("free-building-position"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; if ((p1 instanceof IntegerConstant)) { int pos = ((IntegerConstant)p1).value; int w = gs.getPhysicalGameState().getWidth(); if (gs.free(pos % w, pos / w)) { return new LinkedList<>(); } } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("free-producing-direction"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if (p1 instanceof IntegerConstant) { Unit u1 = gs.getUnit(((IntegerConstant)p1).value); if (p2 instanceof IntegerConstant) { int d = ((IntegerConstant)p2).value; int posx = u1.getX() + UnitAction.DIRECTION_OFFSET_X[d]; int posy = u1.getY() + UnitAction.DIRECTION_OFFSET_Y[d]; if (posx>=0 && posx<gs.getPhysicalGameState().getWidth() && posy>=0 && posy<gs.getPhysicalGameState().getHeight() && gs.free(posx, posy)) return new LinkedList<>(); } else if (p2 instanceof Variable) { for(int d = 0;d<4;d++) { int posx = u1.getX() + UnitAction.DIRECTION_OFFSET_X[d]; int posy = u1.getY() + UnitAction.DIRECTION_OFFSET_Y[d]; if (posx>=0 && posx<gs.getPhysicalGameState().getWidth() && posy>=0 && posy<gs.getPhysicalGameState().getHeight() && gs.free(posx, posy)) { List<Binding> l = new LinkedList<>(); if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2, new IntegerConstant(d))); } return l; } } } } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; List<List<Binding>> ll = new LinkedList<>(); if (p1 instanceof IntegerConstant) { Unit u1 = gs.getUnit(((IntegerConstant)p1).value); if (p2 instanceof IntegerConstant) { int d = ((IntegerConstant)p2).value; int posx = u1.getX() + UnitAction.DIRECTION_OFFSET_X[d]; int posy = u1.getY() + UnitAction.DIRECTION_OFFSET_Y[d]; if (posx>=0 && posx<gs.getPhysicalGameState().getWidth() && posy>=0 && posy<gs.getPhysicalGameState().getHeight() && gs.free(posx, posy)) ll.add(new LinkedList<>()); } else if (p2 instanceof Variable) { for(int d = 0;d<4;d++) { int posx = u1.getX() + UnitAction.DIRECTION_OFFSET_X[d]; int posy = u1.getY() + UnitAction.DIRECTION_OFFSET_Y[d]; if (posx>=0 && posx<gs.getPhysicalGameState().getWidth() && posy>=0 && posy<gs.getPhysicalGameState().getHeight() && gs.free(posx, posy)) { List<Binding> l = new LinkedList<>(); if (!((Variable)p2).ignore()) { l.add(new Binding((Variable)p2, new IntegerConstant(d))); } ll.add(l); } } } } return ll; } }); predicates.put(new Symbol("next-available-unit"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; Parameter p3 = term.parameters[2]; if (!(p1 instanceof IntegerConstant)) return null; if (!(p2 instanceof IntegerConstant)) return null; if (!(p3 instanceof Variable)) return null; int lastunit = ((IntegerConstant)p1).value; int player = ((IntegerConstant)p2).value; Unit found = null; for(Unit u:gs.getUnits()) { if (u.getPlayer()==player && u.getID()>lastunit && gs.getUnitAction(u)==null) { if (found==null) { found = u; } else { if (u.getID()<found.getID()) found = u; } } } if (found!=null) { // System.out.println("next-available-unit " + player + " " + lastunit + " (" + gs.getTime() + "): " + found.getID()); List<Binding> l = new LinkedList<>(); l.add(new Binding((Variable)p3, new IntegerConstant((int)found.getID()))); return l; } // System.out.println("next-available-unit " + player + " " + lastunit + " (" + gs.getTime() + "): -"); return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("no-more-available-units"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if (!(p1 instanceof IntegerConstant)) return null; if (!(p2 instanceof IntegerConstant)) return null; int lastunit = ((IntegerConstant)p1).value; int player = ((IntegerConstant)p2).value; for(Unit u:gs.getUnits()) { if (u.getPlayer()==player && u.getID()>lastunit && gs.getUnitAction(u)==null) { return null; } } return new LinkedList<>(); } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("path"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; if ((p1 instanceof IntegerConstant) && (p2 instanceof IntegerConstant)) { Unit u1 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p1).value); Unit u2 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p2).value); if (u1==null || u2==null) return null; if (pf.pathToPositionInRangeExists(u1, u2.getPosition(gs.getPhysicalGameState()), 1, gs, null)) { return new LinkedList<>(); } else { return null; } } return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); predicates.put(new Symbol("path-to-attack"), new PredicateTester() { public List<Binding> firstMatch(Term term, GameState gs) throws Exception { Parameter p1 = term.parameters[0]; Parameter p2 = term.parameters[1]; // System.out.println("path-to-attack: " + p1 + " to " + p2); if ((p1 instanceof IntegerConstant) && (p2 instanceof IntegerConstant)) { Unit u1 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p1).value); Unit u2 = gs.getPhysicalGameState().getUnit(((IntegerConstant)p2).value); if (u1==null || u2==null) return null; if (pf.pathToPositionInRangeExists(u1, u2.getPosition(gs.getPhysicalGameState()), u1.getAttackRange(), gs, null)) { // System.out.println("path!"); return new LinkedList<>(); } else { // System.out.println("no path"); return null; } } throw new Exception("no path, invalid units: " + p1 + ", " + p2); // return null; } public List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { List<Binding> l = firstMatch(term,gs); if (l==null) { return new LinkedList<>(); } else { List<List<Binding>> ll = new LinkedList<>(); ll.add(l); return ll; } } }); } catch (Exception ex) { ex.printStackTrace(); } } public static List<Binding> firstMatch(Term term, GameState gs) throws Exception { PredicateTester pt = predicates.get(term.functor); if (pt==null) { System.err.println("PredefinedPredicates.firstMatch: undefined predicate " + term); return null; } return pt.firstMatch(term, gs); } public static List<List<Binding>> allMatches(Term term, GameState gs) throws Exception { PredicateTester pt = predicates.get(term.functor); if (pt==null) { System.err.println("PredefinedPredicates.allMatches: undefined predicate " + term); return null; } return pt.allMatches(term, gs); } }
45,945
56.4325
149
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Symbol.java
/* * Creator: Santi Ontanon Villar */ /** * Copyright (c) 2013, Santiago Ontañón All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of the IIIA-CSIC nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. THIS SOFTWARE IS PROVIDED * BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ai.ahtn.domain; import java.util.HashMap; /** * The Class Symbol. */ public class Symbol { static HashMap<String, StringBuffer> sSymbolHash = new HashMap<>(); StringBuffer mSym; /** * Instantiates a new symbol. */ public Symbol(String sym) throws Exception { if (sym == null) { throw new Exception("null name in a Symbol!!!"); } if (sSymbolHash.containsKey(sym)) { mSym = sSymbolHash.get(sym); } else { mSym = new StringBuffer(sym); sSymbolHash.put(sym, mSym); } } /** * Instantiates a new symbol. */ public Symbol(Symbol sym) { mSym = sym.mSym; } public String get() { return mSym.toString(); } public void set(String str) { mSym = new StringBuffer(str); } public boolean equals(Object o) { if (o instanceof String) { return equals((String) o); } else if (o instanceof StringBuffer) { return equals((StringBuffer) o); } else if (o instanceof Symbol) { return equals((Symbol) o); } return false; } public boolean equals(String str) { if (mSym == null) { return str == null; } if (str == null) { return false; } return (mSym.toString().equals(str)); } public boolean equals(StringBuffer str) { if (mSym == null) { return str == null; } if (str == null) { return false; } return (mSym.toString().equals(str.toString())); } public boolean equals(Symbol sym) { return mSym == sym.mSym; } static void arrangeString(StringBuffer str) { int len; while (str.charAt(0) == ' ' || str.charAt(0) == '\n' || str.charAt(0) == '\r' || str.charAt(0) == '\t') { str = str.deleteCharAt(0); } len = str.length(); while (len > 1 && (str.charAt(len - 1) == ' ' || str.charAt(len - 1) == '\n' || str.charAt(len - 1) == '\r' || str.charAt(len - 1) == '\t')) { str = str.deleteCharAt(len - 1); len--; } } public String toString() { return mSym.toString(); } public int hashCode() { if (mSym == null) { return 0; } return mSym.hashCode(); } }
4,048
27.514085
150
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/SymbolConstant.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.ArrayList; import java.util.List; import rts.GameState; /** * * @author santi */ public class SymbolConstant extends Symbol implements Parameter { public SymbolConstant(String sym) throws Exception { super(sym); } public SymbolConstant(Symbol sym) throws Exception { super(sym); } public List<Binding> match(int v) { return null; } public List<Binding> match(String s) { if (this.equals(s)) return new ArrayList<>(); return null; } public Parameter cloneParameter() { // constants do not need to be cloned: return this; } public Parameter resolveParameter(List<Binding> l, GameState gs) { return this; } public Parameter applyBindingsParameter(List<Binding> l) { return this; } public boolean equals(Object o) { if (!(o instanceof SymbolConstant)) return false; SymbolConstant sym = (SymbolConstant)o; return mSym == sym.mSym; } }
1,273
21.350877
79
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Term.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import ai.ahtn.domain.LispParser.LispElement; import ai.ahtn.domain.LispParser.LispParser; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import rts.GameState; /** * * @author santi */ public class Term { public static int DEBUG = 0; Symbol functor; Parameter parameters[]; public Term() { functor = null; parameters = null; } public Term(Symbol f) { functor = f; parameters = null; } public Term(Symbol f, Parameter p) { functor = f; parameters = new Parameter[1]; parameters[0] = p; } public Term(Symbol f, Parameter p1, Parameter p2) { functor = f; parameters = new Parameter[2]; parameters[0] = p1; parameters[1] = p2; } public Term(Symbol f, Parameter []p) { functor = f; parameters = p; } public Symbol getFunctor() { return functor; } public static Term fromString(String s) throws Exception { return Term.fromLispElement(LispParser.parseString(s).get(0)); } public static Term fromLispElement(LispElement e) throws Exception { Term t = new Term(); t.functor = new Symbol(e.children.get(0).element); int l = e.children.size()-1; if (l==0) { t.parameters = null; } else { t.parameters = new Parameter[l]; for(int i = 0;i<l;i++) { // Determine whether it's a constant, variable, or function: LispElement p_e = e.children.get(i+1); if (p_e.children!=null) { t.parameters[i] = Function.fromLispElement(p_e); } else { String v = p_e.element; if (v.startsWith("?")) { t.parameters[i] = new Variable(v); } else { try { int iv = Integer.parseInt(v); t.parameters[i] = new IntegerConstant(iv); } catch(Exception ex) { // it's not an integer: t.parameters[i] = new SymbolConstant(v); } } } } } return t; } public void renameVariables(int r) { if (parameters!=null) { for(Parameter p:parameters) { if (p instanceof Variable) { ((Variable)p).setRenaming(r); } else if (p instanceof Function) { ((Function)p).renameVariables(r); } } } } // assumes that: // - the parameters in the terms are not functions // - there are no shared variables between the terms // modifies the term on the left ("this") // GameState is needed to resolve functions in case there are, if no functions appear, then it can be null public List<Binding> simpleUnificationDestructiveNoSharedVariables(Term t, GameState gs) throws Exception { if (DEBUG>=1) System.out.println("simpleUnificationDestructiveNoSharedVariables: start"); if (!functor.equals(t.functor)) return null; if (parameters.length!=t.parameters.length) return null; List<Binding> bindings = new LinkedList<>(); Parameter resolved[] = new Parameter[parameters.length]; for(int i = 0;i<parameters.length;i++) { Parameter p1 = parameters[i].resolveParameter(bindings, gs); Parameter p2 =t. parameters[i].resolveParameter(bindings, gs); if (DEBUG>=1) System.out.println("simpleUnificationDestructiveNoSharedVariables: " + i + " -> " + p1 + " U " + p2); resolved[i] = p1; if (p1 instanceof Variable) { if (!((p2 instanceof Variable) && p2.equals(p1))) { if (!((Variable)p1).ignore()) bindings.add(new Binding((Variable)p1, p2)); } } else { if (p2 instanceof Variable) { if (!((Variable)p2).ignore()) bindings.add(new Binding((Variable)p2, p1)); } else { // otherwise, they are constants, and must be identical: if (!p1.equals(p2)) return null; } } } // if unification is successful, apply it: parameters = resolved; return bindings; } // applies all the bindings and evaluates in case it is a function: // - this should be equivalent to "clone" and then "applyBindings", but it is faster to do it in one step // Also, if there are no bindings, we save the clone operation public Term resolve(List<Binding> l, GameState gs) throws Exception { if (l.isEmpty()) return this; Term t = new Term(); t.functor = functor; t.parameters = new Parameter[parameters.length]; for(int i = 0;i<t.parameters.length;i++) { t.parameters[i] = parameters[i].resolveParameter(l, gs); } return t; } public Term clone() { Term t = new Term(functor); if (parameters!=null) { t.parameters = new Parameter[parameters.length]; for(int i = 0;i<t.parameters.length;i++) { t.parameters[i] = parameters[i].cloneParameter(); } } return t; } // applies all the bindings public void applyBindings(List<Binding> l) throws Exception { if (l.isEmpty()) return; if (parameters!=null) { for(int i = 0;i<parameters.length;i++) { parameters[i] = parameters[i].applyBindingsParameter(l); } } } public boolean isGround() { for(Parameter p:parameters) { if (p instanceof Variable) return false; if (p instanceof Function) { if (!((Function)p).isGround()) return false; } } return true; } public void countVariableAppearances(HashMap<Symbol,Integer> appearances) throws Exception { for(Parameter p:parameters) { if ((p instanceof Variable) && !((Variable)p).ignore()) { Symbol name = ((Variable)p).getName(); if (appearances.containsKey(name)) { appearances.put(name, appearances.get(name)+1); } else { appearances.put(name,1); } } if (p instanceof Function) { ((Function)p).countVariableAppearances(appearances); } } } public void replaceSingletonsByWildcards(List<Symbol> singletons) throws Exception { for(int i = 0;i<parameters.length;i++) { Parameter p = parameters[i]; if ((p instanceof Variable)) { Symbol name = ((Variable)p).getName(); if (singletons.contains(name)) { parameters[i] = new Variable(new Symbol("?_")); } } if (p instanceof Function) { ((Function)p).replaceSingletonsByWildcards(singletons); } } } public boolean equals(Object o) { if (!(o instanceof Term)) return false; Term t = (Term)o; if (!functor.equals(t.functor)) return false; if (parameters.length!=t.parameters.length) return false; for(int i = 0;i<parameters.length;i++) { if (!parameters[i].equals(t.parameters[i])) return false; } return true; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(functor); if (parameters!=null) { for (Parameter parameter : parameters) { sb.append(" "); sb.append(parameter); } } sb.append(")"); return sb.toString(); } }
8,527
31.06015
128
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/Variable.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain; import java.util.LinkedList; import java.util.List; import rts.GameState; /** * * @author santi * * */ public class Variable implements Parameter { static Symbol variable_to_ignore; // this is the name of the "_" variable in prolog, for which no bindings should be kept Symbol name; int renaming = 0; // this is used to differenciate variables when cloning terms/clauses public Variable(String sym) throws Exception { name = new Symbol(sym); } public Variable(Symbol sym) { name = sym; } public Symbol getName() { return name; } public void setRenaming(int r) { renaming = r; } public boolean ignore() throws Exception { if (variable_to_ignore==null) variable_to_ignore = new Symbol("?_"); return name.equals(variable_to_ignore); } public List<Binding> match(int v) throws Exception { List<Binding> l = new LinkedList<>(); if (!ignore()) l.add(new Binding(this,new IntegerConstant(v))); return l; } public List<Binding> match(String s) throws Exception { List<Binding> l = new LinkedList<>(); if (!ignore()) l.add(new Binding(this,new SymbolConstant(new Symbol(s)))); return l; } public Parameter cloneParameter() { Variable v = new Variable(name); v.renaming = renaming; return v; } public Parameter resolveParameter(List<Binding> l, GameState gs) throws Exception { if (l==null) return this; return applyBindingsParameter(l); } public Parameter applyBindingsParameter(List<Binding> l) throws Exception { if (ignore()) return this; Parameter tmp = this; for(Binding b:l) { if (b.v.equals(tmp)) tmp = b.p; } return tmp; } public boolean equals(Object o) { if (!(o instanceof Variable)) return false; Variable v = (Variable)o; return name.equals(v.name) && (renaming == v.renaming); } public String toString() { if (renaming==0) { return name.toString(); } else { return name + "/" + renaming; } } }
2,456
24.59375
128
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/LispParser/LispElement.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain.LispParser; import java.util.LinkedList; import java.util.List; /** * * @author santi */ public class LispElement { public String element; public List<LispElement> children; // create a new atom: public LispElement(String e) { element = e; } // create a new list: public LispElement() { children = new LinkedList<>(); } public String toString() { return toString(0); } public String toString(int tabs) { StringBuilder tabstr = new StringBuilder(); for (int i = 0; i < tabs; i++) { tabstr.append(" "); } if (children == null) { return tabstr + element; } else { StringBuilder tmp = new StringBuilder(tabstr + "(\n"); for(LispElement e:children) { tmp.append(e.toString(tabs + 1)).append("\n"); } tmp.append(tabstr).append(")"); return tmp.toString(); } } }
1,226
21.722222
79
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/LispParser/LispParser.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain.LispParser; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; import java.util.LinkedList; import java.util.List; /** * * @author santi */ public class LispParser { public static int DEBUG = 0; public static List<LispElement> parseString(String s) throws Exception { BufferedReader br = new BufferedReader(new StringReader(s)); return parseLisp(br); } public static List<LispElement> parseLispFile(String fileName) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileName)); return parseLisp(br); } public static List<LispElement> parseLisp(BufferedReader br) throws Exception { List<LispElement> l = new LinkedList<>(); List<LispElement> stack = new LinkedList<>(); LispTokenizer lt = new LispTokenizer(br); String token = lt.nextToken(); while(token!=null) { if (DEBUG>=1) System.out.println("next token: " + token); if (token.equals("(")) { stack.add(0,new LispElement()); } else if (token.equals(")")) { LispElement e = stack.remove(0); if (stack.isEmpty()) { l.add(e); } else { stack.get(0).children.add(e); } } else { if (stack.isEmpty()) { l.add(new LispElement(token)); } else { stack.get(0).children.add(new LispElement(token)); } } token = lt.nextToken(); } return l; } }
1,926
28.646154
93
java
MicroRTS
MicroRTS-master/src/ai/ahtn/domain/LispParser/LispTokenizer.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.domain.LispParser; import java.io.BufferedReader; /** * * @author santi */ public class LispTokenizer { BufferedReader br; int nextCharacter = -1; public LispTokenizer(BufferedReader a_br) { br = a_br; } public int nextCharacter() throws Exception { if (nextCharacter==-1) { return br.read(); } else { int tmp = nextCharacter; nextCharacter = -1; return tmp; } } public String nextToken() throws Exception { /* tokens can be: ( ) anything else separated by spaces we ignore anything in a line after ";" we ignore anything in between "#|" and "|# */ if (!br.ready()) return null; StringBuilder currentToken = null; do { int c = nextCharacter(); if (c==-1) break; if (c==';') { // skip the whole line: br.readLine(); if (currentToken!=null) return currentToken.toString(); } else if (c==' ' || c=='\n' || c=='\r' || c=='\t') { if (currentToken!=null) return currentToken.toString(); } else if (c=='(' || c==')') { if (currentToken==null) { return "" + (char)c; } else { nextCharacter = c; return currentToken.toString(); } } else { if (currentToken==null) { currentToken = new StringBuilder("" + (char) c); } else { currentToken.append((char) c); } if (currentToken.length()>=2 && currentToken.toString().endsWith("#|")) { currentToken = new StringBuilder(currentToken.substring(0, currentToken.length() - 2)); // skip comments: int previous = -1; while(br.ready()) { c = nextCharacter(); if (c==-1) break; if (c=='#' && previous=='|') break; previous = c; } if (currentToken.length()==0) { currentToken = null; } else { return currentToken.toString(); } } } }while(br.ready()); return currentToken.toString(); } }
2,860
28.802083
107
java
MicroRTS
MicroRTS-master/src/ai/ahtn/planner/AdversarialBoundedDepthPlannerAlphaBeta.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.planner; import ai.ahtn.domain.Binding; import ai.ahtn.domain.DomainDefinition; import ai.ahtn.domain.MethodDecomposition; import ai.ahtn.domain.PredefinedOperators; import ai.ahtn.domain.Term; import ai.core.AI; import ai.evaluation.EvaluationFunction; import java.util.ArrayList; import java.util.List; import rts.GameState; import rts.PlayerAction; import util.Pair; /** * * @author santi */ public class AdversarialBoundedDepthPlannerAlphaBeta { public static int DEBUG = 0; public static boolean ALPHA_BETA_CUT = true; // - if the following variable is set to "false", the search will stop // as soon as the is a point where we have the number of desired actions // - if the following variable is set to "true", even after the number of // desired actions is reached, simulation will continue until the next choice // point, in order to get as much information as possible about the effects of the // selected actions. public static boolean SIMULATE_UNTIL_NEXT_CHOICEPOINT = true; MethodDecomposition maxPlanRoot; MethodDecomposition minPlanRoot; int maxPlayer; GameState gs; DomainDefinition dd; EvaluationFunction f; AI playoutAI; int PLAYOUT_LOOKAHEAD = 100; int maxDepth = 3; int operatorExecutionTimeout = 1000; static int MAX_TREE_DEPTH = 25; static int nPlayouts = 0; // number of leaves in the current search (includes all the trees in the current ID process) List<AdversarialChoicePoint> stack; List<Integer> trail; // how many bindings to remove, when popping this element of the stack List<Binding> bindings; int renamingIndex = 1; // for renaming variables boolean lastRunSolvedTheProblem = false; // if this is true, no need to continue iterative deepening // statistics public static int n_iterative_deepening_runs = 0; public static double max_iterative_deepening_depth = 0; public static double average_iterative_deepening_depth = 0; public static int n_trees = 0; public static double max_tree_leaves = 0; public static double last_tree_leaves = 0; public static double average_tree_leaves = 0; public static double max_tree_nodes = 0; public static double last_tree_nodes = 0; public static double average_tree_nodes = 0; public static double max_tree_depth = 0; public static double last_tree_depth = 0; public static double average_tree_depth = 0; public static double max_time_depth = 0; public static double last_time_depth = 0; public static double average_time_depth = 0; public static void clearStatistics() { n_iterative_deepening_runs = 0; max_iterative_deepening_depth = 0; average_iterative_deepening_depth = 0; n_trees = 0; max_tree_leaves = 0; last_tree_leaves = 0; average_tree_leaves = 0; max_tree_nodes = 0; last_tree_nodes = 0; average_tree_nodes = 0; max_tree_depth = 0; last_tree_depth = 0; average_tree_depth = 0; max_time_depth = 0; last_time_depth = 0; average_time_depth = 0; } // depth is in actions: public AdversarialBoundedDepthPlannerAlphaBeta(Term goalPlayerMax, Term goalPlayerMin, int a_maxPlayer, int depth, int playoutLookahead, GameState a_gs, DomainDefinition a_dd, EvaluationFunction a_f, AI a_playoutAI) { maxPlanRoot = new MethodDecomposition(goalPlayerMax,null); minPlanRoot = new MethodDecomposition(goalPlayerMin,null); minPlanRoot.renameVariables(1); renamingIndex = 2; maxPlayer = a_maxPlayer; gs = a_gs; dd = a_dd; stack = null; maxDepth = depth; PLAYOUT_LOOKAHEAD = playoutLookahead; f = a_f; playoutAI = a_playoutAI; // System.out.println(a_dd); } public Pair<MethodDecomposition,MethodDecomposition> getBestPlan() throws Exception { return getBestPlan(-1, -1, false); } // if "forceAnswer == true", then even if the search does not finish due to the time limit, // the best action found so far is returned public Pair<MethodDecomposition,MethodDecomposition> getBestPlan(long timeLimit, int maxPlayouts, boolean forceAnswer) throws Exception { if (DEBUG>=1) System.out.println("AdversarialBoundedDepthPlanner.getBestPlan"); if (stack==null) { if (DEBUG>=1) System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: first time, initializing stack"); stack = new ArrayList<>(); stack.add(0,new AdversarialChoicePoint(maxPlanRoot, minPlanRoot, maxPlanRoot, minPlanRoot, gs,0,-1,-EvaluationFunction.VICTORY,EvaluationFunction.VICTORY,false)); trail = new ArrayList<>(); trail.add(0,0); bindings = new ArrayList<>(); } last_tree_leaves = 0; last_tree_nodes = 0; last_tree_depth = 0; last_time_depth = 0; AdversarialChoicePoint root = stack.get(stack.size()-1); boolean timeout = false; // int n_times_deadend_is_reached = 0; do{ if ((timeLimit>0 && System.currentTimeMillis()>=timeLimit) || (maxPlayouts>0 && nPlayouts>=maxPlayouts)){ // if (!timeout) System.out.println(root.gs.getTime() + ": timeout!!!! depth: " + maxDepth +", with leaves: " + last_tree_leaves + " (timelimit: " + timeLimit + " currenttime: " + System.currentTimeMillis() + ")"); // System.out.println("maxDepth: " + maxDepth + ", nPlayouts: " + nPlayouts + ", n_times_deadend_is_reached: " + n_times_deadend_is_reached); if (forceAnswer) { timeout = true; } else { return null; } } // statistics: int treedepth = stack.size(); if (treedepth>=last_tree_depth) last_tree_depth = treedepth; AdversarialChoicePoint choicePoint = stack.get(0); choicePoint.restoreExecutionState(); if (DEBUG>=2) { System.out.println("\nAdversarialBoundedDepthPlanner.getBestPlan: stack size: " + stack.size() + ", bindings: " + bindings.size() + ", gs.time: " + choicePoint.gs.getTime() + ", operators: " + root.choicePointPlayerMin.getOperatorsBeingExecuted() + ", " + root.choicePointPlayerMax.getOperatorsBeingExecuted()); /* if (stack.size()==23) { maxPlanRoot.printDetailed(); minPlanRoot.printDetailed(); } */ } if (DEBUG>=3) { System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: bindings: " + bindings); System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: trail: " + trail); System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: stack:"); for(int i = 0;i<stack.size();i++) { System.out.println((stack.size()-i) + ": " + stack.get(i)); } maxPlanRoot.printDetailed(); minPlanRoot.printDetailed(); } int bl = bindings.size(); boolean pop = true; while(!timeout && choicePoint.nextExpansion(dd, bindings, renamingIndex, choicePoint)) { renamingIndex++; // System.out.println("bindings: " + bindings); AdversarialChoicePoint tmp = simulateUntilNextChoicePoint(bindings, choicePoint); if (tmp==null) { // System.out.println(" tmp = null"); // execution failure: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: plan execution failed"); choicePoint.restoreExecutionState(); // n_times_deadend_is_reached++; } else if ((tmp.choicePointPlayerMax==null && tmp.choicePointPlayerMin==null)) { last_tree_nodes++; // execution success: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: plan execution success or depth limit reached"); if (DEBUG>=3) System.out.println(tmp.gs); if (DEBUG>=3) { maxPlanRoot.printDetailed(); minPlanRoot.printDetailed(); } // use evaluation function float eval = playout(maxPlayer, tmp.gs); // float eval = f.evaluate(maxPlayer, 1-maxPlayer, tmp.gs); last_tree_leaves++; boolean alphaBetaTest = choicePoint.processEvaluation(eval, choicePoint.maxPlanRoot, choicePoint.minPlanRoot, true); if (!ALPHA_BETA_CUT) alphaBetaTest = false; double time = tmp.gs.getTime() - root.gs.getTime(); if (time>last_time_depth) last_time_depth = time; if (DEBUG>=2) { System.out.println("---- ---- ---- ----"); System.out.println(tmp.gs); System.out.println("Evaluation: " + eval); System.out.println("Bindings: " + bindings.size()); System.out.println("Bindings: " + bindings); System.out.println("Max plan:"); List<Pair<Integer,List<Term>>> l = maxPlanRoot.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l) System.out.println(" " + a.m_a + ": " + a.m_b); System.out.println("Min plan:"); List<Pair<Integer,List<Term>>> l2 = minPlanRoot.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l2) System.out.println(" " + a.m_a + ": " + a.m_b); } choicePoint.restoreExecutionState(); // undo the bindings: int n = bindings.size() - bl; for(int i = 0;i<n;i++) bindings.remove(0); if (alphaBetaTest) break; } else { last_tree_nodes++; // System.out.println(" next choice point"); // next choice point: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.getBestPlan: stack push"); stack.add(0,tmp); trail.add(0,bindings.size() - bl); // System.out.println("trail.add(" + (bindings.size() - bl) + ")"); pop = false; break; } } if (pop) { if (!timeout && nPlayouts==0) { AdversarialChoicePoint cp = stack.get(0); if ((cp.choicePointPlayerMax!=null && cp.choicePointPlayerMax.getType() == MethodDecomposition.METHOD_METHOD) || (cp.choicePointPlayerMax==null && cp.choicePointPlayerMin!=null && cp.choicePointPlayerMin.getType() == MethodDecomposition.METHOD_METHOD)) { System.err.println("Popping without finding any decomposition:"); System.err.println(cp); System.err.println(bindings); System.err.println(cp.gs); throw new Error("Popping without finding any decomposition"); } } // System.out.println("Popping:"); do { // System.out.println(" pop"); pop = false; stackPop(); if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.nextPlan: stack pop"); // propagate the value up: if (!stack.isEmpty()) { if (choicePoint.minimaxType==-1) { // this means that this was a dead-end /* float eval = f.evaluate(0, 1, choicePoint.gs); nleaves++; choicePoint.processEvaluation(eval, (choicePoint.choicePointPlayerMax!=null ? null:maxPlanRoot), (choicePoint.choicePointPlayerMax==null ? null:minPlanRoot)); // float eval = f.evaluate(0, 1, choicePoint.gs); // stack.get(0).processEvaluaiton(eval, maxPlanRoot, minPlanRoot); pop = stack.get(0).processEvaluation(choicePoint.bestEvaluation, choicePoint.bestMaxPlan, choicePoint.bestMinPlan); */ } else { pop = stack.get(0).processEvaluation(choicePoint.bestEvaluation, choicePoint.bestMaxPlan, choicePoint.bestMinPlan, false); if (!ALPHA_BETA_CUT) pop = false; } if (pop) { choicePoint = stack.get(0); } } }while(pop && !stack.isEmpty()); } }while(!stack.isEmpty()); /* if (last_time_depth==0) { System.out.println(root.gs); System.exit(1); } */ // System.out.println(root.gs.getTime() + ": depth: " + maxDepth + ", maxtreedepth: " + last_tree_depth + ", maxtimedepth: " + last_time_depth + ", nleaves: " + last_tree_leaves + ", evaluation: " + root.bestEvaluation); if (DEBUG>=1) System.out.println(last_tree_leaves); /* { System.out.println(nleaves + " -> best move: " + root.bestEvaluation); System.out.println("Max plan:"); if (root.bestMaxPlan!=null) { List<Pair<Integer,List<Term>>> l = root.bestMaxPlan.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l) System.out.println(" " + a.m_a + ": " + a.m_b); } if (root.bestMinPlan!=null) { System.out.println("Min plan:"); List<Pair<Integer,List<Term>>> l2 = root.bestMinPlan.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l2) System.out.println(" " + a.m_a + ": " + a.m_b); } } */ stack = null; // System.out.println("AdversarialBoundedDepthPlanner.nextPlan: options exhausted for rootPlan (timeout = " + timeout + ", nPLayouts = "+nPlayouts+")"); if (DEBUG>=1) System.out.println("AdversarialBoundedDepthPlanner.nextPlan: options exhausted for rootPlan"); if (DEBUG>=1) System.out.println("best evaluation: " + root.bestEvaluation); if (root.bestEvaluation==EvaluationFunction.VICTORY || root.bestEvaluation==-EvaluationFunction.VICTORY) lastRunSolvedTheProblem = true; // if this happens, it means that there is no plan that can be made for the current situation: if (root.bestMaxPlan==null && root.bestMinPlan==null) { lastRunSolvedTheProblem = true; System.out.println("No AHTN can be found for situation:"); System.out.println(gs); } return new Pair<>(root.bestMaxPlan, root.bestMinPlan); } /* The search will end when: - the tree is searched to the maximum depth - or when System.currentTimeMillis() is larger or equal than timeLimit - or when int is larger or equal to maxPlayouts */ public static Pair<MethodDecomposition,MethodDecomposition> getBestPlanIterativeDeepening(Term goalPlayerMax, Term goalPlayerMin, int a_maxPlayer, int timeout, int maxPlayouts, int a_playoutLookahead, GameState a_gs, DomainDefinition a_dd, EvaluationFunction a_f, AI a_playoutAI) throws Exception { long start = System.currentTimeMillis(); long timeLimit = start + timeout; if (timeout<=0) timeLimit = 0; Pair<MethodDecomposition,MethodDecomposition> bestLastDepth = null; double tmp_leaves = 0, tmp_nodes = 0, tmp_depth = 0, tmp_time = 0; int nPlayoutsBeforeStartingLastTime = 0, nPlayoutsUSedLastTime = 0; nPlayouts = 0; for(int depth = 1;;depth++) { // for(int depth = 6;depth<7;depth++) { Pair<MethodDecomposition,MethodDecomposition> best = null; long currentTime = System.currentTimeMillis(); if (DEBUG>=1) System.out.println("Iterative Deepening depth: " + depth + " (total time so far: " + (currentTime - start) + "/" + timeout + ")" + " (total playouts so far: " + nPlayouts + "/" + maxPlayouts + ")"); AdversarialBoundedDepthPlannerAlphaBeta planner = new AdversarialBoundedDepthPlannerAlphaBeta(goalPlayerMax, goalPlayerMin, a_maxPlayer, depth, a_playoutLookahead, a_gs, a_dd, a_f, a_playoutAI); nPlayoutsBeforeStartingLastTime = nPlayouts; if (depth<=MAX_TREE_DEPTH) { int nPlayoutsleft = maxPlayouts - nPlayouts; if (maxPlayouts<0 || nPlayoutsleft>nPlayoutsUSedLastTime) { if (DEBUG>=1) System.out.println("last time we used " + nPlayoutsUSedLastTime + ", and there are " + nPlayoutsleft + " left, trying one more depth!"); best = planner.getBestPlan(timeLimit, maxPlayouts, (bestLastDepth == null)); } else { if (DEBUG>=1) System.out.println("last time we used " + nPlayoutsUSedLastTime + ", and there are only " + nPlayoutsleft + " left..., canceling search"); } } nPlayoutsUSedLastTime = nPlayouts - nPlayoutsBeforeStartingLastTime; if (DEBUG>=1) System.out.println(" time taken: " + (System.currentTimeMillis() - currentTime)); // print best plan: if (DEBUG>=1) { if (best!=null) { // if (best.m_a!=null) best.m_a.printDetailed(); System.out.println("Max plan:"); if (best.m_a!=null) { List<Pair<Integer,List<Term>>> l = best.m_a.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l) System.out.println(" " + a.m_a + ": " + a.m_b); } if (best.m_b!=null) { System.out.println("Min plan:"); List<Pair<Integer,List<Term>>> l2 = best.m_b.convertToOperatorList(); for(Pair<Integer, List<Term>> a:l2) System.out.println(" " + a.m_a + ": " + a.m_b); } } } if (best!=null) { bestLastDepth = best; tmp_leaves = last_tree_leaves; tmp_nodes = last_tree_nodes; // System.out.println("nodes: " + tmp_nodes + ", leaves: " + tmp_leaves); tmp_depth = last_tree_depth; tmp_time = last_time_depth; if (planner.lastRunSolvedTheProblem) { // statistics: n_trees++; if (tmp_leaves>max_tree_leaves) max_tree_leaves=tmp_leaves; average_tree_leaves += tmp_leaves; if (tmp_nodes>max_tree_nodes) max_tree_nodes=tmp_nodes; average_tree_nodes += tmp_nodes; average_tree_depth += tmp_depth; if (tmp_depth>=max_tree_depth) max_tree_depth = tmp_depth; average_time_depth += tmp_time; if (tmp_time>=max_time_depth) max_time_depth = tmp_time; n_iterative_deepening_runs++; average_iterative_deepening_depth+=depth; if (depth>max_iterative_deepening_depth) max_iterative_deepening_depth = depth; return bestLastDepth; } } else { // statistics: n_trees++; if (tmp_leaves>max_tree_leaves) max_tree_leaves=tmp_leaves; average_tree_leaves += tmp_leaves; if (tmp_nodes>max_tree_nodes) max_tree_nodes=tmp_nodes; average_tree_nodes += tmp_nodes; average_tree_depth += tmp_depth; if (tmp_depth>=max_tree_depth) max_tree_depth = tmp_depth; average_time_depth += tmp_time; if (tmp_time>=max_time_depth) max_time_depth = tmp_time; n_iterative_deepening_runs++; average_iterative_deepening_depth+=depth-1; // the last one couldn't finish, so we have to add "depth-1" if ((depth-1)>max_iterative_deepening_depth) max_iterative_deepening_depth = depth-1; return bestLastDepth; } } // return bestLastDepth; } /* - Return value "null" means execution failure - Return value <null,GameState> means execution success - <md,GameState> represents a choice point */ public AdversarialChoicePoint simulateUntilNextChoicePoint(List<Binding> bindings, AdversarialChoicePoint previous_cp) throws Exception { GameState gs = previous_cp.gs; GameState gs2 = gs.clone(); int lastTimeOperatorsIssued = previous_cp.getLastTimeOperatorsIssued(); int operatorDepth = previous_cp.getOperatorDepth(); // System.out.println(gs2.getTime() + " - " + lastTimeOperatorsIssued + " - " + operatorDepth); while(true) { // System.out.println(bindings); if (!SIMULATE_UNTIL_NEXT_CHOICEPOINT) { if (operatorDepth>=maxDepth && gs2.getTime()>lastTimeOperatorsIssued) { // max depth reached: return new AdversarialChoicePoint(null,null,previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued,previous_cp.getAlpha(),previous_cp.getBeta(),false); } } List<MethodDecomposition> actions1 = new ArrayList<>(); List<MethodDecomposition> actions2 = new ArrayList<>(); List<MethodDecomposition> choicePoints1 = new ArrayList<>(); List<MethodDecomposition> choicePoints2 = new ArrayList<>(); int er1 = previous_cp.maxPlanRoot.executionCycle(gs2, actions1, choicePoints1, previous_cp); int er2 = previous_cp.minPlanRoot.executionCycle(gs2, actions2, choicePoints2, previous_cp); if (SIMULATE_UNTIL_NEXT_CHOICEPOINT) { if (operatorDepth>=maxDepth && gs2.getTime()>lastTimeOperatorsIssued && (er1==MethodDecomposition.EXECUTION_CHOICE_POINT || er2==MethodDecomposition.EXECUTION_CHOICE_POINT)) { // max depth reached: // System.out.println(operatorDepth + " >= " + maxDepth); return new AdversarialChoicePoint(null,null,previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued,previous_cp.getAlpha(),previous_cp.getBeta(),false); } } if (er1==MethodDecomposition.EXECUTION_SUCCESS && er2==MethodDecomposition.EXECUTION_SUCCESS) { return new AdversarialChoicePoint(null,null,previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued,previous_cp.getAlpha(),previous_cp.getBeta(),false); } else if (er1==MethodDecomposition.EXECUTION_FAILURE || er2==MethodDecomposition.EXECUTION_FAILURE) { if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: execution failure " + er1 + ", " + er2); return null; } else if (er1==MethodDecomposition.EXECUTION_CHOICE_POINT || er2==MethodDecomposition.EXECUTION_CHOICE_POINT) { MethodDecomposition cp_md = (choicePoints1.isEmpty() ? null:choicePoints1.get(0)); if (cp_md==null) cp_md = (choicePoints2.isEmpty() ? null:choicePoints2.get(0)); if (cp_md.getType() == MethodDecomposition.METHOD_NON_BRANCHING_CONDITION) { AdversarialChoicePoint acp = new AdversarialChoicePoint((choicePoints1.isEmpty() ? null:choicePoints1.get(0)), (choicePoints2.isEmpty() ? null:choicePoints2.get(0)), previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued, previous_cp.getAlpha(),previous_cp.getBeta(),false); // System.out.println("testing non-branching condition: " + cp_md); if (!acp.nextExpansion(dd, bindings, renamingIndex, acp)) return null; renamingIndex++; } else { return new AdversarialChoicePoint((choicePoints1.isEmpty() ? null:choicePoints1.get(0)), (choicePoints2.isEmpty() ? null:choicePoints2.get(0)), previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued, previous_cp.getAlpha(),previous_cp.getBeta(),false); } } else if ((er1==MethodDecomposition.EXECUTION_WAITING_FOR_ACTION || er2==MethodDecomposition.EXECUTION_WAITING_FOR_ACTION) && er1!=MethodDecomposition.EXECUTION_ACTION_ISSUE && er2!=MethodDecomposition.EXECUTION_ACTION_ISSUE) { boolean gameover = gs2.cycle(); if (gameover) return new AdversarialChoicePoint(null,null,previous_cp.maxPlanRoot,previous_cp.minPlanRoot, gs2,operatorDepth,lastTimeOperatorsIssued,previous_cp.getAlpha(),previous_cp.getBeta(),false); List<MethodDecomposition> toDelete = null; if (previous_cp.maxPlanRoot.getOperatorsBeingExecuted()!=null) { for(MethodDecomposition md:previous_cp.maxPlanRoot.getOperatorsBeingExecuted()) { previous_cp.captureExecutionStateNonRecursive(md); // issue action: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: continuing executing operator " + md.getUpdatedTerm()); if (PredefinedOperators.execute(md, gs2) || gs2.getTime()>md.getUpdatedTermCycle()+operatorExecutionTimeout) { // if (gs2.getTime()>md.getUpdatedTermCycle()+operatorExecutionTimeout) System.out.println("operator timed out: " + md.getUpdatedTerm()); md.setExecutionState(2); if (toDelete==null) toDelete = new ArrayList<>(); toDelete.add(md); if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: operator complete (1)."); } else { md.setExecutionState(1); } } if (toDelete!=null) previous_cp.maxPlanRoot.getOperatorsBeingExecuted().removeAll(toDelete); } if (previous_cp.minPlanRoot.getOperatorsBeingExecuted()!=null) { toDelete = null; for(MethodDecomposition md:previous_cp.minPlanRoot.getOperatorsBeingExecuted()) { previous_cp.captureExecutionStateNonRecursive(md); // issue action: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: continuing executing operator " + md.getUpdatedTerm()); if (PredefinedOperators.execute(md, gs2) || gs2.getTime()>md.getUpdatedTermCycle()+operatorExecutionTimeout) { // if (gs2.getTime()>md.getUpdatedTermCycle()+operatorExecutionTimeout) System.out.println("operator timed out: " + md.getUpdatedTerm()); md.setExecutionState(2); if (toDelete==null) toDelete = new ArrayList<>(); toDelete.add(md); if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: operator complete (2)."); } else { md.setExecutionState(1); } } if (toDelete!=null) previous_cp.minPlanRoot.getOperatorsBeingExecuted().removeAll(toDelete); } } if (er1==MethodDecomposition.EXECUTION_ACTION_ISSUE || er2==MethodDecomposition.EXECUTION_ACTION_ISSUE) { if (gs2.getTime()>lastTimeOperatorsIssued) { lastTimeOperatorsIssued = gs2.getTime(); operatorDepth++; } } if (er1==MethodDecomposition.EXECUTION_ACTION_ISSUE) { for(MethodDecomposition md:actions1) { previous_cp.captureExecutionStateNonRecursive(md); md.setUpdatedTerm(md.getTerm().clone()); md.getUpdatedTerm().applyBindings(bindings); md.setUpdatedTermCycle(gs2.getTime()); // issue action: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: executing operator " + md.getUpdatedTerm()); md.setOperatorExecutingState(0); // System.out.println(md.getUpdatedTerm() + " <- " + bindings); if (PredefinedOperators.execute(md, gs2)) { md.setExecutionState(2); if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: operator complete (3)."); } else { md.setExecutionState(1); if (previous_cp.maxPlanRoot.getOperatorsBeingExecuted()==null) { previous_cp.maxPlanRoot.setOperatorsBeingExecuted(new ArrayList<>()); } previous_cp.maxPlanRoot.getOperatorsBeingExecuted().add(md); } } } if (er2==MethodDecomposition.EXECUTION_ACTION_ISSUE) { for(MethodDecomposition md:actions2) { previous_cp.captureExecutionStateNonRecursive(md); md.setUpdatedTerm(md.getTerm().clone()); md.getUpdatedTerm().applyBindings(bindings); md.setUpdatedTermCycle(gs2.getTime()); // issue action: if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: executing operator " + md.getUpdatedTerm()); md.setOperatorExecutingState(0); if (PredefinedOperators.execute(md, gs2)) { md.setExecutionState(2); if (DEBUG>=2) System.out.println("AdversarialBoundedDepthPlanner.simulateUntilNextChoicePoint: operator complete (4)."); } else { md.setExecutionState(1); if (previous_cp.minPlanRoot.getOperatorsBeingExecuted()==null) { previous_cp.minPlanRoot.setOperatorsBeingExecuted(new ArrayList<>()); } previous_cp.minPlanRoot.getOperatorsBeingExecuted().add(md); } } } } } public void stackPop() { AdversarialChoicePoint cp = stack.remove(0); cp.restoreAfterPop(); int tmp = trail.remove(0); if (DEBUG>=2) System.out.println("StackPop! removing " + tmp + " bindings."); for(int i = 0;i<tmp;i++) bindings.remove(0); if (!stack.isEmpty()) stack.get(0).restoreExecutionState(); } public float playout(int player, GameState gs) throws Exception { nPlayouts++; GameState gs2 = gs; if (PLAYOUT_LOOKAHEAD>0 && playoutAI!=null) { AI ai1 = playoutAI.clone(); AI ai2 = playoutAI.clone(); gs2 = gs.clone(); ai1.reset(); ai2.reset(); int timeLimit = gs2.getTime() + PLAYOUT_LOOKAHEAD; boolean gameover = false; while(!gameover && gs2.getTime()<timeLimit) { if (gs2.isComplete()) { gameover = gs2.cycle(); } else { PlayerAction pa1 = ai1.getAction(player, gs2); PlayerAction pa2 = ai2.getAction(1-player, gs2); // System.out.println("time: " + gs2.getTime() + " resources: " + gs2.getPlayer(0).getResources() + "/" + gs2.getPlayer(1).getResources()); // System.out.println(" pa1: " + pa1); // System.out.println(" pa2: " + pa2); gs2.issue(pa1); gs2.issue(pa2); } } } float e = f.evaluate(player, 1-player, gs2); // if (DEBUG>=1) System.out.println(" done: " + e); return e; } }
34,319
52.541342
327
java
MicroRTS
MicroRTS-master/src/ai/ahtn/planner/AdversarialChoicePoint.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.planner; import ai.ahtn.domain.Binding; import ai.ahtn.domain.Clause; import ai.ahtn.domain.DomainDefinition; import ai.ahtn.domain.HTNMethod; import ai.ahtn.domain.MethodDecomposition; import java.util.HashMap; import java.util.ArrayList; import java.util.List; import rts.GameState; /** * * @author santi */ public class AdversarialChoicePoint { public static int DEBUG = 0; // these are the root nodes: public MethodDecomposition maxPlanRoot; public MethodDecomposition minPlanRoot; // these are the choicePoint nodes (should be descendants of the root nodes, or null): public MethodDecomposition choicePointPlayerMax; public MethodDecomposition choicePointPlayerMin; public GameState gs; int lastTimeOperatorsIssued = -1; int operatorDepth = 0; // this is to keep track of the depth of the search tree // keeps track of the number of instants when operators where // executed (if only one operator is executed at a time, this // is equivalent to the number of operators executed so far) // Method: variables to continue finding expansions after the first: List<HTNMethod> possibleMethods; // Condition: variables to continue finding expansions after the first: Clause updatedClause; boolean updatedClauseHadAnyMatches = false; List<Binding> lastBindings; // If the bindings found for a next match are the same as // the previous one, the new match is ignored (to reduce // useless branching) // Variables to restore the execution point of the plan after backtracking: HashMap<MethodDecomposition, MethodDecompositionState> executionState; // evaluation function: public int minimaxType = -1; // 0: max, 1: min, -1: not yet set. public float bestEvaluation = 0; public MethodDecomposition bestMaxPlan; public MethodDecomposition bestMinPlan; float alpha = 0; float beta = 0; private AdversarialChoicePoint() { executionState = new HashMap<>(); } public AdversarialChoicePoint(MethodDecomposition cpMax, MethodDecomposition cpMin, MethodDecomposition rootMax, MethodDecomposition rootMin, GameState a_gs, int nops, int ltoi) { maxPlanRoot = rootMax; minPlanRoot = rootMin; choicePointPlayerMax = cpMax; choicePointPlayerMin = cpMin; gs = a_gs; operatorDepth = nops; lastTimeOperatorsIssued = ltoi; executionState = new HashMap<>(); captureExecutionState(rootMax); captureExecutionState(rootMin); } public AdversarialChoicePoint(MethodDecomposition cpMax, MethodDecomposition cpMin, MethodDecomposition rootMax, MethodDecomposition rootMin, GameState a_gs, int nops, int ltoi, float a, float b, boolean saveExecutionState) { maxPlanRoot = rootMax; minPlanRoot = rootMin; choicePointPlayerMax = cpMax; choicePointPlayerMin = cpMin; gs = a_gs; operatorDepth = nops; lastTimeOperatorsIssued = ltoi; alpha = a; beta = b; // System.out.println("new: " + alpha + " , " + beta); executionState = new HashMap<>(); if (saveExecutionState) { captureExecutionState(rootMax); captureExecutionState(rootMin); } else { captureExecutionStateNonRecursive(rootMax); captureExecutionStateNonRecursive(rootMin); } } public AdversarialChoicePoint cloneForMCTS() { AdversarialChoicePoint acp = new AdversarialChoicePoint(); MethodDecomposition []in1 = {choicePointPlayerMax}; MethodDecomposition []out1 = {null}; acp.maxPlanRoot = maxPlanRoot.cloneTrackingDescendants(in1,out1); MethodDecomposition []in2 = {choicePointPlayerMin}; MethodDecomposition []out2 = {null}; acp.minPlanRoot = minPlanRoot.cloneTrackingDescendants(in2,out2); acp.choicePointPlayerMax = out1[0]; acp.choicePointPlayerMin = out2[0]; acp.gs = gs.clone(); acp.lastTimeOperatorsIssued = lastTimeOperatorsIssued; acp.operatorDepth = operatorDepth; /* // no need to clone these ones for the purposes of MCTS: List<HTNMethod> possibleMethods = null; Clause updatedClause = null; boolean updatedClauseHadAnyMatches = false; List<Binding> lastBindings = null; HashMap<MethodDecomposition, MethodDecompositionState> executionState = null; public int minimaxType = -1; public float bestEvaluation = 0; public MethodDecomposition bestMaxPlan = null; public MethodDecomposition bestMinPlan = null; float alpha = 0; float beta = 0; */ return acp; } public float getAlpha() { return alpha; } public float getBeta() { return beta; } public void setAlpha(float a) { alpha = a; } public void setBeta(float b) { beta = b; } public int getOperatorDepth() { return operatorDepth; } public int getLastTimeOperatorsIssued() { return lastTimeOperatorsIssued; } public void setLastTimeOperatorsIssued(int ltoi) { lastTimeOperatorsIssued = ltoi; } public float getBestEvaluation() { return bestEvaluation; } public void setBestEvaluation(float be) { bestEvaluation = be; } public int getMiniMaxType() { return minimaxType; } public GameState getGameState() { return gs; } public void captureExecutionState(MethodDecomposition md) { executionState.put(md, new MethodDecompositionState(md)); if (md.getSubparts()!=null) { for(int i = 0;i<md.getSubparts().length;i++) { captureExecutionState(md.getSubparts()[i]); } } if (md.getMethod()!=null) { captureExecutionState(md.getMethod().getDecomposition()); } } public void captureExecutionStateNonRecursive(MethodDecomposition md) { if (executionState.get(md)==null) executionState.put(md, new MethodDecompositionState(md)); } public void restoreExecutionState() { for(MethodDecomposition md:executionState.keySet()) { executionState.get(md).restoreState(md); } } public void restoreAfterPop() { if (choicePointPlayerMax!=null && choicePointPlayerMax.getType() == MethodDecomposition.METHOD_METHOD) { choicePointPlayerMax.setMethod(null); } if (choicePointPlayerMin!=null && choicePointPlayerMin.getType() == MethodDecomposition.METHOD_METHOD) { choicePointPlayerMin.setMethod(null); } } // "previous_cp" is usually == this, and it is the choice point where the state should be saved for restoring it later when backtracking public boolean nextExpansion(DomainDefinition dd, List<Binding> bindings, int renamingIndex, AdversarialChoicePoint previous_cp) throws Exception { if (choicePointPlayerMax!=null) { previous_cp.captureExecutionStateNonRecursive(choicePointPlayerMax); if (choicePointPlayerMax.getType() == MethodDecomposition.METHOD_METHOD) { return nextMethodExpansion(choicePointPlayerMax, gs, dd, bindings, renamingIndex); } else if (choicePointPlayerMax.getType() == MethodDecomposition.METHOD_CONDITION || choicePointPlayerMax.getType() == MethodDecomposition.METHOD_NON_BRANCHING_CONDITION) { return nextConditionExpansion(choicePointPlayerMax, bindings); } else { throw new Exception("Wrong MethodDecomposition in choicePoint!"); } } else { previous_cp.captureExecutionStateNonRecursive(choicePointPlayerMin); if (choicePointPlayerMin.getType() == MethodDecomposition.METHOD_METHOD) { return nextMethodExpansion(choicePointPlayerMin, gs, dd, bindings, renamingIndex); } else if (choicePointPlayerMin.getType() == MethodDecomposition.METHOD_CONDITION || choicePointPlayerMin.getType() == MethodDecomposition.METHOD_NON_BRANCHING_CONDITION) { return nextConditionExpansion(choicePointPlayerMin, bindings); } else { throw new Exception("Wrong MethodDecomposition in choicePoint!"); } } } private boolean nextConditionExpansion(MethodDecomposition choicePoint, List<Binding> bindings) throws Exception { if (DEBUG>=1) System.out.println("AdversarialChoicePoint.nextExpansionCondition: testing " + choicePoint.getClause()); if (updatedClause==null) { updatedClause = choicePoint.getClause().clone(); updatedClause.applyBindings(bindings); updatedClauseHadAnyMatches = false; lastBindings = null; } while(true) { // System.out.println(" Condition: " + updatedClause); // System.out.println(" " + bindings); List<Binding> l = updatedClause.nextMatch(gs); if (DEBUG>=1) System.out.println("AdversarialChoicePoint.nextConditionExpansion: bindings: " + l); if (l==null) { if (updatedClauseHadAnyMatches) { updatedClause = null; return false; } else { choicePoint.setExecutionState(2); updatedClauseHadAnyMatches = true; return true; } } else { if (lastBindings!=null && l.equals(lastBindings)) { // System.out.println(this.hashCode() + " - !!! " + updatedClause + "\n " + lastBindings + " ==\n " + l); continue; } else { // System.out.println(this.hashCode() + " - ok " + l); } lastBindings = new ArrayList<>(); lastBindings.addAll(l); updatedClauseHadAnyMatches = true; choicePoint.setExecutionState(1); for(Binding b:l) bindings.add(0,b); return true; } } } public boolean nextMethodExpansion(MethodDecomposition choicePoint, GameState gs, DomainDefinition dd, List<Binding> bindings, int renamingIndex) throws Exception { if (DEBUG>=1) System.out.println("AdversarialChoicePoint.nextMethodExpansion: testing " + choicePoint.getTerm()); if (possibleMethods==null) { // System.out.println("possibleMethods = null"); // System.out.println(" Method:" + choicePoint.getTerm()); // System.out.println(" " + bindings); List<HTNMethod> methods = dd.getMethodsForGoal(choicePoint.getTerm().getFunctor()); if (methods==null) throw new Exception("No methods for: " + choicePoint.getTerm().getFunctor()); possibleMethods = new ArrayList<>(); possibleMethods.addAll(methods); if (DEBUG>=1) System.out.println("AdversarialChoicePoint.nextMethodExpansion: Goal: " + choicePoint.getTerm()); if (DEBUG>=1) System.out.println("AdversarialChoicePoint.nextMethodExpansion: Methods found: " + methods.size()); } // if no more methods, reset, and return false: if (possibleMethods.isEmpty()) { possibleMethods = null; choicePoint.setMethod(null); return false; } // otherwise, nextExpansion: HTNMethod m = possibleMethods.remove(0); // clone the method (this clones the method, and applies any required variable substitution, setMethod(choicePoint, m, gs, bindings, renamingIndex); return true; } public void setMethod(MethodDecomposition choicePoint, HTNMethod original, GameState gs, List<Binding> bindings, int renamingIndex) throws Exception { // 1. Clone method: HTNMethod m = original.clone(); choicePoint.setMethod(m); // 2. Find variable bindings: List<Binding> bindings2 = m.getHead().simpleUnificationDestructiveNoSharedVariables(choicePoint.getTerm(), gs); if (DEBUG>=1) System.out.println("AdversarialChoicePoint.setMethod: bindings2 " + bindings2); // 3. Apply bindings to the rest of the method: m.applyBindings(bindings2); m.applyBindings(bindings); m.renameVariables(renamingIndex); } // returns "true" if the alpha-beta test determines it's time to prune the tree: public boolean processEvaluation(float f, MethodDecomposition maxPlan, MethodDecomposition minPlan, boolean clone) { switch(minimaxType) { case -1: if (choicePointPlayerMax!=null) { // in "max" choicepoints, we can only accept values that come when "max" can find a plan bestEvaluation = f; bestMaxPlan = (maxPlan==null ? null:(clone ? maxPlan.clone():maxPlan)); bestMinPlan = (minPlan==null ? null:(clone ? minPlan.clone():minPlan)); minimaxType = 0; } else { bestEvaluation = f; bestMaxPlan = (maxPlan==null ? null:(clone ? maxPlan.clone():maxPlan)); bestMinPlan = (minPlan==null ? null:(clone ? minPlan.clone():minPlan)); minimaxType = 1; } break; case 0: if ((bestMaxPlan==null && (maxPlan!=null || f>bestEvaluation)) || (bestMaxPlan!=null && minPlan!=null && f>bestEvaluation)) { bestEvaluation = f; bestMaxPlan = (maxPlan==null ? null:(clone ? maxPlan.clone():maxPlan)); bestMinPlan = (minPlan==null ? null:(clone ? minPlan.clone():minPlan)); } break; case 1: if ((bestMinPlan==null && (minPlan!=null || f<bestEvaluation)) || (bestMinPlan!=null && minPlan!=null && f<bestEvaluation)) { bestEvaluation = f; bestMaxPlan = (maxPlan==null ? null:(clone ? maxPlan.clone():maxPlan)); bestMinPlan = (minPlan==null ? null:(clone ? minPlan.clone():minPlan)); } break; } // alpha-beta pruning if (minimaxType==0) alpha = Math.max(alpha, f); else if (minimaxType==1) beta = Math.min(beta, f); return beta <= alpha; } public String toString() { String tmp = "( "; if (choicePointPlayerMax==null) { tmp += "null"; } else { if (choicePointPlayerMax.getType()==MethodDecomposition.METHOD_METHOD) { tmp+= "choicePointPlayerMax(" + choicePointPlayerMax.getTerm() + ")"; } else if (choicePointPlayerMax.getType()==MethodDecomposition.METHOD_CONDITION) { tmp+= "choicePointPlayerMax(" + choicePointPlayerMax.getClause() + ")"; } else { tmp+= "choicePointPlayerMax(???)"; } } tmp += " , "; if (choicePointPlayerMin==null) { tmp += "null"; } else { if (choicePointPlayerMin.getType()==MethodDecomposition.METHOD_METHOD) { tmp+= "choicePointPlayerMin(" + choicePointPlayerMin.getTerm() + ")"; } else if (choicePointPlayerMin.getType()==MethodDecomposition.METHOD_CONDITION) { tmp+= "choicePointPlayerMin(" + choicePointPlayerMin.getClause() + ")"; } else { tmp+= "choicePointPlayerMin(???)"; } } return tmp + ")"; } }
16,685
39.014388
168
java
MicroRTS
MicroRTS-master/src/ai/ahtn/planner/MethodDecompositionState.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.planner; import ai.ahtn.domain.MethodDecomposition; import java.util.ArrayList; import java.util.List; /** * * @author santi */ public class MethodDecompositionState { int executionState = 0; int operatorExecutingState = 0; List<MethodDecomposition> operatorsBeingExecuted; public MethodDecompositionState(MethodDecomposition md) { executionState = md.getExecutionState(); operatorExecutingState = md.getOperatorExecutingState(); if (md.getOperatorsBeingExecuted()!=null) { operatorsBeingExecuted = new ArrayList<>(); operatorsBeingExecuted.addAll(md.getOperatorsBeingExecuted()); } } public void restoreState(MethodDecomposition md) { md.setExecutionState(executionState); md.setOperatorExecutingState(operatorExecutingState); if (operatorsBeingExecuted==null) { md.setOperatorsBeingExecuted(null); } else { List<MethodDecomposition> l = md.getOperatorsBeingExecuted(); if (l==null) { l = new ArrayList<>(); md.setOperatorsBeingExecuted(l); } l.clear(); l.addAll(operatorsBeingExecuted); } } }
1,448
29.829787
79
java
MicroRTS
MicroRTS-master/src/ai/ahtn/visualization/HTNDomainVisualizer.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.visualization; import ai.ahtn.domain.DomainDefinition; import ai.ahtn.domain.HTNMethod; import ai.ahtn.domain.MethodDecomposition; import ai.ahtn.domain.Symbol; import ai.ahtn.domain.Term; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.imageio.ImageIO; /** * * @author santi */ public class HTNDomainVisualizer { public static int DEBUG = 0; public static void main(String args[]) throws Exception { // DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-lowest-level.lisp"); // DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-low-level.lisp"); DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-portfolio.lisp"); System.out.println(dd); HTNDomainVisualizer v = new HTNDomainVisualizer(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain.png")); } int hpadding = 8; int vpadding = 4; int hMethodPadding = 16; int vMethodPadding = 16; Font font; FontMetrics fm; public HTNDomainVisualizer() { font = new Font("Arial", Font.PLAIN, 10); Canvas c = new Canvas(); fm = c.getFontMetrics(font); } public BufferedImage visualizeHTNDomain(DomainDefinition d, Symbol root) throws Exception { List<Symbol> alreadyProcessed = new LinkedList<>(); return visualizeHTNTask(d,root,alreadyProcessed); } public BufferedImage visualizeHTNOperator(Symbol root) throws Exception { int textWidth = fm.stringWidth(root.get()); BufferedImage img = new BufferedImage(hpadding*2+textWidth, vpadding*2+fm.getHeight() , BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); g2d.setColor(new Color(0,127,0)); g2d.fillRect(0, 0,img.getWidth(), img.getHeight()); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), hpadding, vpadding+fm.getHeight()); return img; } public BufferedImage visualizeHTNOperator(Term t) throws Exception { String name = t.toString(); int textWidth = fm.stringWidth(name); BufferedImage img = new BufferedImage(hpadding*2+textWidth, vpadding*2+fm.getHeight() , BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); g2d.setColor(new Color(0,127,0)); g2d.fillRect(0, 0,img.getWidth(), img.getHeight()); g2d.setColor(Color.WHITE); g2d.drawString(name, hpadding, vpadding+fm.getHeight()); return img; } public BufferedImage visualizeHTNTask(DomainDefinition d, Symbol root, List<Symbol> alreadyProcessed) throws Exception { if (alreadyProcessed.contains(root)) { if (DEBUG>=1) System.out.println("visualizeHTNTask (already processed): " + root); int textWidth = fm.stringWidth(root.get()); BufferedImage img = new BufferedImage(hpadding*2+textWidth, vpadding*2+fm.getHeight() , BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); g2d.setColor(Color.RED); g2d.fillRect(0, 0,img.getWidth(), img.getHeight()); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), hpadding, vpadding+fm.getHeight()); return img; } else { if (DEBUG>=1) System.out.println("visualizeHTNTask: " + root); alreadyProcessed.add(root); List<HTNMethod> methods = d.getMethodsForGoal(new Symbol(root)); int textWidth = fm.stringWidth(root.get()); int methodWidth = 0; int methodHeight = 0; List<BufferedImage> images = new LinkedList<>(); for(HTNMethod m:methods) { BufferedImage img2 = visualizeHTNMethod(d, m, alreadyProcessed); images.add(img2); methodWidth+=img2.getWidth(); methodHeight = Math.max(methodHeight, img2.getHeight()); } methodWidth += (methods.size())*hMethodPadding; int width = Math.max(textWidth+2*hpadding, methodWidth); BufferedImage img = new BufferedImage(width, fm.getHeight()+2*vpadding + vMethodPadding+methodHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); if (DEBUG>=1) System.out.println(" visualizeHTNTask img: " + img.getWidth() + " x " + img.getHeight() + " (methodHeight: " + methodHeight + ")"); int x = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(width/2, fm.getHeight() + vpadding*2, x+img2.getWidth()/2, fm.getHeight() + vpadding*2 + vMethodPadding); g2d.drawImage(img2,x,fm.getHeight() + vpadding*2 + vMethodPadding, null); x+=img2.getWidth()+hMethodPadding; } g2d.setColor(Color.BLACK); g2d.fillRect(width/2 - (textWidth+2*hpadding)/2, 0, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), width/2 - (textWidth+2*hpadding)/2 + hpadding, vpadding+fm.getHeight()); return img; } } public BufferedImage visualizeHTNMethod(DomainDefinition d, HTNMethod m, List<Symbol> alreadyProcessed) throws Exception { List<Symbol> children = new LinkedList<>(); List<BufferedImage> images = new LinkedList<>(); if (DEBUG>=1) System.out.println("visualizeHTNMethod: " + m.getName()); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); stack.add(m.getDecomposition()); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: children.add(md.getTerm().getFunctor()); break; case MethodDecomposition.METHOD_METHOD: children.add(md.getTerm().getFunctor()); break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } int textWidth = fm.stringWidth(m.getName()); int childrenWidth = 0; int childrenHeight = 0; for(Symbol c:children) { if (c.get().startsWith("!")) { // operator: BufferedImage img = visualizeHTNOperator(c); images.add(img); childrenWidth+=img.getWidth(); childrenHeight = Math.max(childrenHeight, img.getHeight()); } else { // task: BufferedImage img = visualizeHTNTask(d, c, alreadyProcessed); images.add(img); childrenWidth+=img.getWidth(); childrenHeight = Math.max(childrenHeight, img.getHeight()); } } childrenWidth += (children.size())*hMethodPadding; int width = Math.max(textWidth+2*hpadding, childrenWidth); BufferedImage img = new BufferedImage(width, fm.getHeight() + vpadding*2 + vMethodPadding+childrenHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); if (DEBUG>=1) System.out.println(" visualizeHTNMethod img: " + img.getWidth() + " x " + img.getHeight()); int x = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(width/2, fm.getHeight() + vpadding*2, x+img2.getWidth()/2, fm.getHeight() + vpadding*2 + vMethodPadding); g2d.drawImage(img2,x,fm.getHeight() + vpadding*2 + vMethodPadding, null); x+=img2.getWidth()+hMethodPadding; } g2d.setColor(Color.GRAY); g2d.fillRect(width/2 - (textWidth+2*hpadding)/2, 0, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m.getName(), width/2 - (textWidth+2*hpadding)/2 + hpadding, vpadding+fm.getHeight()); return img; } /* The difference between this and the previous methods is that this one visualizes an instantiated plan, whereas the previous one is designed to visualize the domain definition of a given method. */ public BufferedImage visualizeHTNPlan(HTNMethod m) throws Exception { List<BufferedImage> images = new LinkedList<>(); String m_head_name = m.getHead().toString(); String m_name = m.getName(); int textWidth = Math.max(fm.stringWidth(m_name),fm.stringWidth(m_head_name)); int childrenWidth = 0; int childrenHeight = 0; if (DEBUG>=1) System.out.println("visualizeHTNPlan: " + m_name); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); if (m.getDecomposition()!=null) stack.add(m.getDecomposition()); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: { BufferedImage img2 = visualizeHTNOperator(md.getTerm()); images.add(img2); childrenWidth+=img2.getWidth(); childrenHeight = Math.max(childrenHeight, img2.getHeight()); } break; case MethodDecomposition.METHOD_METHOD: { BufferedImage img2 = visualizeHTNPlan(md); images.add(img2); childrenWidth+=img2.getWidth(); childrenHeight = Math.max(childrenHeight, img2.getHeight()); } break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } childrenWidth += (images.size())*hMethodPadding; int width = Math.max(textWidth+2*hpadding, childrenWidth); BufferedImage img = new BufferedImage(width, (fm.getHeight() + vpadding*2)*2 + vMethodPadding+childrenHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); if (DEBUG>=1) System.out.println(" visualizeHTNMethod img: " + img.getWidth() + " x " + img.getHeight()); int x = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(width/2, (fm.getHeight() + vpadding*2)*2, x+img2.getWidth()/2, (fm.getHeight() + vpadding*2)*2 + vMethodPadding); g2d.drawImage(img2,x, (fm.getHeight() + vpadding*2)*2 + vMethodPadding, null); x+=img2.getWidth()+hMethodPadding; } g2d.setColor(Color.GRAY); g2d.fillRect(width/2 - (textWidth+2*hpadding)/2, 0, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m_head_name, width/2 - (textWidth+2*hpadding)/2 + hpadding, vpadding+fm.getHeight()); g2d.setColor(Color.BLACK); g2d.fillRect(width/2 - (textWidth+2*hpadding)/2, fm.getHeight() + vpadding*2, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.WHITE); g2d.drawString(m_name, width/2 - (textWidth+2*hpadding)/2 + hpadding, fm.getHeight() + vpadding*2 + vpadding+fm.getHeight()); return img; } public BufferedImage visualizeHTNPlan(MethodDecomposition m) throws Exception { if (m.getType() == MethodDecomposition.METHOD_METHOD && m.getMethod()!=null) return visualizeHTNPlan(m.getMethod()); List<BufferedImage> images = new LinkedList<>(); String m_name = "-"; if (m.getTerm()!=null) m_name = m.getTerm().toString(); int textWidth = fm.stringWidth(m_name); int childrenWidth = 0; int childrenHeight = 0; if (DEBUG>=1) System.out.println("visualizeHTNPlan: " + m_name); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); stack.add(m); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: { BufferedImage img2 = visualizeHTNOperator(md.getTerm()); images.add(img2); childrenWidth+=img2.getWidth(); childrenHeight = Math.max(childrenHeight, img2.getHeight()); } break; case MethodDecomposition.METHOD_METHOD: { if (md.getMethod()!=null) { BufferedImage img2 = visualizeHTNPlan(md.getMethod()); images.add(img2); childrenWidth+=img2.getWidth(); childrenHeight = Math.max(childrenHeight, img2.getHeight()); } else { if (md!=m) { BufferedImage img2 = visualizeHTNPlan(md); images.add(img2); childrenWidth+=img2.getWidth(); childrenHeight = Math.max(childrenHeight, img2.getHeight()); } } } break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } childrenWidth += (images.size())*hMethodPadding; int width = Math.max(textWidth+2*hpadding, childrenWidth); BufferedImage img = new BufferedImage(width, fm.getHeight() + vpadding*2 + vMethodPadding+childrenHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); if (DEBUG>=1) System.out.println(" visualizeHTNMethod img: " + img.getWidth() + " x " + img.getHeight()); int x = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(width/2, fm.getHeight() + vpadding*2, x+img2.getWidth()/2, fm.getHeight() + vpadding*2 + vMethodPadding); g2d.drawImage(img2,x,fm.getHeight() + vpadding*2 + vMethodPadding, null); x+=img2.getWidth()+hMethodPadding; } g2d.setColor(Color.GRAY); g2d.fillRect(width/2 - (textWidth+2*hpadding)/2, 0, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m_name, width/2 - (textWidth+2*hpadding)/2 + hpadding, vpadding+fm.getHeight()); return img; } }
16,806
42.768229
160
java
MicroRTS
MicroRTS-master/src/ai/ahtn/visualization/HTNDomainVisualizerVertical.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.ahtn.visualization; import ai.ahtn.domain.DomainDefinition; import ai.ahtn.domain.HTNMethod; import ai.ahtn.domain.MethodDecomposition; import ai.ahtn.domain.Symbol; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.imageio.ImageIO; /** * * @author santi */ public class HTNDomainVisualizerVertical { public static void main(String args[]) throws Exception { { DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-lowest-level.lisp"); HTNDomainVisualizerVertical v = new HTNDomainVisualizerVertical(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain-lowest-level.png")); } { DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-low-level.lisp"); HTNDomainVisualizerVertical v = new HTNDomainVisualizerVertical(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain-low-level.png")); } { DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-portfolio.lisp"); HTNDomainVisualizerVertical v = new HTNDomainVisualizerVertical(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain-portfolio.png")); } { DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-flexible-portfolio.lisp"); HTNDomainVisualizerVertical v = new HTNDomainVisualizerVertical(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain-flexible-portfolio.png")); } { DomainDefinition dd = DomainDefinition.fromLispFile("ahtn/microrts-ahtn-definition-flexible-single-target-portfolio.lisp"); HTNDomainVisualizerVertical v = new HTNDomainVisualizerVertical(); BufferedImage img = v.visualizeHTNDomain(dd, new Symbol("destroy-player")); ImageIO.write(img, "png", new File("HTN-domain-flexible-single-target-portfolio.png")); } } int hpadding = 8; int vpadding = 4; int hMethodPadding = 32; int vMethodPadding = 8; Font font; FontMetrics fm; public HTNDomainVisualizerVertical() { font = new Font("Arial", Font.PLAIN, 16); Canvas c = new Canvas(); fm = c.getFontMetrics(font); } public BufferedImage visualizeHTNDomain(DomainDefinition d, Symbol root) throws Exception { List<Symbol> alreadyProcessed = new LinkedList<>(); return visualizeHTNTask(d,root,alreadyProcessed); } public BufferedImage visualizeHTNOperator(Symbol root) throws Exception { int textWidth = fm.stringWidth(root.get()); BufferedImage img = new BufferedImage(hpadding*2+textWidth, vpadding*2+fm.getHeight() , BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); g2d.setColor(new Color(0,127,0)); g2d.fillRect(0, 0,img.getWidth(), img.getHeight()); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), hpadding, vpadding+fm.getHeight() - 2); return img; } public BufferedImage visualizeHTNTask(DomainDefinition d, Symbol root, List<Symbol> alreadyProcessed) throws Exception { if (alreadyProcessed.contains(root)) { System.out.println("visualizeHTNTask (already processed): " + root); int textWidth = fm.stringWidth(root.get()); BufferedImage img = new BufferedImage(hpadding*2+textWidth, vpadding*2+fm.getHeight() , BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); g2d.setColor(Color.RED); g2d.fillRect(0, 0,img.getWidth(), img.getHeight()); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), hpadding, vpadding+fm.getHeight() - 2); return img; } else { System.out.println("visualizeHTNTask: " + root); alreadyProcessed.add(root); List<HTNMethod> methods = d.getMethodsForGoal(new Symbol(root)); int textWidth = fm.stringWidth(root.get()); int methodWidth = 0; int methodHeight = 0; List<BufferedImage> images = new LinkedList<>(); for(HTNMethod m:methods) { BufferedImage img2 = visualizeHTNMethod(d, m, alreadyProcessed); images.add(img2); methodWidth = Math.max(methodWidth, img2.getWidth()); methodHeight += img2.getHeight(); } methodHeight += (methods.size()-1)*vMethodPadding; int width = textWidth+2*hpadding + hMethodPadding + methodWidth; int height = Math.max(fm.getHeight()+2*vpadding,methodHeight); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); System.out.println(" visualizeHTNTask img: " + img.getWidth() + " x " + img.getHeight() + " (methodHeight: " + methodHeight + ")"); int y = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(textWidth+2*hpadding, height/2, textWidth+2*hpadding + hMethodPadding, y+img2.getHeight()/2); System.out.println(" drawing image at: " + (textWidth+2*hpadding + hMethodPadding) + ", " + y); g2d.drawImage(img2,textWidth+2*hpadding + hMethodPadding,y, null); y+=img2.getHeight()+vMethodPadding; } g2d.setColor(Color.BLACK); g2d.fillRect(0,height/2 - (fm.getHeight()+2*vpadding)/2, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.WHITE); g2d.drawString(root.get(), hpadding, height/2 - (fm.getHeight()+2*vpadding)/2 + fm.getHeight() + vpadding - 2); return img; } } public BufferedImage visualizeHTNMethod(DomainDefinition d, HTNMethod m, List<Symbol> alreadyProcessed) throws Exception { List<Symbol> children = new LinkedList<>(); List<BufferedImage> images = new LinkedList<>(); System.out.println("visualizeHTNMethod: " + m.getName()); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); stack.add(m.getDecomposition()); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: children.add(md.getTerm().getFunctor()); break; case MethodDecomposition.METHOD_METHOD: children.add(md.getTerm().getFunctor()); break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } int textWidth = fm.stringWidth(m.getName()); int childrenWidth = 0; int childrenHeight = 0; for(Symbol c:children) { if (c.get().startsWith("!")) { // operator: BufferedImage img2 = visualizeHTNOperator(c); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } else { // task: BufferedImage img2 = visualizeHTNTask(d, c, alreadyProcessed); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } } childrenHeight += (children.size()-1)*vMethodPadding; int width = textWidth+2*hpadding + hMethodPadding + childrenWidth; int height = Math.max(fm.getHeight()+2*vpadding,childrenHeight); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); System.out.println(" visualizeHTNMethod img: " + img.getWidth() + " x " + img.getHeight()); int y = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(textWidth+2*hpadding, height/2, textWidth+2*hpadding + hMethodPadding, y+img2.getHeight()/2); g2d.drawImage(img2,textWidth+2*hpadding + hMethodPadding,y, null); y+=img2.getHeight()+vMethodPadding; } g2d.setColor(Color.LIGHT_GRAY); g2d.fillRect(0,height/2 - (fm.getHeight()+2*vpadding)/2, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m.getName(), hpadding, height/2 - (fm.getHeight()+2*vpadding)/2 + fm.getHeight() + vpadding - 2); return img; } /* The difference between this and the previous methods is that this one visualizes an instantiated plan, whereas the previous one is designed to visualize the domain definition of a given method. */ public BufferedImage visualizeHTNPlan(HTNMethod m) throws Exception { List<BufferedImage> images = new LinkedList<>(); String m_name = m.getName(); int textWidth = fm.stringWidth(m_name); int childrenWidth = 0; int childrenHeight = 0; System.out.println("visualizeHTNPlan: " + m_name); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); stack.add(m.getDecomposition()); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: { BufferedImage img2 = visualizeHTNOperator(md.getTerm().getFunctor()); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } break; case MethodDecomposition.METHOD_METHOD: { if (md.getMethod()!=null) { BufferedImage img2 = visualizeHTNPlan(md.getMethod()); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } } break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } childrenHeight += (images.size()-1)*vMethodPadding; int width = textWidth+2*hpadding + hMethodPadding + childrenWidth; int height = Math.max(fm.getHeight()+2*vpadding,childrenHeight); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); System.out.println(" visualizeHTNPlan img: " + img.getWidth() + " x " + img.getHeight()); int y = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(textWidth+2*hpadding, height/2, textWidth+2*hpadding + hMethodPadding, y+img2.getHeight()/2); g2d.drawImage(img2,textWidth+2*hpadding + hMethodPadding,y, null); y+=img2.getHeight()+vMethodPadding; } g2d.setColor(Color.LIGHT_GRAY); g2d.fillRect(0,height/2 - (fm.getHeight()+2*vpadding)/2, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m_name, hpadding, height/2 - (fm.getHeight()+2*vpadding)/2 + fm.getHeight() + vpadding - 2); return img; } public BufferedImage visualizeHTNPlan(MethodDecomposition m) throws Exception { List<BufferedImage> images = new LinkedList<>(); String m_name = "-"; if (m.getTerm()!=null) m_name = m.getTerm().toString(); int textWidth = fm.stringWidth(m_name); int childrenWidth = 0; int childrenHeight = 0; System.out.println("visualizeHTNPlan: " + m_name); // generate the children: List<MethodDecomposition> stack = new LinkedList<>(); stack.add(m); while(!stack.isEmpty()) { MethodDecomposition md = stack.remove(0); switch(md.getType()) { case MethodDecomposition.METHOD_OPERATOR: { BufferedImage img2 = visualizeHTNOperator(md.getTerm().getFunctor()); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } break; case MethodDecomposition.METHOD_METHOD: { if (md.getMethod()!=null) { BufferedImage img2 = visualizeHTNPlan(md.getMethod()); images.add(img2); childrenWidth = Math.max(childrenWidth, img2.getWidth()); childrenHeight += img2.getHeight(); } } break; case MethodDecomposition.METHOD_SEQUENCE: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_PARALLEL: stack.addAll(Arrays.asList(md.getSubparts())); break; case MethodDecomposition.METHOD_CONDITION: break; } } childrenHeight += (images.size()-1)*vMethodPadding; int width = textWidth+2*hpadding + hMethodPadding + childrenWidth; int height = Math.max(fm.getHeight()+2*vpadding,childrenHeight); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(font); System.out.println(" visualizeHTNPlan img: " + img.getWidth() + " x " + img.getHeight()); int y = 0; for(BufferedImage img2:images) { g2d.setColor(Color.BLACK); g2d.drawLine(textWidth+2*hpadding, height/2, textWidth+2*hpadding + hMethodPadding, y+img2.getHeight()/2); g2d.drawImage(img2,textWidth+2*hpadding + hMethodPadding,y, null); y+=img2.getHeight()+vMethodPadding; } g2d.setColor(Color.LIGHT_GRAY); g2d.fillRect(0,height/2 - (fm.getHeight()+2*vpadding)/2, textWidth+2*hpadding, fm.getHeight() + vpadding*2); g2d.setColor(Color.BLACK); g2d.drawString(m_name, hpadding, height/2 - (fm.getHeight()+2*vpadding)/2 + fm.getHeight() + vpadding - 2); return img; } }
16,765
43.472149
146
java
MicroRTS
MicroRTS-master/src/ai/core/AI.java
package ai.core; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * Basic AI class for any microRTS controller. * In other words, any microRTS controller is a subclass of this class, * either directly or indirectly via other basic AI classes. * * @author santi */ public abstract class AI { public abstract void reset(); /* * Indicates to the AI that the new game will * be played with a new {@link UnitTypeTable} * (in case the AI needs to do anything with it) */ public void reset(UnitTypeTable utt) { reset(); } /** * Main "thinking" method of a microRTS controller. * Receives the current {@link GameState} and the player index to return * the calculated {@link PlayerAction}. * @param player ID of the player to move. Use it to check whether units are yours or enemy's * @param gs the game state where the action should be performed * @return the PlayerAction stores a collection of {@link UnitAction} per {@link Unit}. * Each of these pairs indicate an assignment of an action to a unit * @throws Exception */ public abstract PlayerAction getAction(int player, GameState gs) throws Exception; @Override /** * This function is not supposed to do an exact clone with all the internal state, etc. * just a copy of the AI with the same configuration. */ public abstract AI clone(); /** * Returns a list of {@link ParameterSpecification} with this controller's parameters * @return */ public abstract List<ParameterSpecification> getParameters(); /** * This method can be used to report any meaningful statistics once the game is over * (for example, average nodes explored per move, etc.) * @return */ public String statisticsString() { return null; } /** * Just prints the String returned by {@link #statisticsString()} to the standard * output */ public void printStats() { String stats = statisticsString(); if (stats!=null) System.out.println(stats); } @Override public String toString() { return this.getClass().getSimpleName(); } /** * In this function you can implement some pre-game reasoning, as the function receives * the initial game state and a time limit to execute. * * Whether or not this function is called depends on the tournament configuration. * * @param gs the initial state of the game about to be played. Even if the game is * partially observable, the game state received by this * function might be fully observable * @param milliseconds time limit to perform the analysis. If zero, you can take as * long as you need * @throws Exception */ public void preGameAnalysis(GameState gs, long milliseconds) throws Exception { } /** * This function is also for implementing pre-game reasoning with the possibility of * reading from and writing to disc, in the specified directory. * * @param gs the initial state of the game about to be played. Even if the game is * partially observable, the game state received by this * function might be fully observable * @param milliseconds milliseconds time limit to perform the analysis. If zero, you can take as * long as you need * @param readWriteFolder path to the directory where you can read/write stuff * @throws Exception */ public void preGameAnalysis(GameState gs, long milliseconds, String readWriteFolder) throws Exception { preGameAnalysis(gs, milliseconds); } /** * Notifies the AI that the game is over, and reports who was the winner * @param winner * @throws Exception */ public void gameOver(int winner) throws Exception { } }
4,014
31.12
105
java
MicroRTS
MicroRTS-master/src/ai/core/AIWithComputationBudget.java
package ai.core; /** * An "AIWithComputationBudget" is one that is given a limit in the * amount of CPU it can use per game frame. This limit is specified in either: * - TIME_BUDGET: number of milliseconds that the call to "getAction" can take, or * - ITERATIONS_BUDGET: number of internal iterations the AI can use * (e.g., in a Monte Carlo AI, this is the number of playouts, or in a minimax AI, * this is the number of leaves it can explore). * * If either of these values is -1, it means that that particular bound can be ignored. * @author santi * */ public abstract class AIWithComputationBudget extends AI { /** * Number of milisseconds the function {@link #getAction(int, rts.GameState)} * is allowed to use. If set to -1, time is not limited. */ protected int TIME_BUDGET = 100; /** * Number of internal iterations for this controller * (e.g. playouts for Monte Carlo Tree Search). * If set to -1, the number of iterations is not limited */ protected int ITERATIONS_BUDGET = 100; /** * Constructs the controller with the specified time and iterations budget * @param timeBudget time in milisseconds * @param iterationsBudget number of allowed iterations */ public AIWithComputationBudget(int timeBudget, int iterationsBudget) { TIME_BUDGET = timeBudget; ITERATIONS_BUDGET = iterationsBudget; } /** * Returns the time budget of this controller * @return time in milliseconds (-1 means no time limit) */ public int getTimeBudget() { return TIME_BUDGET; } /** * Sets the time budget (milliseconds) for this controller * @param milisseconds */ public void setTimeBudget(int milisseconds) { TIME_BUDGET = milisseconds; } /** * Returns the number of internal iterations this AI is allowed * (-1 means no limit of iterations) * @return */ public int getIterationsBudget() { return ITERATIONS_BUDGET; } /** * Sets the number of allowed internal iterations * @param iterations */ public void setIterationsBudget(int iterations) { ITERATIONS_BUDGET = iterations; } }
2,250
29.013333
87
java
MicroRTS
MicroRTS-master/src/ai/core/ContinuingAI.java
package ai.core; import java.util.List; import rts.GameState; import rts.PlayerAction; /** * * @author santi */ public class ContinuingAI extends AI { /** * Becomes verbose if >0 for debugging purposes */ public static int DEBUG = 0; /** * An {@link AI} instance that implements {@link InterruptibleAI}. * ContinuingAI uses this AI to effectively calculate the action to return */ protected AI m_AI; /** * Indicates whether this AI is currently computing an action */ protected boolean m_isThereAComputationGoingOn = false; /** * The game state for which the action is being computed */ protected GameState m_gameStateUsedForComputation; /** * Instantiates the ContinuingAI with an AI that implements {@link InterruptibleAI}. * Throws an exception if the received AI does not implement {@link InterruptibleAI}. * @param ai * @throws Exception */ public ContinuingAI(AI ai) throws Exception { if (!(ai instanceof InterruptibleAI)) throw new Exception("ContinuingAI: ai does not implement InterruptibleAI!"); m_AI = ai; } public PlayerAction getAction(int player, GameState gs) throws Exception { if (gs.canExecuteAnyAction(player)) { // check to make sure game is deterministic: if (m_gameStateUsedForComputation != null && !m_gameStateUsedForComputation.equals(gs)) { if (DEBUG >= 1) { System.out.println( "The game state is different from the predicted one (this can happen in non-deterministic games), restarting search." ); } m_isThereAComputationGoingOn = false; m_gameStateUsedForComputation = null; } if (DEBUG >= 1) System.out.println("ContinuingAI: this cycle we need an action"); // prepares a new computation if there isn't any going on if (!m_isThereAComputationGoingOn) ((InterruptibleAI)m_AI).startNewComputation(player, gs.clone()); // improves the current solution ((InterruptibleAI)m_AI).computeDuringOneGameFrame(); // re-sets the variables for a next call m_isThereAComputationGoingOn = false; m_gameStateUsedForComputation = null; // returns the best action found so far return ((InterruptibleAI)m_AI).getBestActionSoFar(); } else { // player cannot act in this cycle if (!m_isThereAComputationGoingOn) { GameState newGameState = gs.clone(); // fast-forwards the world until a player can act or the game is over while (newGameState.winner() == -1 && !newGameState.gameover() && !newGameState.canExecuteAnyAction(0) && !newGameState.canExecuteAnyAction(1)) { newGameState.cycle(); } // if the reached state is not a game over and this player can act, // starts a new computation if ((newGameState.winner() == -1 && !newGameState.gameover()) && newGameState.canExecuteAnyAction(player)) { if (DEBUG>=1) { System.out.println("ContinuingAI: this cycle we do not need an action, but we will be next to move"); } m_isThereAComputationGoingOn = true; m_gameStateUsedForComputation = newGameState; ((InterruptibleAI)m_AI).startNewComputation(player, m_gameStateUsedForComputation); ((InterruptibleAI)m_AI).computeDuringOneGameFrame(); } else { // game is over or this player cannot move if (DEBUG>=1) System.out.println("ContinuingAI: this cycle we do not need an action, but we will not be next to move, so we can do nothing"); } } else { // computation was already started, resume to improve solution if (DEBUG>=1) System.out.println("ContinuingAI: continuing a computation from a previous frame"); ((InterruptibleAI)m_AI).computeDuringOneGameFrame(); } // returns a default action return new PlayerAction(); } } public void reset() { m_isThereAComputationGoingOn = false; m_gameStateUsedForComputation = null; m_AI.reset(); } public AI clone() { try { return new ContinuingAI(m_AI.clone()); } catch(Exception e) { // given the check in the constructor, this will never happen return null; } } @Override public String toString() { return getClass().getSimpleName() + "(" + m_AI + ")"; } @Override public String statisticsString() { return m_AI.statisticsString(); } /** * Returns the parameters of the internal AI */ public List<ParameterSpecification> getParameters() { return m_AI.getParameters(); } /** * Requests the internal AI to perform the pre-game analysis */ public void preGameAnalysis(GameState gs, long milliseconds) throws Exception { m_AI.preGameAnalysis(gs, milliseconds); } }
5,371
33.658065
161
java
MicroRTS
MicroRTS-master/src/ai/core/InterruptibleAI.java
package ai.core; import rts.GameState; import rts.PlayerAction; /** * A "InterruptibleAI" can divide the computation across multiple game frames. * * The idea is that of an "anytime" algorithm: compute until requested to return the best * solution so far. Computation is prepared by {@link #startNewComputation}, performed * with {@link #computeDuringOneGameFrame} (which can be called several times to improve the * current solution) and the best solution found is returned with {@link #getBestActionSoFar()}. * * Usually, this interface is used in combination with the {@link ContinuingAI} class. * * @author santi * */ public interface InterruptibleAI { /** * Starts the calculation of an action to return, receiving the player to act * and the game state. * @param player the index of the player have its action calculated * @param gs the game state where the action will be taken * @throws Exception */ void startNewComputation(int player, GameState gs) throws Exception; /** * Resumes the computation of the best action calculated so far. * Every time this function is called is an opportunity to improve the action * to be taken in the {@link GameState} received in {@link #startNewComputation} * @throws Exception */ void computeDuringOneGameFrame() throws Exception; /** * Returns the best action calculated so far * @return * @throws Exception */ PlayerAction getBestActionSoFar() throws Exception; } /* public abstract class InterruptibleAI extends AIWithComputationBudget { public InterruptibleAI(int mt, int mi) { super(mt,mi); } public final PlayerAction getAction(int player, GameState gs) throws Exception { if (gs.canExecuteAnyAction(player)) { startNewComputation(player,gs.clone()); computeDuringOneGameFrame(); return getBestActionSoFar(); } else { return new PlayerAction(); } } public abstract void startNewComputation(int player, GameState gs) throws Exception; public abstract void computeDuringOneGameFrame() throws Exception; public abstract PlayerAction getBestActionSoFar() throws Exception; } */
2,275
32.470588
97
java
MicroRTS
MicroRTS-master/src/ai/core/ParameterSpecification.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.core; import java.util.ArrayList; import java.util.List; /** * * @author santi */ public class ParameterSpecification { public String name; public Class type; public Object defaultValue; public List<Object> possibleValues; // used only if not-null public Double minValue, maxValue; // for parameters with a range public ParameterSpecification(String n, Class t, Object dv) { name = n; type = t; defaultValue = dv; } public void addPossibleValue(Object v) { if (possibleValues==null) possibleValues = new ArrayList<>(); possibleValues.add(v); } public void setRange(Double min, Double max) { minValue = min; maxValue = max; } }
962
22.487805
79
java
MicroRTS
MicroRTS-master/src/ai/core/PseudoContinuingAI.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.core; import java.util.List; import rts.GameState; import rts.PlayerAction; /** * * @author santi * * - This class is just a wrapper around some other AI class, that "fakes" the AI to be a "Continuing" one by doing this: * - The AI keeps track of each game cycle in which the AI had nothing to do (none of its units were ready to execute an action) * - Then, when it comes time to execute an action, it uses additional time based on how many of those game cycles the AI was idle. * - So, basically, instead of splitting computation across frames, this AI, just does all the computation in the last game cycle * - This AI will violate the timing checks of the tournament setting of the game, but it is useful for experimentation purposes. * */ public class PseudoContinuingAI extends AI { public static int DEBUG = 0; protected AIWithComputationBudget m_AI; protected int n_cycles_to_think = 1; protected GameState m_farecastedGameState; public PseudoContinuingAI(AIWithComputationBudget ai) { m_AI = ai; } public PlayerAction getAction(int player, GameState gs) throws Exception { if (gs.canExecuteAnyAction(player)) { // check to make sure game is deterministic: if (m_farecastedGameState!=null && !m_farecastedGameState.equals(gs)) { if (DEBUG>=1) System.out.println("The game state is different from the predicted one (this can happen in non-deterministic games), restarring search."); n_cycles_to_think = 1; m_farecastedGameState = null; } if (DEBUG>=1) System.out.println("PseudoContinuingAI: n_cycles_to_think = " + n_cycles_to_think); int MT = m_AI.TIME_BUDGET; int MI = m_AI.ITERATIONS_BUDGET; if (MT>0) m_AI.TIME_BUDGET = MT * n_cycles_to_think; if (MI>0) m_AI.ITERATIONS_BUDGET = MI * n_cycles_to_think; PlayerAction action = m_AI.getAction(player,gs); m_AI.TIME_BUDGET = MT; m_AI.ITERATIONS_BUDGET = MI; n_cycles_to_think = 1; m_farecastedGameState = null; return action; } else { if (n_cycles_to_think==1) { GameState gs2 = gs.clone(); while(gs2.winner()==-1 && !gs2.gameover() && !gs2.canExecuteAnyAction(0) && !gs2.canExecuteAnyAction(1)) gs2.cycle(); if ((gs2.winner() == -1 && !gs2.gameover()) && gs2.canExecuteAnyAction(player)) { n_cycles_to_think++; m_farecastedGameState = gs2; } } else { n_cycles_to_think++; } return new PlayerAction(); } } public void reset() { n_cycles_to_think = 1; m_AI.reset(); } public AI clone() { return new PseudoContinuingAI((AIWithComputationBudget) m_AI.clone()); } @Override public String toString() { return getClass().getSimpleName() + "(" + m_AI + ")"; } @Override public String statisticsString() { return m_AI.statisticsString(); } public List<ParameterSpecification> getParameters() { return m_AI.getParameters(); } public AIWithComputationBudget getbaseAI() { return m_AI; } }
3,772
32.990991
168
java
MicroRTS
MicroRTS-master/src/ai/evaluation/EvaluationFunction.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.evaluation; import rts.GameState; /** * * @author santi */ public abstract class EvaluationFunction { public static float VICTORY = 10000; public abstract float evaluate(int maxplayer, int minplayer, GameState gs); public abstract float upperBound(GameState gs); public String toString() { return getClass().getSimpleName(); } }
487
20.217391
79
java
MicroRTS
MicroRTS-master/src/ai/evaluation/EvaluationFunctionForwarding.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.evaluation; import rts.GameState; /** * * @author santi */ public class EvaluationFunctionForwarding extends EvaluationFunction { EvaluationFunction baseFunction; public EvaluationFunctionForwarding(EvaluationFunction base) { baseFunction = base; } public float evaluate(int maxplayer, int minplayer, GameState gs) { GameState gs2 = gs.clone(); gs2.forceExecuteAllActions(); return baseFunction.evaluate(maxplayer,minplayer,gs) + baseFunction.evaluate(maxplayer,minplayer,gs2) * 0.5f; } public float upperBound(GameState gs) { return baseFunction.upperBound(gs)*1.5f; } }
802
22.617647
71
java
MicroRTS
MicroRTS-master/src/ai/evaluation/LanchesterEvaluationFunction.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.evaluation; import rts.GameState; import rts.PhysicalGameState; import rts.units.*; /** * * @author santi */ public class LanchesterEvaluationFunction extends EvaluationFunction { public static float[] W_BASE = {0.12900641042498262f, 0.48944975377829392f}; public static float[] W_RAX = {0.23108197488337265f, 0.55022866772062451f}; public static float[] W_WORKER = {0.18122298329807154f, -0.0078514695699861588f}; public static float[] W_LIGHT = {1.7496678034331925f, 0.12587241165484406f}; public static float[] W_RANGE = {1.6793840344563218f, 0.029918374064639004f}; public static float[] W_HEAVY = {3.9012441116439427f, 0.16414240458460899f}; public static float[] W_MINERALS_CARRIED = {0.3566229669443759f, 0.01061490087512941f}; public static float[] W_MINERALS_MINED = {0.30141654836442761f, 0.38643842595899713f}; public static float order = 1.7f; public static float sigmoid(float x) { return (float) (1.0f/( 1.0f + Math.pow(Math.E,(0.0f - x)))); } public float evaluate(int maxplayer, int minplayer, GameState gs) { return 2.0f*sigmoid(base_score(maxplayer,gs) - base_score(minplayer,gs))-1.0f; } public float base_score(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int index = 0; if (pgs.getWidth() == 128) { index = 1; } float score = 0.0f; float score_buildings = 0.0f; float nr_units = 0.0f; float res_carried = 0.0f; UnitTypeTable utt = gs.getUnitTypeTable(); for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { res_carried += u.getResources(); //UNITS if(u.getType() == utt.getUnitType("Base")) { score_buildings += W_BASE[index]*u.getHitPoints(); } else if(u.getType() == utt.getUnitType("Barracks")) { score_buildings += W_RAX[index]*u.getHitPoints(); } else if(u.getType() == utt.getUnitType("Worker")) { nr_units += 1; score += W_WORKER[index]*u.getHitPoints(); } else if(u.getType() == utt.getUnitType("Light")) { nr_units += 1; score += W_LIGHT[index]*u.getHitPoints()/(float)u.getMaxHitPoints(); } else if(u.getType() == utt.getUnitType("Ranged")) { nr_units += 1; score += W_RANGE[index]*u.getHitPoints(); } else if(u.getType() == utt.getUnitType("Heavy")) { nr_units += 1; score += W_HEAVY[index]*u.getHitPoints()/(float)u.getMaxHitPoints(); } } } score = (float) (score * Math.pow(nr_units, order-1)); score += score_buildings + res_carried * W_MINERALS_CARRIED[index] + gs.getPlayer(player).getResources() * W_MINERALS_MINED[index]; return score; } public float upperBound(GameState gs) { return 2.0f; } }
3,343
32.777778
93
java
MicroRTS
MicroRTS-master/src/ai/evaluation/SimpleEvaluationFunction.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.evaluation; import rts.GameState; import rts.PhysicalGameState; import rts.units.*; /** * * @author santi */ public class SimpleEvaluationFunction extends EvaluationFunction { public static float RESOURCE = 20; public static float RESOURCE_IN_WORKER = 10; public static float UNIT_BONUS_MULTIPLIER = 40.0f; public float evaluate(int maxplayer, int minplayer, GameState gs) { //System.out.println("SimpleEvaluationFunction: " + base_score(maxplayer,gs) + " - " + base_score(minplayer,gs)); return base_score(maxplayer,gs) - base_score(minplayer,gs); } public float base_score(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); float score = gs.getPlayer(player).getResources()*RESOURCE; for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { score += u.getResources() * RESOURCE_IN_WORKER; score += UNIT_BONUS_MULTIPLIER * (u.getCost()*u.getHitPoints())/(float)u.getMaxHitPoints(); } } return score; } public float upperBound(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int free_resources = 0; int player_resources[] = {gs.getPlayer(0).getResources(),gs.getPlayer(1).getResources()}; for(Unit u:pgs.getUnits()) { if (u.getPlayer()==-1) free_resources+=u.getResources(); if (u.getPlayer()==0) { player_resources[0] += u.getResources(); player_resources[0] += u.getCost(); } if (u.getPlayer()==1) { player_resources[1] += u.getResources(); player_resources[1] += u.getCost(); } } // System.out.println(free_resources + " + [" + player_resources[0] + " , " + player_resources[1] + "]"); // if (free_resources + player_resources[0] + player_resources[1]>62) { // System.out.println(gs); // } return (free_resources + Math.max(player_resources[0],player_resources[1]))*UNIT_BONUS_MULTIPLIER; } }
2,256
36.616667
121
java
MicroRTS
MicroRTS-master/src/ai/evaluation/SimpleOptEvaluationFunction.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.evaluation; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; public class SimpleOptEvaluationFunction extends SimpleEvaluationFunction { public static float RESOURCE = 0.19059792f; public static float RESOURCE_IN_WORKER = 0.60513535f; public static float UNIT_BONUS_MULTIPLIER = 0.30983887f; public float evaluate(int maxplayer, int minplayer, GameState gs) { //System.out.println("SimpleEvaluationFunction: " + base_score(maxplayer,gs) + " - " + base_score(minplayer,gs)); return base_score(maxplayer,gs) - base_score(minplayer,gs); } public float base_score(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); float score = gs.getPlayer(player).getResources()*RESOURCE; for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { score += u.getResources() * RESOURCE_IN_WORKER; score += UNIT_BONUS_MULTIPLIER * (u.getCost()*u.getHitPoints())/(float)u.getMaxHitPoints(); } } return score; } public float upperBound(GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); int free_resources = 0; int player_resources[] = {gs.getPlayer(0).getResources(),gs.getPlayer(1).getResources()}; for(Unit u:pgs.getUnits()) { if (u.getPlayer()==-1) free_resources+=u.getResources(); if (u.getPlayer()==0) { player_resources[0] += u.getResources(); player_resources[0] += u.getCost(); } if (u.getPlayer()==1) { player_resources[1] += u.getResources(); player_resources[1] += u.getCost(); } } // System.out.println(free_resources + " + [" + player_resources[0] + " , " + player_resources[1] + "]"); // if (free_resources + player_resources[0] + player_resources[1]>62) { // System.out.println(gs); // } return (free_resources + Math.max(player_resources[0],player_resources[1]))*UNIT_BONUS_MULTIPLIER; } }
2,264
39.446429
121
java