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
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnelliusImportanceSampling.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ArrayUtils; import other.GameLoader; import supplementary.experiments.analysis.RulesetConceptsUCT; import utils.RulesetNames; /** * Generates job scripts to submit to SLURM for running ExIt training runs * * Script generation currently made for Snellius cluster (not RWTH Aachen) * * @author Dennis Soemers */ public class ExItTrainingScriptsGenSnelliusImportanceSampling { //------------------------------------------------------------------------- /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */ private static final String JVM_MEM = "5120"; /** Memory to assign per process (in GB) */ private static final int MEM_PER_PROCESS = 6; /** Memory available per node in GB (this is for Thin nodes on Snellius) */ private static final int MEM_PER_NODE = 256; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 234; /** Max number of self-play trials */ private static final int MAX_SELFPLAY_TRIALS = 200; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 2880; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */ private static final int CORES_PER_PROCESS = 3; /** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_CORES_THRESHOLD = 96; /** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS; /**Number of processes we can put in a single job (on a single node) */ private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS; /** Games we want to run */ private static final String[] GAMES = new String[] { "Amazons.lud", "ArdRi.lud", "Breakthrough.lud", "English Draughts.lud", "Fanorona.lud", "Fox and Geese.lud", "Gomoku.lud", "Groups.lud", "Hex.lud", "Knightthrough.lud", "Konane.lud", "Pentalath.lud", "Reversi.lud", "Royal Game of Ur.lud", "Surakarta.lud", "Tablut.lud", "Yavalath.lud" }; /** Descriptors of several variants we want to test */ private static final String[] VARIANTS = new String[] { "None", "EpisodeDurations", "PER", //"CEExplore", //"CEExploreNoIS", "All" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private ExItTrainingScriptsGenSnelliusImportanceSampling() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // Sort games in decreasing order of expected duration (in moves per trial) // This ensures that we start with the slow games, and that games of similar // durations are likely to end up in the same job script (and therefore run // on the same node at the same time). final Game[] compiledGames = new Game[GAMES.length]; final double[] expectedTrialDurations = new double[GAMES.length]; for (int i = 0; i < compiledGames.length; ++i) { final Game game = GameLoader.loadGameFromName(GAMES[i]); if (game == null) throw new IllegalArgumentException("Cannot load game: " + GAMES[i]); compiledGames[i] = game; expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves"); System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]); } final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()]; if (delta < 0.0) return -1; if (delta > 0.0) return 1; return 0; } }); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (int idx : sortedGameIndices) { final Game game = compiledGames[idx]; final String gameName = GAMES[idx]; for (final String variant : VARIANTS) { processDataList.add(new ProcessData(gameName, game.players().count(), variant)); } } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "TrainFeaturesIS_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J TrainFeaturesIS"); writer.println("#SBATCH -p thin"); writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesIS/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesIS/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc // Compute memory and core requirements final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB); final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD); final int jobMemRequestGB; if (exclusive) jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory else jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM); writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS); writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc if (exclusive) writer.println("#SBATCH --exclusive"); else writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work // load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < numProcessesThisJob) { final ProcessData processData = processDataList.get(processIdx); final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS); final int numPlayingThreads = CORES_PER_PROCESS; // Write Java call for this process String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific core to each process "-c", StringRoutines.join ( ",", String.valueOf(numJobProcesses * 3), String.valueOf(numJobProcesses * 3 + 1), String.valueOf(numJobProcesses * 3 + 2) ), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/TrainFeaturesIS/Ludii.jar"), "--expert-iteration", "--game", StringRoutines.quote("/" + processData.gameName), "-n", String.valueOf(MAX_SELFPLAY_TRIALS), "--out-dir", StringRoutines.quote ( "/home/" + userName + "/TrainFeaturesIS/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + processData.trainingVariant + "/" ), "--iteration-limit 800", "--max-wall-time", String.valueOf(MAX_WALL_TIME), "--checkpoint-freq 5", "--wis", "--game-length-cap 1000", "--no-value-learning", "--num-agent-threads", String.valueOf(numPlayingThreads), "--num-feature-discovery-threads", String.valueOf(numFeatureDiscoveryThreads), "--no-logging" ); if (processData.trainingVariant.equals("EpisodeDurations")) { javaCall += " --is-episode-durations"; } else if (processData.trainingVariant.equals("PER")) { javaCall += " --prioritized-experience-replay"; } else if (processData.trainingVariant.equals("CEExplore")) { javaCall += " --ce-explore"; } else if (processData.trainingVariant.equals("CEExploreNoIS")) { javaCall += " --ce-explore --no-ce-explore-is"; } else if (processData.trainingVariant.equals("All")) { javaCall += " --is-episode-durations"; javaCall += " --prioritized-experience-replay"; //javaCall += " --ce-explore --no-ce-explore-is"; } javaCall += " " + StringRoutines.join ( " ", ">", "/home/" + userName + "/TrainFeaturesIS/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "2>", "/home/" + userName + "/TrainFeaturesIS/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final int numPlayers; public final String trainingVariant; /** * Constructor * @param gameName * @param numPlayers * @param trainingVariant */ public ProcessData(final String gameName, final int numPlayers, final String trainingVariant) { this.gameName = gameName; this.numPlayers = numPlayers; this.trainingVariant = trainingVariant; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating feature training job scripts for Snellius cluster." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
13,683
30.385321
135
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsSmallGames.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ArrayUtils; import other.GameLoader; import supplementary.experiments.analysis.RulesetConceptsUCT; import utils.RulesetNames; /** * Generates scripts for training runs on small games (generally ones * where we can probably easily reach (close to) perfect play. * * @author Dennis Soemers */ public class ExItTrainingScriptsSmallGames { //------------------------------------------------------------------------- /** Memory to assign to JVM */ private static final String JVM_MEM = "5120"; /** Max number of self-play trials */ private static final int MAX_SELFPLAY_TRIALS = 200; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 2880; /** Games we want to run */ private static final String[] GAMES = new String[] { "Tic-Tac-Toe.lud", "Mu Torere.lud", "Mu Torere.lud", "Jeu Militaire.lud", "Pong Hau K'i.lud", "Akidada.lud", "Alquerque de Tres.lud", "Ho-Bag Gonu.lud", "Madelinette.lud", "Haretavl.lud", "Kaooa.lud", "Hat Diviyan Keliya.lud", "Three Men's Morris.lud" }; /** Rulesets we want to run */ private static final String[] RULESETS = new String[] { "", "Ruleset/Complete (Observed)", "Ruleset/Simple (Suggested)", "", "", "", "", "", "", "", "", "", "" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private ExItTrainingScriptsSmallGames() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; // Sort games in decreasing order of expected duration (in moves per trial) // This ensures that we start with the slow games, and that games of similar // durations are likely to end up in the same job script (and therefore run // on the same node at the same time). final Game[] compiledGames = new Game[GAMES.length]; final double[] expectedTrialDurations = new double[GAMES.length]; for (int i = 0; i < compiledGames.length; ++i) { final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]); if (game == null) throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]); compiledGames[i] = game; expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves"); System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]); } final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()]; if (delta < 0.0) return -1; if (delta > 0.0) return 1; return 0; } }); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (int idx : sortedGameIndices) { final Game game = compiledGames[idx]; final String gameName = GAMES[idx]; final String rulesetName = RULESETS[idx]; processDataList.add(new ProcessData(gameName, rulesetName, game.players().count())); } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("mkdir /home/USERNAME/TrainFeaturesSmallGames/Out"); int numJobProcesses = 0; while (numJobProcesses < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); final int numFeatureDiscoveryThreads = processData.numPlayers; final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")); final String cleanRulesetName = StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_"); // Write Java call for this process String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + "USERNAME" + "/TrainFeaturesSmallGames/Ludii.jar"), "--expert-iteration", "--game", StringRoutines.quote("/" + processData.gameName), "--ruleset", StringRoutines.quote(processData.rulesetName), "-n", String.valueOf(MAX_SELFPLAY_TRIALS), "--game-length-cap 1000", "--thinking-time 1", "--is-episode-durations", "--prioritized-experience-replay", "--wis", "--playout-features-epsilon 0.5", "--num-policy-gradient-epochs 100", "--pg-gamma 0.9", "--handle-aliasing", "--no-value-learning", "--train-tspg", "--checkpoint-freq 5", "--num-agent-threads", String.valueOf(1), "--num-policy-gradient-threads", String.valueOf(1), "--post-pg-weight-scalar 0.0", "--num-feature-discovery-threads", String.valueOf(numFeatureDiscoveryThreads), "--out-dir", StringRoutines.quote ( "/home/" + "USERNAME" + "/TrainFeaturesSmallGames/Out/" + cleanGameName + "_" + cleanRulesetName + "/" ), "--no-logging", "--max-wall-time", String.valueOf(MAX_WALL_TIME) ); javaCall += " " + StringRoutines.join ( " ", ">", "/home/" + "USERNAME" + "/TrainFeaturesSmallGames/Out/Out_" + cleanGameName + "_" + cleanRulesetName + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String rulesetName; public final int numPlayers; /** * Constructor * @param gameName * @param rulesetName * @param numPlayers */ public ProcessData(final String gameName, final String rulesetName, final int numPlayers) { this.gameName = gameName; this.rulesetName = rulesetName; this.numPlayers = numPlayers; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating feature training job scripts for small games." ); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,761
27.083333
130
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/ExportLatexConcept.java
package supplementary.experiments.scripts; import other.concept.Concept; /** * To print the concepts in the taxonomy latex format. * * @author Eric.Piette * */ public class ExportLatexConcept { /** * The main method. * * @param args */ public static void main(final String[] args) { final Concept[] concepts = Concept.values(); final StringBuffer results = new StringBuffer(); for(final Concept concept : concepts) { results.append(numIndent(concept.taxonomy()) + concept.taxonomy() + " " + getLatexName(concept.name(), concept.isleaf()) + "\n \n"); //+ concept.description() + "\n \n"); } System.out.println(results.toString()); } /** * @param taxo The taxonomy. * @return The number of necessary indentation in latex for this concept. */ public static String numIndent(final String taxo) { int numIndent = 0; for (int i = 1; i < taxo.length(); i++) { final char c = taxo.charAt(i); if (c != '.') numIndent++; } final StringBuffer indentation = new StringBuffer(); for (int i = 0; i < numIndent; i++) { indentation.append("\\tb" + " "); } return indentation.toString(); } /** * @param name The name of the concept. * @param isLeaf True if the concept is a leaf. * @return The name with space before each upper case. */ public static String getLatexName(final String name, final boolean isLeaf) { final StringBuffer nameToPrint = new StringBuffer(); for (int i = 0; i < name.length(); i++) { final char c = name.charAt(i); if (Character.isLowerCase(c) || i == 0) nameToPrint.append(c); else nameToPrint.append(" " + c); } if(isLeaf) return nameToPrint.toString(); else return "\\textbf{" + nameToPrint.toString() + "}"; } }
1,778
20.433735
75
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/FindBestBaseAgentScriptsGen.java
package supplementary.experiments.scripts; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import agentPrediction.external.AgentPredictionExternal; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ListUtils; import main.options.Ruleset; import metadata.ai.heuristics.Heuristics; import metadata.ai.heuristics.terms.HeuristicTerm; import other.GameLoader; import search.mcts.MCTS; import search.minimax.AlphaBetaSearch; import search.minimax.BRSPlus; import utils.AIFactory; import utils.AIUtils; import utils.RandomAI; /** * Script to find best base agent in every game. * * @author Dennis Soemers */ public class FindBestBaseAgentScriptsGen { /** Memory to assign per CPU, in MB */ private static final String MEM_PER_CPU = "5120"; /** Memory to assign to JVM, in MB */ private static final String JVM_MEM = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 7000; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Max number of trials we want to be running from a single script */ private static final int NUM_TRIALS_PER_SCRIPT = 150; /** All our hyperparameters for MCTS */ private static final String[] mctsHyperparamNames = new String[] { "ExplorationConstant", "Selection", "Backpropagation", "Playout", "ScoreBounds" }; /** Indices for our MCTS hyperparameter types */ private static final int IDX_EXPLORATION_CONSTANT = 0; private static final int IDX_SELECTION = 1; private static final int IDX_BACKPROPAGATION = 2; private static final int IDX_PLAYOUT = 3; private static final int IDX_SCORE_BOUNDS = 4; /** All the values our hyperparameters for MCTS can take */ private static final String[][] mctsHyperParamValues = new String[][] { {"0.1", "0.6", "1.41421356237"}, {"ProgressiveBias", "ProgressiveHistory", "UCB1", "UCB1GRAVE", "UCB1Tuned"}, {"AlphaGo05", "AlphaGo0", "Heuristic", "MonteCarlo", "QualitativeBonus"}, {"MAST", "NST", "Random200", "Random4", "Random0"}, {"true", "false"} }; /** For every MCTS hyperparameter value, an indication of whether stochastic games are supported */ private static final boolean[][] mctsSupportsStochastic = new boolean[][] { {true, true, true}, {true, true, true, true, true}, {true, true, true, true, true}, {true, true, true, true, true}, {false, true}, }; /** For every MCTS hyperparameter value, an indication of whether heuristics are required */ private static final boolean[][] mctsRequiresHeuristic = new boolean[][] { {false, false, false}, {true, false, false, false, false}, {true, true, true, false, true}, {false, false, false, false, false}, {false, false}, }; /** * Games we should skip since they never end anyway (in practice), but do * take a long time. */ private static final String[] SKIP_GAMES = new String[] { "Chinese Checkers.lud", "Li'b al-'Aqil.lud", "Li'b al-Ghashim.lud", "Pagade Kayi Ata (Sixteen-handed).lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private FindBestBaseAgentScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * @param supportStochasticGames Do we need to support stochastic games? * @return All combinations of indices for MCTS hyperparameter values */ public static int[][] generateMCTSCombos(final boolean supportStochasticGames) { if (mctsHyperparamNames.length != 5) { System.err.println("generateMCTSCombos() code currently hardcoded for exactly 5 hyperparams."); return null; } final List<TIntArrayList> combos = new ArrayList<TIntArrayList>(); // Hyperparam 1 for (int i1 = 0; i1 < mctsHyperParamValues[0].length; ++i1) { if (supportStochasticGames && !mctsSupportsStochastic[0][i1]) continue; // Hyperparam 2 for (int i2 = 0; i2 < mctsHyperParamValues[1].length; ++i2) { if (supportStochasticGames && !mctsSupportsStochastic[1][i2]) continue; // Hyperparam 3 for (int i3 = 0; i3 < mctsHyperParamValues[2].length; ++i3) { if (supportStochasticGames && !mctsSupportsStochastic[2][i3]) continue; final boolean alphaGo0Backprop = (mctsHyperParamValues[2][i3].equals("AlphaGo0")); // Hyperparam 4 for (int i4 = 0; i4 < mctsHyperParamValues[3].length; ++i4) { if (supportStochasticGames && !mctsSupportsStochastic[3][i4]) continue; // With AlphaGo-0 backprops, we only support 0-length playouts if (alphaGo0Backprop && !(mctsHyperParamValues[3][i4].equals("Random0"))) continue; // Hyperparam 5 for (int i5 = 0; i5 < mctsHyperParamValues[4].length; ++i5) { if (supportStochasticGames && !mctsSupportsStochastic[4][i5]) continue; combos.add(TIntArrayList.wrap(i1, i2, i3, i4, i5)); } } } } } final int[][] ret = new int[combos.size()][]; for (int i = 0; i < ret.length; ++i) { ret[i] = combos.get(i).toArray(); } return ret; } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); final AlphaBetaSearch dummyAlphaBeta = new AlphaBetaSearch(); final BRSPlus dummyBRSPlus = (BRSPlus) AIFactory.createAI("BRS+"); final MCTS dummyUCT = MCTS.createUCT(); //final MCTS dummyBiased = MCTS.createBiasedMCTS(0.0); //final MCTS dummyBiasedUniformPlayouts = MCTS.createBiasedMCTS(1.0); final RandomAI dummyRandom = (RandomAI) AIFactory.createAI("Random"); final int[][] deterministicMCTSCombos = generateMCTSCombos(false); final int[][] stochasticMCTSCombos = generateMCTSCombos(true); // Construct all the strings for MCTS variants in deterministic games final String[] mctsNamesDeterministic = new String[deterministicMCTSCombos.length]; final String[] mctsStringsDeterministic = new String[deterministicMCTSCombos.length]; final boolean[] mctsRequiresHeuristicsDeterministic = new boolean[deterministicMCTSCombos.length]; for (int i = 0; i < deterministicMCTSCombos.length; ++i) { final int[] combo = deterministicMCTSCombos[i]; mctsRequiresHeuristicsDeterministic[i] = mctsRequiresHeuristic[0][combo[0]] || mctsRequiresHeuristic[1][combo[1]] || mctsRequiresHeuristic[2][combo[2]] || mctsRequiresHeuristic[3][combo[3]] || mctsRequiresHeuristic[4][combo[4]]; final List<String> nameParts = new ArrayList<String>(); final List<String> algStringParts = new ArrayList<String>(); nameParts.add("MCTS"); algStringParts.add("algorithm=MCTS"); algStringParts.add("tree_reuse=true"); final String selectionType = mctsHyperParamValues[IDX_SELECTION][combo[IDX_SELECTION]]; final String explorationConstant = mctsHyperParamValues[IDX_EXPLORATION_CONSTANT][combo[IDX_EXPLORATION_CONSTANT]]; nameParts.add(selectionType); nameParts.add(explorationConstant); algStringParts.add("selection=" + selectionType + ",explorationconstant=" + explorationConstant); String qinitString = "PARENT"; if (Double.parseDouble(explorationConstant) == 0.1) qinitString = "INF"; else if (selectionType.equals("ProgressiveBias")) qinitString = "INF"; algStringParts.add("qinit=" + qinitString); final String playoutType = mctsHyperParamValues[IDX_PLAYOUT][combo[IDX_PLAYOUT]]; nameParts.add(playoutType); switch (playoutType) { case "MAST": algStringParts.add("playout=mast,playoutturnlimit=200"); break; case "NST": algStringParts.add("playout=nst,playoutturnlimit=200"); break; case "Random200": algStringParts.add("playout=random,playoutturnlimit=200"); break; case "Random4": algStringParts.add("playout=random,playoutturnlimit=4"); break; case "Random0": algStringParts.add("playout=random,playoutturnlimit=0"); break; default: System.err.println("Unrecognised playout type: " + playoutType); break; } final String backpropType = mctsHyperParamValues[IDX_BACKPROPAGATION][combo[IDX_BACKPROPAGATION]]; nameParts.add(backpropType); switch (backpropType) { case "AlphaGo05": algStringParts.add("backprop=alphago"); algStringParts.add("playout_value_weight=0.5"); break; case "AlphaGo0": algStringParts.add("backprop=alphago"); algStringParts.add("playout_value_weight=0.0"); break; case "Heuristic": algStringParts.add("backprop=heuristic"); break; case "MonteCarlo": algStringParts.add("backprop=montecarlo"); break; case "QualitativeBonus": algStringParts.add("backprop=qualitativebonus"); break; default: System.err.println("Unrecognised backprop type: " + backpropType); break; } if (mctsHyperParamValues[IDX_SCORE_BOUNDS][combo[IDX_SCORE_BOUNDS]].equals("true")) algStringParts.add("use_score_bounds=true"); algStringParts.add("friendly_name=" + StringRoutines.join("-", nameParts)); mctsNamesDeterministic[i] = StringRoutines.join("-", nameParts); mctsStringsDeterministic[i] = StringRoutines.join(";", algStringParts); } // all the same once more for stochastic games final String[] mctsNamesStochastic = new String[stochasticMCTSCombos.length]; final String[] mctsStringsStochastic = new String[stochasticMCTSCombos.length]; final boolean[] mctsRequiresHeuristicsStochastic = new boolean[stochasticMCTSCombos.length]; for (int i = 0; i < stochasticMCTSCombos.length; ++i) { final int[] combo = stochasticMCTSCombos[i]; mctsRequiresHeuristicsStochastic[i] = mctsRequiresHeuristic[0][combo[0]] || mctsRequiresHeuristic[1][combo[1]] || mctsRequiresHeuristic[2][combo[2]] || mctsRequiresHeuristic[3][combo[3]] || mctsRequiresHeuristic[4][combo[4]]; final List<String> nameParts = new ArrayList<String>(); final List<String> algStringParts = new ArrayList<String>(); nameParts.add("MCTS"); algStringParts.add("algorithm=MCTS"); algStringParts.add("tree_reuse=true"); final String selectionType = mctsHyperParamValues[IDX_SELECTION][combo[IDX_SELECTION]]; final String explorationConstant = mctsHyperParamValues[IDX_EXPLORATION_CONSTANT][combo[IDX_EXPLORATION_CONSTANT]]; nameParts.add(selectionType); nameParts.add(explorationConstant); algStringParts.add("selection=" + selectionType + ",explorationconstant=" + explorationConstant); String qinitString = "PARENT"; if (Double.parseDouble(explorationConstant) == 0.0) qinitString = "INF"; else if (selectionType.equals("ProgressiveBias")) qinitString = "INF"; algStringParts.add("qinit=" + qinitString); final String playoutType = mctsHyperParamValues[IDX_PLAYOUT][combo[IDX_PLAYOUT]]; nameParts.add(playoutType); switch (playoutType) { case "MAST": algStringParts.add("playout=mast,playoutturnlimit=200"); break; case "NST": algStringParts.add("playout=nst,playoutturnlimit=200"); break; case "Random200": algStringParts.add("playout=random,playoutturnlimit=200"); break; case "Random4": algStringParts.add("playout=random,playoutturnlimit=4"); break; case "Random0": algStringParts.add("playout=random,playoutturnlimit=0"); break; default: System.err.println("Unrecognised playout type: " + playoutType); break; } final String backpropType = mctsHyperParamValues[IDX_BACKPROPAGATION][combo[IDX_BACKPROPAGATION]]; nameParts.add(backpropType); switch (backpropType) { case "AlphaGo05": algStringParts.add("backprop=alphago"); algStringParts.add("playout_value_weight=0.5"); break; case "AlphaGo0": algStringParts.add("backprop=alphago"); algStringParts.add("playout_value_weight=0.0"); break; case "Heuristic": algStringParts.add("backprop=heuristic"); break; case "MonteCarlo": algStringParts.add("backprop=montecarlo"); break; case "QualitativeBonus": algStringParts.add("backprop=qualitativebonus"); break; default: System.err.println("Unrecognised backprop type: " + backpropType); break; } if (mctsHyperParamValues[IDX_SCORE_BOUNDS][combo[IDX_SCORE_BOUNDS]].equals("true")) System.err.println("Should never have score bounds in MCTSes for stochastic games!"); algStringParts.add("friendly_name=" + StringRoutines.join("-", nameParts)); mctsNamesStochastic[i] = StringRoutines.join("-", nameParts); mctsStringsStochastic[i] = StringRoutines.join(";", algStringParts); } String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); //final BestStartingHeuristics bestStartingHeuristics = BestStartingHeuristics.loadData(); final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); long callID = 0L; for (final String fullGamePath : allGameNames) { final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); boolean skipGame = false; for (final String game : SKIP_GAMES) { if (gamePathParts[gamePathParts.length - 1].endsWith(game)) { skipGame = true; break; } } if (skipGame) continue; final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), ""); final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud"); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.hasSubgames()) continue; final String bestPredictedHeuristicName = predictBestHeuristic(game); final String filepathsGameName = StringRoutines.cleanGameName(gameName); final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), "")); //final String dbGameName = DBGameInfo.getUniqueName(game); //final Entry abHeuristicEntry = bestStartingHeuristics.getEntry(dbGameName); final List<String> relevantNonMCTSAIs = new ArrayList<String>(); final String alphaBetaString; final String brsPlusString; if (dummyAlphaBeta.supportsGame(game)) { if (bestPredictedHeuristicName != null) { //final String heuristic = abHeuristicEntry.topHeuristic(); alphaBetaString = StringRoutines.join ( ";", "algorithm=Alpha-Beta", "heuristics=/home/" + userName + "/FindStartingHeuristic/" + bestPredictedHeuristicName + ".txt", "friendly_name=AlphaBeta" ); relevantNonMCTSAIs.add("Alpha-Beta"); } else { System.err.println("Null predicted heuristic!"); alphaBetaString = null; } // final Heuristics metadataHeuristics = game.metadata().ai().heuristics(); // if (metadataHeuristics != null) // { // // Also include AlphaBeta with existing metadata heuristics // alphaBetaMetadataString = StringRoutines.join // ( // ";", // "algorithm=Alpha-Beta", // "friendly_name=AlphaBetaMetadata" // ); // relevantAIs.add("Alpha-Beta-Metadata"); // } // else // { // alphaBetaMetadataString = null; // } } else { alphaBetaString = null; //alphaBetaMetadataString = null; } if (dummyBRSPlus.supportsGame(game)) { if (bestPredictedHeuristicName != null) { //final String heuristic = abHeuristicEntry.topHeuristic(); brsPlusString = StringRoutines.join ( ";", "algorithm=BRS+", "heuristics=/home/" + userName + "/FindStartingHeuristic/" + bestPredictedHeuristicName + ".txt", "friendly_name=BRS+" ); relevantNonMCTSAIs.add("BRS+"); } else { brsPlusString = null; } } else { brsPlusString = null; } if (dummyRandom.supportsGame(game)) relevantNonMCTSAIs.add("Random"); final int numPlayers = game.players().count(); int numTrialsThisJob = 0; int jobCounterThisGame = 0; @SuppressWarnings("resource") // Not using try-catch to control this resource because we need to sometimes switch to different files PrintWriter writer = null; try { // Evaluate all of the non-MCTSes against each other for (int evalAgentIdxNonMCTS = 0; evalAgentIdxNonMCTS < relevantNonMCTSAIs.size(); ++evalAgentIdxNonMCTS) { final String agentToEval = relevantNonMCTSAIs.get(evalAgentIdxNonMCTS); for (int oppIdx = 0; oppIdx < relevantNonMCTSAIs.size(); ++oppIdx) { if (writer == null || numTrialsThisJob + numPlayers > NUM_TRIALS_PER_SCRIPT) { // Time to open a new job script if (writer != null) { writer.close(); writer = null; } final String jobScriptFilename = "Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + ".sh"; jobScriptNames.add(jobScriptFilename); numTrialsThisJob = 0; writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"); writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame); writer.println("#SBATCH -o /work/" + userName + "/FindBestBaseAgent/Out" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/FindBestBaseAgent/Err" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); ++jobCounterThisGame; } numTrialsThisJob += numPlayers; // Take (k - 1) copies of same opponent for a k-player game final String[] agentStrings = new String[numPlayers]; for (int i = 0; i < numPlayers - 1; ++i) { final String agent = relevantNonMCTSAIs.get(oppIdx); final String agentCommandString; if (agent.equals("Alpha-Beta")) agentCommandString = StringRoutines.quote(alphaBetaString); else if (agent.equals("BRS+")) agentCommandString = StringRoutines.quote(brsPlusString); else agentCommandString = StringRoutines.quote(agent); agentStrings[i] = agentCommandString; } // and finally add the eval agent final String evalAgentCommandString; if (agentToEval.equals("Alpha-Beta")) evalAgentCommandString = StringRoutines.quote(alphaBetaString); else if (agentToEval.equals("BRS+")) evalAgentCommandString = StringRoutines.quote(brsPlusString); else evalAgentCommandString = StringRoutines.quote(agentToEval); agentStrings[numPlayers - 1] = evalAgentCommandString; final String javaCall = generateJavaCall ( userName, gameName, fullRulesetName, numPlayers, filepathsGameName, filepathsRulesetName, callID, agentStrings ); ++callID; writer.println(javaCall); } } if (dummyUCT.supportsGame(game)) { // Evaluate all MCTSes... final String[] relevantMCTSNames = (game.isStochasticGame()) ? mctsNamesStochastic : mctsNamesDeterministic; final String[] relevantMCTSStrings = (game.isStochasticGame()) ? mctsStringsStochastic : mctsStringsDeterministic; final boolean[] relevantMCTSHeuristicRequirements = (game.isStochasticGame()) ? mctsRequiresHeuristicsStochastic : mctsRequiresHeuristicsDeterministic; for (int evalAgentIdxMCTS = 0; evalAgentIdxMCTS < relevantMCTSNames.length; ++evalAgentIdxMCTS) { // ... against all non-MCTSes... for (int oppIdx = 0; oppIdx < relevantNonMCTSAIs.size(); ++oppIdx) { if (writer == null || numTrialsThisJob + numPlayers > NUM_TRIALS_PER_SCRIPT) { // Time to open a new job script if (writer != null) { writer.close(); writer = null; } final String jobScriptFilename = "Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + ".sh"; jobScriptNames.add(jobScriptFilename); numTrialsThisJob = 0; writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"); writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame); writer.println("#SBATCH -o /work/" + userName + "/FindBestBaseAgent/Out" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/FindBestBaseAgent/Err" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); ++jobCounterThisGame; } numTrialsThisJob += numPlayers; // Take (k - 1) copies of same opponent for a k-player game final String[] agentStrings = new String[numPlayers]; for (int i = 0; i < numPlayers - 1; ++i) { final String agent = relevantNonMCTSAIs.get(oppIdx); final String agentCommandString; if (agent.equals("Alpha-Beta")) agentCommandString = StringRoutines.quote(alphaBetaString); else if (agent.equals("BRS+")) agentCommandString = StringRoutines.quote(brsPlusString); else agentCommandString = StringRoutines.quote(agent); agentStrings[i] = agentCommandString; } // and finally add the eval agent String evalAgentCommandString = relevantMCTSStrings[evalAgentIdxMCTS]; if (relevantMCTSHeuristicRequirements[evalAgentIdxMCTS]) { if (bestPredictedHeuristicName != null) { evalAgentCommandString += ";heuristics=/home/" + userName + "/FindStartingHeuristic/" + bestPredictedHeuristicName + ".txt"; } else { // Our MCTS requires heuristics but we don't have any, so skip continue; } } evalAgentCommandString = StringRoutines.quote(evalAgentCommandString); agentStrings[numPlayers - 1] = evalAgentCommandString; final String javaCall = generateJavaCall ( userName, gameName, fullRulesetName, numPlayers, filepathsGameName, filepathsRulesetName, callID, agentStrings ); ++callID; writer.println(javaCall); } // ... and once against a randomly selected set of (k - 1) other MCTSes for a k-player game if (writer == null || numTrialsThisJob + numPlayers > NUM_TRIALS_PER_SCRIPT) { // Time to open a new job script if (writer != null) { writer.close(); writer = null; } final String jobScriptFilename = "Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + ".sh"; jobScriptNames.add(jobScriptFilename); numTrialsThisJob = 0; writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"); writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J Eval" + filepathsGameName + filepathsRulesetName + jobCounterThisGame); writer.println("#SBATCH -o /work/" + userName + "/FindBestBaseAgent/Out" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/FindBestBaseAgent/Err" + filepathsGameName + filepathsRulesetName + jobCounterThisGame + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); ++jobCounterThisGame; } numTrialsThisJob += numPlayers; final String[] agentStrings = new String[numPlayers]; for (int i = 0; i < numPlayers - 1; ++i) { boolean success = false; final TIntArrayList sampleIndices = ListUtils.range(relevantMCTSNames.length); while (!success) { final int randIdx = ThreadLocalRandom.current().nextInt(sampleIndices.size()); final int otherMCTSIdx = sampleIndices.getQuick(randIdx); ListUtils.removeSwap(sampleIndices, randIdx); String agentCommandString = relevantMCTSStrings[otherMCTSIdx]; if (relevantMCTSHeuristicRequirements[otherMCTSIdx]) { if (bestPredictedHeuristicName != null) { agentCommandString += ";heuristics=/home/" + userName + "/FindStartingHeuristic/" + bestPredictedHeuristicName + ".txt"; success = true; } else { // Our MCTS requires heuristics but we don't have any, so try again //System.out.println("no heuristics in game: " + dbGameName); //System.out.println("picked index " + otherMCTSIdx + " out of " + relevantMCTSNames.length + " options"); continue; } } else { success = true; } agentCommandString = StringRoutines.quote(agentCommandString); agentStrings[i] = agentCommandString; } if (!success) { System.err.println("No suitable MCTS found at all"); continue; } } // add the eval agent String evalAgentCommandString = relevantMCTSStrings[evalAgentIdxMCTS]; if (relevantMCTSHeuristicRequirements[evalAgentIdxMCTS]) { if (bestPredictedHeuristicName != null) { evalAgentCommandString += ";heuristics=/home/" + userName + "/FindStartingHeuristic/" + bestPredictedHeuristicName + ".txt"; } else { // Our MCTS requires heuristics but we don't have any, so skip continue; } } evalAgentCommandString = StringRoutines.quote(evalAgentCommandString); agentStrings[numPlayers - 1] = evalAgentCommandString; final String javaCall = generateJavaCall ( userName, gameName, fullRulesetName, numPlayers, filepathsGameName, filepathsRulesetName, callID, agentStrings ); ++callID; writer.println(javaCall); } } if (writer != null) { writer.close(); writer = null; } } catch (final IOException e) { e.printStackTrace(); } } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; Collections.shuffle(remainingJobScriptNames); while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } public static String predictBestHeuristic(final Game game) { final boolean useClassifier = true; final boolean useCompilationOnly = true; String modelFilePath = "RandomForestClassifier"; if (useClassifier) modelFilePath += "-Classification"; else modelFilePath += "-Regression"; modelFilePath += "-Heuristics"; if (useCompilationOnly) modelFilePath += "-True"; else modelFilePath += "-False"; String sInput = null; String sError = null; try { final String conceptNameString = "RulesetName," + AgentPredictionExternal.conceptNameString(useCompilationOnly); final String conceptValueString = "UNUSED," + AgentPredictionExternal.conceptValueString(game, useCompilationOnly); final String arg1 = modelFilePath; final String arg2 = "Classification"; final String arg3 = conceptNameString; final String arg4 = conceptValueString; final Process p = Runtime.getRuntime().exec("conda.bat activate DefaultEnv && python3 ../../LudiiPrivate/DataMiningScripts/Sklearn/External/GetBestPredictedAgent.py " + arg1 + " " + arg2 + " " + arg3 + " " + arg4); // Read file output final BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((sInput = stdInput.readLine()) != null) { System.out.println(sInput); if (sInput.contains("PREDICTION")) { // Check if returning probabilities for each class. try { final String[] classNamesAndProbas = sInput.split("=")[1].split("_:_"); final String[] classNames = classNamesAndProbas[0].split("_;_"); for (int i = 0; i < classNames.length; i++) classNames[i] = classNames[i]; final String[] valueStrings = classNamesAndProbas[1].split("_;_"); final double[] values = new double[valueStrings.length]; for (int i = 0; i < valueStrings.length; i++) values[i] = Double.parseDouble(valueStrings[i]); if (classNames.length != values.length) System.out.println("ERROR! Class Names and Values should be the same length."); double highestProbabilityValue = -1.0; String highestProbabilityName = "Random"; for (int i = 0; i < classNames.length; i++) { if (values[i] > highestProbabilityValue) { // Check that the heuristic is actually applicable final Heuristics heuristics = AIUtils.convertStringtoHeuristic(classNames[i]); boolean applicable = true; for (final HeuristicTerm term : heuristics.heuristicTerms()) { if (!term.isApplicable(game)) { applicable = false; break; } } if (applicable) { highestProbabilityValue = values[i]; highestProbabilityName = classNames[i]; } } } return highestProbabilityName; } catch (final Exception e) { return sInput.split("=")[1]; } } } // Read any errors. final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((sError = stdError.readLine()) != null) { System.out.println("Python Error\n"); System.out.println(sError); } } catch (final IOException e) { e.printStackTrace(); } return null; } /** * @param userName * @param gameName * @param fullRulesetName * @param numTrialsPerOpponent * @param filepathsGameName * @param filepathsRulesetName * @param callID * @param agentStrings * @return A complete string for a Java call */ public static String generateJavaCall ( final String userName, final String gameName, final String fullRulesetName, final int numTrialsPerOpponent, final String filepathsGameName, final String filepathsRulesetName, final long callID, final String[] agentStrings ) { return StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/FindBestBaseAgent/Ludii.jar"), "--eval-agents", "--game", StringRoutines.quote(gameName + ".lud"), "--ruleset", StringRoutines.quote(fullRulesetName), "-n", String.valueOf(numTrialsPerOpponent), "--game-length-cap 1000", "--thinking-time 1", "--iteration-limit 100000", // 100K iterations per move should be good enough "--warming-up-secs 10", "--out-dir", StringRoutines.quote ( "/work/" + userName + "/FindBestBaseAgent/" + filepathsGameName + filepathsRulesetName + "/" + callID + "/" ), "--agents", StringRoutines.join(" ", agentStrings), "--max-wall-time", String.valueOf(500), "--output-alpha-rank-data", "--no-print-out", "--suppress-divisor-warning" ); } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Evaluate playing strength of different base agents against each other" + " (Alpha-Beta, UCT, MC-GRAVE)." ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
38,032
32.627763
223
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/FindBestStartingHeuristicsScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import game.Game; import game.equipment.other.Regions; import gnu.trove.list.array.TIntArrayList; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ListUtils; import main.options.Ruleset; import metadata.ai.heuristics.Heuristics; import metadata.ai.heuristics.terms.CentreProximity; import metadata.ai.heuristics.terms.ComponentValues; import metadata.ai.heuristics.terms.CornerProximity; import metadata.ai.heuristics.terms.HeuristicTerm; import metadata.ai.heuristics.terms.Influence; import metadata.ai.heuristics.terms.InfluenceAdvanced; import metadata.ai.heuristics.terms.LineCompletionHeuristic; import metadata.ai.heuristics.terms.Material; import metadata.ai.heuristics.terms.MobilityAdvanced; import metadata.ai.heuristics.terms.MobilitySimple; import metadata.ai.heuristics.terms.NullHeuristic; import metadata.ai.heuristics.terms.OwnRegionsCount; import metadata.ai.heuristics.terms.PlayerRegionsProximity; import metadata.ai.heuristics.terms.PlayerSiteMapCount; import metadata.ai.heuristics.terms.RegionProximity; import metadata.ai.heuristics.terms.Score; import metadata.ai.heuristics.terms.SidesProximity; import metadata.ai.heuristics.terms.UnthreatenedMaterial; import other.GameLoader; import search.minimax.AlphaBetaSearch; import utils.AIUtils; /** * Method to generate cluster job scripts for finding the best * starting heuristics. * * We consider every possible starting heuristic individually, always * with a weight of +1.0 or -1.0. Heuristics with multiple weights * (for instance for different piece types) have the same weights * for all types. * * Heuristics evaluated by winning percentage against all other potential * starting heuristics. * * @author Dennis Soemers */ public class FindBestStartingHeuristicsScriptsGen { /** Memory to assign per CPU (and to JVM), in MB */ private static final String MEM_PER_CPU = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 3000; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private FindBestStartingHeuristicsScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); final AlphaBetaSearch dummyAlphaBeta = new AlphaBetaSearch(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); // Generate eval scripts final String userName = argParse.getValueString("--user-name"); for (final String fullGamePath : allGameNames) { final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), ""); final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud"); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.hasSubgames()) continue; if (!dummyAlphaBeta.supportsGame(game)) continue; final String filepathsGameName = StringRoutines.cleanGameName(gameName); final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), "")); final List<String> relevantHeuristics = new ArrayList<String>(); if (CentreProximity.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("CentreProximity", game, argParse)); if (ComponentValues.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("ComponentValues", game, argParse)); if (CornerProximity.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("CornerProximity", game, argParse)); if (LineCompletionHeuristic.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("LineCompletionHeuristic", game, argParse)); if (Material.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("Material", game, argParse)); if (UnthreatenedMaterial.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("UnthreatenedMaterial", game, argParse)); if (MobilitySimple.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("MobilitySimple", game, argParse)); if (MobilityAdvanced.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("MobilityAdvanced", game, argParse)); if (NullHeuristic.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("NullHeuristic", game, argParse)); if (Influence.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("Influence", game, argParse)); if (InfluenceAdvanced.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("InfluenceAdvanced", game, argParse)); if (OwnRegionsCount.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("OwnRegionsCount", game, argParse)); if (PlayerRegionsProximity.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("PlayerRegionsProximity", game, argParse)); if (PlayerSiteMapCount.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("PlayerSiteMapCount", game, argParse)); if (RegionProximity.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("RegionProximity", game, argParse)); if (Score.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("Score", game, argParse)); if (SidesProximity.isSensibleForGame(game)) relevantHeuristics.addAll(heuristicFilepaths("SidesProximity", game, argParse)); final int numPlayers = game.players().count(); for (int evalHeuristicIdx = 0; evalHeuristicIdx < relevantHeuristics.size(); ++evalHeuristicIdx) { final String heuristicToEval = relevantHeuristics.get(evalHeuristicIdx); final TIntArrayList candidateOpponentIndices = new TIntArrayList(relevantHeuristics.size() - 1); for (int i = 0; i < relevantHeuristics.size(); ++i) { if (i != evalHeuristicIdx) candidateOpponentIndices.add(i); } final int numOpponents = numPlayers - 1; final List<TIntArrayList> opponentCombinations = new ArrayList<TIntArrayList>(); final int opponentCombLength; if (candidateOpponentIndices.size() >= numOpponents) opponentCombLength = numOpponents; else opponentCombLength = candidateOpponentIndices.size(); generateAllCombinations(candidateOpponentIndices, opponentCombLength, 0, new int[opponentCombLength], opponentCombinations); while (opponentCombinations.size() > 10) { // Too many combinations of opponents; we'll randomly remove some ListUtils.removeSwap(opponentCombinations, ThreadLocalRandom.current().nextInt(opponentCombinations.size())); } if (candidateOpponentIndices.size() < numOpponents) { // We don't have enough candidates to fill up all opponent slots; // we'll just fill up every combination with duplicates of its last entry for (final TIntArrayList combination : opponentCombinations) { while (combination.size() < numOpponents) { combination.add(combination.getQuick(combination.size() - 1)); } } } final int numCombinations = opponentCombinations.size(); int numGamesPerComb = 10; while (numCombinations * numGamesPerComb < 120) { numGamesPerComb += 10; } final String[] heuristicToEvalSplit = heuristicToEval.split(Pattern.quote("/")); String heuristicToEvalName = heuristicToEvalSplit[heuristicToEvalSplit.length - 1]; heuristicToEvalName = heuristicToEvalName.substring(0, heuristicToEvalName.length() - ".txt".length()); final String jobScriptFilename = "Eval" + filepathsGameName + filepathsRulesetName + heuristicToEvalName + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J Eval" + filepathsGameName + filepathsRulesetName + heuristicToEvalName); writer.println("#SBATCH -o /work/" + userName + "/FindStartingHeuristic/Out" + filepathsGameName + filepathsRulesetName + heuristicToEvalName + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/FindStartingHeuristic/Err" + filepathsGameName + filepathsRulesetName + heuristicToEvalName + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); for (final TIntArrayList agentsCombination : opponentCombinations) { // Add the index of the heuristic to eval in front agentsCombination.insert(0, evalHeuristicIdx); assert (agentsCombination.size() == numPlayers); final String[] agentStrings = new String[numPlayers]; String matchupStr = ""; for (int i = 0; i < numPlayers; ++i) { final String heuristicFilepath = relevantHeuristics.get(agentsCombination.getQuick(i)); final String[] heuristicSplit = heuristicFilepath.split(Pattern.quote("/")); String heuristicName = heuristicSplit[heuristicSplit.length - 1]; heuristicName = heuristicName.substring(0, heuristicName.length() - ".txt".length()); agentStrings[i] = StringRoutines.quote(StringRoutines.join ( ";", "algorithm=HeuristicSampling", "heuristics=" + StringRoutines.quote(heuristicFilepath), "friendly_name=" + heuristicName )); matchupStr += AIUtils.shortenHeuristicName(heuristicName); } final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + MEM_PER_CPU + "M", "-Xmx" + MEM_PER_CPU + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/FindStartingHeuristic/Ludii.jar"), "--eval-agents", "--game", StringRoutines.quote(gameName + ".lud"), "--ruleset", StringRoutines.quote(fullRulesetName), "-n", "" + numGamesPerComb, "--game-length-cap 1000", "--thinking-time 1", "--warming-up-secs 0", "--out-dir", StringRoutines.quote ( "/work/" + userName + "/FindStartingHeuristic/" + filepathsGameName + filepathsRulesetName + "/" + matchupStr + "/" ), "--agents", StringRoutines.join(" ", agentStrings), "--max-wall-time", "" + Math.max((MAX_WALL_TIME / opponentCombinations.size()), 60), "--output-alpha-rank-data", "--no-print-out", "--round-to-next-permutations-divisor" ); writer.println(javaCall); } jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } /** * Generates all combinations of given target combination-length from * the given list of candidates (without replacement, order does not * matter). * * @param candidates * @param combinationLength * @param startIdx Index at which to start filling up results array * @param currentCombination (partial) combination constructed so far * @param combinations List of all result combinations */ private static void generateAllCombinations ( final TIntArrayList candidates, final int combinationLength, final int startIdx, final int[] currentCombination, final List<TIntArrayList> combinations ) { if (combinationLength == 0) { combinations.add(new TIntArrayList(currentCombination)); } else { for (int i = startIdx; i <= candidates.size() - combinationLength; ++i) { currentCombination[currentCombination.length - combinationLength] = candidates.getQuick(i); generateAllCombinations(candidates, combinationLength - 1, i + 1, currentCombination, combinations); } } } //------------------------------------------------------------------------- /** * Returns filepaths for a heuristic (and writes them if they don't already * exist) * @param heuristicDescription * @param game * @param argParse * @return List of filepaths for heuristic term (filepaths for use on cluster) */ private static List<String> heuristicFilepaths ( final String heuristicDescription, final Game game, final CommandLineArgParse argParse ) { final List<String> returnFilepaths = new ArrayList<String>(); final List<String> writeFilepaths = new ArrayList<String>(); final List<HeuristicTerm> heuristicTerms = new ArrayList<HeuristicTerm>(); final String userName = argParse.getValueString("--user-name"); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; if (heuristicDescription.equals("CentreProximity")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/CentreProximityPos.txt"); writeFilepaths.add(scriptsDir + "CentreProximityPos.txt"); heuristicTerms.add(new CentreProximity(null, Float.valueOf(1.f), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/CentreProximityNeg.txt"); writeFilepaths.add(scriptsDir + "CentreProximityNeg.txt"); heuristicTerms.add(new CentreProximity(null, Float.valueOf(-1.f), null)); } else if (heuristicDescription.equals("ComponentValues")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/ComponentValuesPos.txt"); writeFilepaths.add(scriptsDir + "ComponentValuesPos.txt"); heuristicTerms.add(new ComponentValues(null, Float.valueOf(1.f), null, null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/ComponentValuesNeg.txt"); writeFilepaths.add(scriptsDir + "ComponentValuesNeg.txt"); heuristicTerms.add(new ComponentValues(null, Float.valueOf(-1.f), null, null)); } else if (heuristicDescription.equals("CornerProximity")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/CornerProximityPos.txt"); writeFilepaths.add(scriptsDir + "CornerProximityPos.txt"); heuristicTerms.add(new CornerProximity(null, Float.valueOf(1.f), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/CornerProximityNeg.txt"); writeFilepaths.add(scriptsDir + "CornerProximityNeg.txt"); heuristicTerms.add(new CornerProximity(null, Float.valueOf(-1.f), null)); } else if (heuristicDescription.equals("LineCompletionHeuristic")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/LineCompletionHeuristicPos.txt"); writeFilepaths.add(scriptsDir + "LineCompletionHeuristicPos.txt"); heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(1.f), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/LineCompletionHeuristicNeg.txt"); writeFilepaths.add(scriptsDir + "LineCompletionHeuristicNeg.txt"); heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(-1.f), null)); } else if (heuristicDescription.equals("Material")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MaterialPos.txt"); writeFilepaths.add(scriptsDir + "MaterialPos.txt"); heuristicTerms.add(new Material(null, Float.valueOf(1.f), null, null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MaterialNeg.txt"); writeFilepaths.add(scriptsDir + "MaterialNeg.txt"); heuristicTerms.add(new Material(null, Float.valueOf(-1.f), null, null)); } else if (heuristicDescription.equals("MobilityAdvanced")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MobilityAdvancedPos.txt"); writeFilepaths.add(scriptsDir + "MobilityAdvancedPos.txt"); heuristicTerms.add(new MobilityAdvanced(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MobilityAdvancedNeg.txt"); writeFilepaths.add(scriptsDir + "MobilityAdvancedNeg.txt"); heuristicTerms.add(new MobilityAdvanced(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("MobilitySimple")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MobilitySimplePos.txt"); writeFilepaths.add(scriptsDir + "MobilitySimplePos.txt"); heuristicTerms.add(new MobilitySimple(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/MobilitySimpleNeg.txt"); writeFilepaths.add(scriptsDir + "MobilitySimpleNeg.txt"); heuristicTerms.add(new MobilitySimple(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("NullHeuristic")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/NullHeuristicPos.txt"); writeFilepaths.add(scriptsDir + "NullHeuristicPos.txt"); heuristicTerms.add(new NullHeuristic()); } else if (heuristicDescription.equals("Influence")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/InfluencePos.txt"); writeFilepaths.add(scriptsDir + "InfluencePos.txt"); heuristicTerms.add(new Influence(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/InfluenceNeg.txt"); writeFilepaths.add(scriptsDir + "InfluenceNeg.txt"); heuristicTerms.add(new Influence(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("InfluenceAdvanced")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/InfluenceAdvancedPos.txt"); writeFilepaths.add(scriptsDir + "InfluenceAdvancedPos.txt"); heuristicTerms.add(new InfluenceAdvanced(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/InfluenceAdvancedNeg.txt"); writeFilepaths.add(scriptsDir + "InfluenceAdvancedNeg.txt"); heuristicTerms.add(new InfluenceAdvanced(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("OwnRegionsCount")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/OwnRegionsCountPos.txt"); writeFilepaths.add(scriptsDir + "OwnRegionsCountPos.txt"); heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/OwnRegionsCountNeg.txt"); writeFilepaths.add(scriptsDir + "OwnRegionsCountNeg.txt"); heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("PlayerRegionsProximity")) { final Regions[] regions = game.equipment().regions(); for (int p = 1; p <= game.players().count(); ++p) { boolean foundOwnedRegion = false; for (final Regions region : regions) { if (region.owner() == p) { foundOwnedRegion = true; break; } } if (foundOwnedRegion) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/PlayerRegionsProximityPos_" + p + ".txt"); writeFilepaths.add(scriptsDir + "PlayerRegionsProximityPos_" + p + ".txt"); heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(1.f), Integer.valueOf(p), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/PlayerRegionsProximityNeg_" + p + ".txt"); writeFilepaths.add(scriptsDir + "PlayerRegionsProximityNeg_" + p + ".txt"); heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(-1.f), Integer.valueOf(p), null)); } } } else if (heuristicDescription.equals("PlayerSiteMapCount")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/PlayerSiteMapCountPos.txt"); writeFilepaths.add(scriptsDir + "PlayerSiteMapCountPos.txt"); heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/PlayerSiteMapCountNeg.txt"); writeFilepaths.add(scriptsDir + "PlayerSiteMapCountNeg.txt"); heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("RegionProximity")) { final Regions[] regions = game.equipment().regions(); for (int i = 0; i < regions.length; ++i) { if (game.distancesToRegions()[i] != null) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/RegionProximityPos_" + i + ".txt"); writeFilepaths.add(scriptsDir + "RegionProximityPos_" + i + ".txt"); heuristicTerms.add(new RegionProximity(null, Float.valueOf(1.f), Integer.valueOf(i), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/RegionProximityNeg_" + i + ".txt"); writeFilepaths.add(scriptsDir + "RegionProximityNeg_" + i + ".txt"); heuristicTerms.add(new RegionProximity(null, Float.valueOf(-1.f), Integer.valueOf(i), null)); } } } else if (heuristicDescription.equals("Score")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/ScorePos.txt"); writeFilepaths.add(scriptsDir + "ScorePos.txt"); heuristicTerms.add(new Score(null, Float.valueOf(1.f))); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/ScoreNeg.txt"); writeFilepaths.add(scriptsDir + "ScoreNeg.txt"); heuristicTerms.add(new Score(null, Float.valueOf(-1.f))); } else if (heuristicDescription.equals("SidesProximity")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/SidesProximityPos.txt"); writeFilepaths.add(scriptsDir + "SidesProximityPos.txt"); heuristicTerms.add(new SidesProximity(null, Float.valueOf(1.f), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/SidesProximityNeg.txt"); writeFilepaths.add(scriptsDir + "SidesProximityNeg.txt"); heuristicTerms.add(new SidesProximity(null, Float.valueOf(-1.f), null)); } else if (heuristicDescription.equals("UnthreatenedMaterial")) { returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/UnthreatenedMaterialPos.txt"); writeFilepaths.add(scriptsDir + "UnthreatenedMaterialPos.txt"); heuristicTerms.add(new UnthreatenedMaterial(null, Float.valueOf(1.f), null)); returnFilepaths.add("/home/" + userName + "/FindStartingHeuristic/UnthreatenedMaterialNeg.txt"); writeFilepaths.add(scriptsDir + "UnthreatenedMaterialNeg.txt"); heuristicTerms.add(new UnthreatenedMaterial(null, Float.valueOf(-1.f), null)); } else { throw new RuntimeException("Did not recognise heuristic description: " + heuristicDescription); } // Write our heuristic files for (int i = 0; i < heuristicTerms.size(); ++i) { final HeuristicTerm heuristic = heuristicTerms.get(i); final File file = new File(writeFilepaths.get(i)); if (!file.exists()) { try (final PrintWriter writer = new UnixPrintWriter(file, "UTF-8")) { writer.write(new Heuristics(heuristic).toString()); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } return returnFilepaths; } /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Evaluate playing strength of different heuristic sampling agents with different" + " default heuristics against each other." ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
29,051
38.472826
131
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/FindCrashingTrialScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; /** * Method to generate cluster job scripts for playing lots of trials of a given * game until we crash, and then saving the trial right before we crashed. * * @author Dennis Soemers */ public class FindCrashingTrialScriptsGen { /** Memory to assign per CPU (and to JVM), in MB */ private static final String MEM_PER_CPU = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 6000; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private FindCrashingTrialScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); final int numJobs = argParse.getValueInt("--num-jobs"); for (int jobID = 0; jobID < numJobs; ++jobID) { final String jobScriptFilename = "FindCrashingTrial_" + jobID + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J FindCrashingTrial_" + jobID); writer.println("#SBATCH -o /work/" + userName + "/FindCrashingTrial/Out_" + jobID + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/FindCrashingTrial/Err_" + jobID + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); @SuppressWarnings("unchecked") final String[] agentsStrings = ((List<String>) argParse.getValue("--agents")).toArray(new String[0]); for (int i = 0; i < agentsStrings.length; ++i) { agentsStrings[i] = StringRoutines.quote(agentsStrings[i]); } final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + MEM_PER_CPU + "M", "-Xmx" + MEM_PER_CPU + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/FindCrashingTrial/Ludii.jar"), "--find-crashing-trial", "--game", StringRoutines.quote(argParse.getValueString("--game")), "-n", "" + argParse.getValueInt("--num-trials-per-job"), "--game-length-cap 1000", "--thinking-time " + argParse.getValueDouble("--thinking-time"), "--depth-limit " + argParse.getValueInt("--depth-limit"), "--iteration-limit " + argParse.getValueInt("--iteration-limit"), "--out-trial-file", StringRoutines.quote ( "/work/" + userName + "/FindCrashingTrial/" + "CrashTrial_" + jobID + ".trl" ), "--agents", StringRoutines.join(" ", agentsStrings), "--max-wall-time", "" + Math.max((MAX_WALL_TIME), 60), "--no-print-out" ); writer.println(javaCall); jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Play many trials of a game, save trials right before crashes." ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--num-trials-per-job") .help("Number of trials to run per job.") .withNumVals(1) .withType(OptionTypes.Int) .withDefault(Integer.valueOf(100))); argParse.addOption(new ArgOption() .withNames("--num-jobs") .help("Number of (copies of) jobs to run.") .withNumVals(1) .withType(OptionTypes.Int) .withDefault(Integer.valueOf(100))); argParse.addOption(new ArgOption() .withNames("--game") .help("Name of the game to play. Should end with \".lud\".") .withDefault("Amazons.lud") .withNumVals(1) .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--game-options") .help("Game Options to load.") .withDefault(new ArrayList<String>(0)) .withNumVals("*") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--agents") .help("Agents to use for playing") .withDefault(Arrays.asList("UCT", "Biased MCTS")) .withNumVals("+") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--thinking-time", "--time", "--seconds") .help("Max allowed thinking time per move (in seconds).") .withDefault(Double.valueOf(1.0)) .withNumVals(1) .withType(OptionTypes.Double)); argParse.addOption(new ArgOption() .withNames("--iteration-limit", "--iterations") .help("Max allowed number of MCTS iterations per move.") .withDefault(Integer.valueOf(-1)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--depth-limit") .help("Max allowed search depth per move (for e.g. alpha-beta).") .withDefault(Integer.valueOf(-1)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--no-rotate-agents") .help("Don't rotate through possible assignments of agents to Player IDs.") .withType(OptionTypes.Boolean) .withNumVals(0)); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,506
29.382143
118
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/GenerateBiasedMCTSEvalScripts.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.DoubleAdder; import java.util.regex.Pattern; import decision_trees.classifiers.DecisionTreeNode; import decision_trees.classifiers.ExperienceIQRTreeLearner; import features.feature_sets.BaseFeatureSet; import features.spatial.Walk; import function_approx.LinearFunction; import game.Game; import game.types.play.RoleType; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ArrayUtils; import main.collections.ListUtils; import main.options.Ruleset; import metadata.ai.features.trees.FeatureTrees; import other.GameLoader; import other.WeaklyCachingGameLoader; import policies.softmax.SoftmaxPolicyLinear; import search.mcts.MCTS; import supplementary.experiments.analysis.RulesetConceptsUCT; import utils.AIFactory; import utils.ExperimentFileUtils; import utils.RulesetNames; import utils.data_structures.experience_buffers.ExperienceBuffer; import utils.data_structures.experience_buffers.PrioritizedReplayBuffer; import utils.data_structures.experience_buffers.UniformExperienceBuffer; /** * Class with main method to automatically generate all the appropriate evaluation * scripts for features on the Snellius cluster. * * @author Dennis Soemers */ public class GenerateBiasedMCTSEvalScripts { /** Number of threads to use for our actual job that's generating eval scripts */ private static final int NUM_GENERATION_THREADS = 96; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */ private static final String JVM_MEM = "5120"; /** Memory to assign per process (in GB) */ private static final int MEM_PER_PROCESS = 6; /** Memory available per node in GB (this is for Thin nodes on Snellius) */ private static final int MEM_PER_NODE = 256; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 234; /** Num trials per matchup */ private static final int NUM_TRIALS = 100; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 1445; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */ private static final int CORES_PER_PROCESS = 3; /** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_CORES_THRESHOLD = 96; /** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS; /**Number of processes we can put in a single job (on a single node) */ private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS; /** * Games we should skip since they never end anyway (in practice), but do * take a long time. */ private static final String[] SKIP_GAMES = new String[] { "Chinese Checkers.lud", "Li'b al-'Aqil.lud", "Li'b al-Ghashim.lud", "Mini Wars.lud", "Pagade Kayi Ata (Sixteen-handed).lud", "Taikyoku Shogi.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private GenerateBiasedMCTSEvalScripts() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); final String userName = argParse.getValueString("--user-name"); // Modify the ruleset filepaths for running on Snellius RulesetConceptsUCT.FILEPATH = "/home/" + userName + "/rulesetConceptsUCT.csv"; RulesetNames.FILEPATH = "/home/" + userName + "/GameRulesets.csv"; final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); final List<String> gameNames = new ArrayList<String>(); final List<String> rulesetNames = new ArrayList<String>(); final TIntArrayList gamePlayerCounts = new TIntArrayList(); final TDoubleArrayList expectedTrialDurations = new TDoubleArrayList(); for (final String gameName : allGameNames) { final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String shortGameName = gameNameSplit[gameNameSplit.length - 1]; boolean skipGame = false; for (final String game : SKIP_GAMES) { if (shortGameName.endsWith(game)) { skipGame = true; break; } } if (skipGame) continue; final Game gameNoRuleset = GameLoader.loadGameFromName(gameName); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName, fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.hasSubgames()) continue; if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.isStacking()) continue; if (game.isBoardless()) continue; if (game.hiddenInformation()) continue; final double drawishness = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "Drawishness"); if (drawishness == 1.0) { System.out.println("Skipping " + shortGameName + " (" + fullRulesetName + ") because of drawishness."); continue; } if (Walk.allGameRotations(game).length == 0) continue; // TODO skip games played on edges (maybe done by the Walk thing above?) final File trainingOutDir = new File ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(("/" + shortGameName).replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(fullRulesetName).replaceAll(Pattern.quote("/"), "_") + "/" ); if (!trainingOutDir.exists() || !trainingOutDir.isDirectory()) continue; // No training results for this ruleset final String[] trainingOutDirFiles = trainingOutDir.list(); if (trainingOutDirFiles.length == 0) continue; // No training results for this ruleset boolean haveBuffers = false; for (final String s : trainingOutDirFiles) { if (s.contains("ExperienceBuffer")) { haveBuffers = true; break; } } if (!haveBuffers) continue; // No training results for this ruleset double expectedTrialDuration = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves"); if (Double.isNaN(expectedTrialDuration)) expectedTrialDuration = Double.MAX_VALUE; gameNames.add("/" + shortGameName); rulesetNames.add(fullRulesetName); gamePlayerCounts.add(game.players().count()); expectedTrialDurations.add(expectedTrialDuration); } } // Sort games in decreasing order of expected duration (in moves per trial) // This ensures that we start with the slow games, and that games of similar // durations are likely to end up in the same job script (and therefore run // on the same node at the same time). final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(gameNames.size(), new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { final double delta = expectedTrialDurations.getQuick(i2.intValue()) - expectedTrialDurations.getQuick(i1.intValue()); if (delta < 0.0) return -1; if (delta > 0.0) return 1; return 0; } }); // Create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (int idx : sortedGameIndices) { final int numPlayers = gamePlayerCounts.getQuick(idx); processDataList.add(new ProcessData(gameNames.get(idx), rulesetNames.get(idx), numPlayers)); } final ExecutorService executor = Executors.newFixedThreadPool(NUM_GENERATION_THREADS); try { final CountDownLatch latch = new CountDownLatch(processDataList.size()); for (final ProcessData processData : processDataList) { executor.submit ( () -> { try { final Game game = WeaklyCachingGameLoader.SINGLETON.loadGameFromName(processData.gameName, processData.rulesetName); // Construct an MCTS object with trained CE selection policy, easiest way to extract // the features from files again final StringBuilder playoutSb = new StringBuilder(); playoutSb.append("playout=softmax"); for (int p = 1; p <= game.players().count(); ++p) { final String policyFilepath = ExperimentFileUtils.getLastFilepath ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/PolicyWeightsSelection" + "_P" + p, "txt" ); playoutSb.append(",policyweights" + p + "=" + policyFilepath); } final StringBuilder selectionSb = new StringBuilder(); selectionSb.append("learned_selection_policy=playout"); final String agentStr = StringRoutines.join ( ";", "algorithm=MCTS", "selection=noisyag0selection", playoutSb.toString(), "final_move=robustchild", "tree_reuse=true", selectionSb.toString(), "friendly_name=BiasedMCTS" ); final MCTS mcts = (MCTS) AIFactory.createAI(agentStr); final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy(); final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets(); final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions(); playoutSoftmax.initAI(game, -1); // Now build trees (only depth 3) final int DEPTH = 3; final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees = new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1]; for (int p = 1; p < featureSets.length; ++p) { // Load experience buffer for Player p final String bufferFilepath = ExperimentFileUtils.getLastFilepath ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/ExperienceBuffer_P" + p, "buf" ); ExperienceBuffer buffer = null; try { buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath); } catch (final Exception e) { if (buffer == null) { try { buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath); } catch (final Exception e2) { e.printStackTrace(); e2.printStackTrace(); } } } // Generate decision tree for Player p final DecisionTreeNode root = ExperienceIQRTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, DEPTH, 5); // Convert to metadata structure final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode(); metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot); } final String outFile = "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/IQR_Tree_" + 3 + ".txt"; System.out.println("Writing IQR tree to: " + outFile); new File(outFile).getParentFile().mkdirs(); try (final PrintWriter writer = new PrintWriter(outFile)) { writer.println(new FeatureTrees(null, metadataTrees)); } catch (final IOException e) { e.printStackTrace(); } } catch (final Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } ); } latch.await(); } catch (final Exception e) { e.printStackTrace(); } // Now write all the eval job scripts final List<EvalProcessData> evalProcessDataList = new ArrayList<EvalProcessData>(); for (final ProcessData processData : processDataList) { final int numPlayers = processData.numPlayers; evalProcessDataList.add(new EvalProcessData(processData.gameName, processData.rulesetName, processData.numPlayers, "Biased")); if (numPlayers == 1) // Need to evaluate UCT separately evalProcessDataList.add(new EvalProcessData(processData.gameName, processData.rulesetName, processData.numPlayers, "UCT")); } final DoubleAdder totalCoreHoursRequested = new DoubleAdder(); final int numProcessBatches = (int) Math.ceil((double)evalProcessDataList.size() / PROCESSES_PER_JOB); final TIntArrayList batchIndices = ListUtils.range(numProcessBatches); try { final CountDownLatch latch = new CountDownLatch(batchIndices.size()); for (int i = 0; i < batchIndices.size(); ++i) { final int batchIdx = batchIndices.getQuick(i); final int evalProcessStartIdx = batchIdx * PROCESSES_PER_JOB; final int evalProcessEndIdx = Math.min((batchIdx + 1) * PROCESSES_PER_JOB, evalProcessDataList.size()); // Start a new job script final String jobScriptFilename = "EvalBiasedMCTS_" + batchIdx + ".sh"; executor.submit ( () -> { try ( final PrintWriter writer = new UnixPrintWriter ( new File("/home/" + userName + "/EvalBiasedMCTSAllGames/" + jobScriptFilename), "UTF-8" ) ) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J EvalBiasedMCTS"); writer.println("#SBATCH -p thin"); writer.println("#SBATCH -o /home/" + userName + "/EvalBiasedMCTSAllGames/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/EvalBiasedMCTSAllGames/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc // Compute memory and core requirements final int numProcessesThisJob = evalProcessEndIdx - evalProcessStartIdx; final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD); final int jobMemRequestGB; if (exclusive) jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory else jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM); totalCoreHoursRequested.add(CORES_PER_NODE * (MAX_WALL_TIME / 60.0)); writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS); writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc if (exclusive) writer.println("#SBATCH --exclusive"); else writer.println("#SBATCH --exclusive"); // load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; for (int processIdx = evalProcessStartIdx; processIdx < evalProcessEndIdx; ++processIdx) { final EvalProcessData evalProcessData = evalProcessDataList.get(processIdx); final List<String> agentStrings = new ArrayList<String>(); final String agentStr1; if (evalProcessData.evalAgent.equals("UCT")) { agentStr1 = "algorithm=UCT"; } else { final List<String> playoutStrParts = new ArrayList<String>(); playoutStrParts.add("playout=classificationtreepolicy"); for (int p = 1; p <= evalProcessData.numPlayers; ++p) { playoutStrParts.add ( "policytrees=/" + StringRoutines.join ( "/", "home", userName, "TrainFeaturesSnelliusAllGames", "Out" + StringRoutines.cleanGameName(evalProcessData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(evalProcessData.rulesetName).replaceAll(Pattern.quote("/"), "_"), "IQR_Tree_3" + ".txt" ) + "," + "greedy=false" ); } final List<String> learnedSelectionStrParts = new ArrayList<String>(); learnedSelectionStrParts.add("learned_selection_policy=playout"); agentStr1 = StringRoutines.join ( ";", "algorithm=MCTS", "selection=noisyag0selection", // Noisy variant here because we're using playout policy in selection StringRoutines.join ( ",", playoutStrParts ), "tree_reuse=true", "use_score_bounds=true", "num_threads=3", "final_move=robustchild", StringRoutines.join ( ",", learnedSelectionStrParts ), "friendly_name=BiasedMCTS" ); } while (agentStrings.size() < evalProcessData.numPlayers) { agentStrings.add(StringRoutines.quote(agentStr1)); if (agentStrings.size() < evalProcessData.numPlayers) agentStrings.add(StringRoutines.quote("algorithm=UCT")); } // Write Java call for this process String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific cores to each process "-c", StringRoutines.join ( ",", String.valueOf(numJobProcesses * 3), String.valueOf(numJobProcesses * 3 + 1), String.valueOf(numJobProcesses * 3 + 2) ), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/EvalBiasedMCTSAllGames/Ludii.jar"), "--eval-agents", "--game", StringRoutines.quote(evalProcessData.gameName), "--ruleset", StringRoutines.quote(evalProcessData.rulesetName), "-n " + NUM_TRIALS, "--thinking-time 1", "--agents", StringRoutines.join(" ", agentStrings), "--warming-up-secs", String.valueOf(30), "--game-length-cap", String.valueOf(1000), "--out-dir", StringRoutines.quote ( "/home/" + userName + "/EvalBiasedMCTSAllGames/Out" + StringRoutines.cleanGameName(evalProcessData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(evalProcessData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/" + evalProcessData.evalAgent ), "--output-summary", "--output-alpha-rank-data", "--max-wall-time", String.valueOf(MAX_WALL_TIME), ">", "/home/" + userName + "/EvalBiasedMCTSAllGames/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } ); } latch.await(); } catch (final Exception e) { e.printStackTrace(); } executor.shutdown(); final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File("/home/" + userName + "/EvalBiasedMCTSAllGames/SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } System.out.println("Total core hours requested = " + totalCoreHoursRequested.doubleValue()); } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String rulesetName; public final int numPlayers; /** * Constructor * @param gameName * @param rulesetName * @param numPlayers */ public ProcessData(final String gameName, final String rulesetName, final int numPlayers) { this.gameName = gameName; this.rulesetName = rulesetName; this.numPlayers = numPlayers; } } /** * Wrapper around data for a single eval process (multiple processes per job) * * @author Dennis Soemers */ private static class EvalProcessData { public final String gameName; public final String rulesetName; public final int numPlayers; public final String evalAgent; /** * Constructor * @param gameName * @param rulesetName * @param numPlayers * @param evalAgent */ public EvalProcessData(final String gameName, final String rulesetName, final int numPlayers, final String evalAgent) { this.gameName = gameName; this.rulesetName = rulesetName; this.numPlayers = numPlayers; this.evalAgent = evalAgent; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Generates scripts to run on cluster for evaluation of MCTS with features." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
27,099
30.733021
151
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/GenerateFeatureEvalScripts.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.DoubleAdder; import java.util.regex.Pattern; import decision_trees.logits.ExperienceLogitTreeLearner; import decision_trees.logits.LogitTreeNode; import features.feature_sets.BaseFeatureSet; import features.spatial.Walk; import function_approx.LinearFunction; import game.Game; import game.types.play.RoleType; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ArrayUtils; import main.collections.ListUtils; import main.options.Ruleset; import metadata.ai.features.trees.FeatureTrees; import other.GameLoader; import other.WeaklyCachingGameLoader; import policies.softmax.SoftmaxPolicyLinear; import search.mcts.MCTS; import supplementary.experiments.analysis.RulesetConceptsUCT; import utils.AIFactory; import utils.ExperimentFileUtils; import utils.RulesetNames; import utils.data_structures.experience_buffers.ExperienceBuffer; import utils.data_structures.experience_buffers.PrioritizedReplayBuffer; import utils.data_structures.experience_buffers.UniformExperienceBuffer; /** * Class with main method to automatically generate all the appropriate evaluation * scripts (and build decision trees) for features on the Snellius cluster. * * @author Dennis Soemers */ public class GenerateFeatureEvalScripts { /** Number of threads to use for our actual job that's building decision trees and generating eval scripts */ private static final int NUM_GENERATION_THREADS = 96; /** Depth limits for which we want to build decision trees */ private static final int[] DECISION_TREE_DEPTHS = new int[] {1, 2, 3, 4, 5}; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */ private static final String JVM_MEM = "5120"; /** Memory to assign per process (in GB) */ private static final int MEM_PER_PROCESS = 6; /** Memory available per node in GB (this is for Thin nodes on Snellius) */ private static final int MEM_PER_NODE = 256; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 234; /** Num trials per matchup */ private static final int NUM_TRIALS = 100; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 60; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */ private static final int CORES_PER_PROCESS = 3; /** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_CORES_THRESHOLD = 96; /** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS; /**Number of processes we can put in a single job (on a single node) */ private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS; /** * Games we should skip since they never end anyway (in practice), but do * take a long time. */ private static final String[] SKIP_GAMES = new String[] { "Chinese Checkers.lud", "Li'b al-'Aqil.lud", "Li'b al-Ghashim.lud", "Mini Wars.lud", "Pagade Kayi Ata (Sixteen-handed).lud", "Taikyoku Shogi.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private GenerateFeatureEvalScripts() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); final String userName = argParse.getValueString("--user-name"); // Modify the ruleset filepaths for running on Snellius RulesetConceptsUCT.FILEPATH = "/home/" + userName + "/rulesetConceptsUCT.csv"; RulesetNames.FILEPATH = "/home/" + userName + "/GameRulesets.csv"; final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); final List<String> gameNames = new ArrayList<String>(); final List<String> rulesetNames = new ArrayList<String>(); final TIntArrayList gamePlayerCounts = new TIntArrayList(); final TDoubleArrayList expectedTrialDurations = new TDoubleArrayList(); for (final String gameName : allGameNames) { final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String shortGameName = gameNameSplit[gameNameSplit.length - 1]; boolean skipGame = false; for (final String game : SKIP_GAMES) { if (shortGameName.endsWith(game)) { skipGame = true; break; } } if (skipGame) continue; final Game gameNoRuleset = GameLoader.loadGameFromName(gameName); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName, fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.hasSubgames()) continue; if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.isStacking()) continue; if (game.isBoardless()) continue; if (game.hiddenInformation()) continue; if (Walk.allGameRotations(game).length == 0) continue; // TODO skip games played on edges (maybe done by the Walk thing above?) final File trainingOutDir = new File ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(("/" + shortGameName).replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(fullRulesetName).replaceAll(Pattern.quote("/"), "_") + "/" ); if (!trainingOutDir.exists() || !trainingOutDir.isDirectory()) continue; // No training results for this ruleset final String[] trainingOutDirFiles = trainingOutDir.list(); if (trainingOutDirFiles.length == 0) continue; // No training results for this ruleset boolean haveBuffers = false; for (final String s : trainingOutDirFiles) { if (s.contains("ExperienceBuffer")) { haveBuffers = true; break; } } if (!haveBuffers) continue; // No training results for this ruleset double expectedTrialDuration = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves"); if (Double.isNaN(expectedTrialDuration)) expectedTrialDuration = Double.MAX_VALUE; gameNames.add("/" + shortGameName); rulesetNames.add(fullRulesetName); gamePlayerCounts.add(game.players().count()); expectedTrialDurations.add(expectedTrialDuration); } } // Sort games in decreasing order of expected duration (in moves per trial) // This ensures that we start with the slow games, and that games of similar // durations are likely to end up in the same job script (and therefore run // on the same node at the same time). final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(gameNames.size(), new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { final double delta = expectedTrialDurations.getQuick(i2.intValue()) - expectedTrialDurations.getQuick(i1.intValue()); if (delta < 0.0) return -1; if (delta > 0.0) return 1; return 0; } }); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (int idx : sortedGameIndices) { processDataList.add(new ProcessData(gameNames.get(idx), rulesetNames.get(idx), gamePlayerCounts.getQuick(idx))); } // Build all the decision trees final ExecutorService executor = Executors.newFixedThreadPool(NUM_GENERATION_THREADS); try { final CountDownLatch latch = new CountDownLatch(processDataList.size()); for (final ProcessData processData : processDataList) { executor.submit ( () -> { try { final Game game = WeaklyCachingGameLoader.SINGLETON.loadGameFromName(processData.gameName, processData.rulesetName); // Construct an MCTS object with trained CE selection policy, easiest way to extract // the features from files again final StringBuilder playoutSb = new StringBuilder(); playoutSb.append("playout=softmax"); for (int p = 1; p <= game.players().count(); ++p) { final String policyFilepath = ExperimentFileUtils.getLastFilepath ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/PolicyWeightsSelection" + "_P" + p, "txt" ); playoutSb.append(",policyweights" + p + "=" + policyFilepath); } final StringBuilder selectionSb = new StringBuilder(); selectionSb.append("learned_selection_policy=playout"); final String agentStr = StringRoutines.join ( ";", "algorithm=MCTS", "selection=noisyag0selection", playoutSb.toString(), "final_move=robustchild", "tree_reuse=true", selectionSb.toString(), "friendly_name=BiasedMCTS" ); final MCTS mcts = (MCTS) AIFactory.createAI(agentStr); final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy(); final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets(); final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions(); playoutSoftmax.initAI(game, -1); // Now build trees final metadata.ai.features.trees.logits.LogitTree[][] metadataTreesPerDepth = new metadata.ai.features.trees.logits.LogitTree[DECISION_TREE_DEPTHS.length][featureSets.length - 1]; for (int p = 1; p < featureSets.length; ++p) { // Load experience buffer for Player p final String bufferFilepath = ExperimentFileUtils.getLastFilepath ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/ExperienceBuffer_P" + p, "buf" ); ExperienceBuffer buffer = null; try { buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath); } catch (final Exception e) { if (buffer == null) { try { buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath); } catch (final Exception e2) { e.printStackTrace(); e2.printStackTrace(); } } } for (final int depth : DECISION_TREE_DEPTHS) { // Generate decision tree for Player p final LogitTreeNode root = ExperienceLogitTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5); // Convert to metadata structure final metadata.ai.features.trees.logits.LogitNode metadataRoot = root.toMetadataNode(); metadataTreesPerDepth[ArrayUtils.indexOf(depth, DECISION_TREE_DEPTHS)][p - 1] = new metadata.ai.features.trees.logits.LogitTree(RoleType.roleForPlayerId(p), metadataRoot); } } for (int depthIdx = 0; depthIdx < DECISION_TREE_DEPTHS.length; ++depthIdx) { final int depth = DECISION_TREE_DEPTHS[depthIdx]; final String outFile = "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/CE_Selection_Logit_Tree_" + depth + ".txt"; System.out.println("Writing Logit Regression tree to: " + outFile); new File(outFile).getParentFile().mkdirs(); try (final PrintWriter writer = new PrintWriter(outFile)) { writer.println(new FeatureTrees(metadataTreesPerDepth[depthIdx], null)); } catch (final IOException e) { e.printStackTrace(); } } } catch (final Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } ); } latch.await(); } catch (final Exception e) { e.printStackTrace(); } // Now write all the eval job scripts final List<EvalProcessData> evalProcessDataList = new ArrayList<EvalProcessData>(); for (final ProcessData processData : processDataList) { for (int i = 0; i < DECISION_TREE_DEPTHS.length - 1; ++i) { evalProcessDataList.add(new EvalProcessData(processData.gameName, processData.rulesetName, processData.numPlayers, DECISION_TREE_DEPTHS[i], DECISION_TREE_DEPTHS[i + 1])); } } final DoubleAdder totalCoreHoursRequested = new DoubleAdder(); final int numProcessBatches = (int) Math.ceil((double)evalProcessDataList.size() / PROCESSES_PER_JOB); final TIntArrayList batchIndices = ListUtils.range(numProcessBatches); try { final CountDownLatch latch = new CountDownLatch(batchIndices.size()); for (int i = 0; i < batchIndices.size(); ++i) { final int batchIdx = batchIndices.getQuick(i); final int evalProcessStartIdx = batchIdx * PROCESSES_PER_JOB; final int evalProcessEndIdx = Math.min((batchIdx + 1) * PROCESSES_PER_JOB, evalProcessDataList.size()); // Start a new job script final String jobScriptFilename = "EvalFeatureTrees_" + batchIdx + ".sh"; executor.submit ( () -> { try ( final PrintWriter writer = new UnixPrintWriter ( new File("/home/" + userName + "/EvalFeatureTreesSnelliusAllGames/" + jobScriptFilename), "UTF-8" ) ) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J EvalFeatureTrees"); writer.println("#SBATCH -p thin"); writer.println("#SBATCH -o /home/" + userName + "/EvalFeatureTreesSnelliusAllGames/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/EvalFeatureTreesSnelliusAllGames/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc // Compute memory and core requirements final int numProcessesThisJob = evalProcessEndIdx - evalProcessStartIdx; final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD); final int jobMemRequestGB; if (exclusive) jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory else jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM); totalCoreHoursRequested.add(CORES_PER_NODE * (MAX_WALL_TIME / 60.0)); writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS); writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc if (exclusive) writer.println("#SBATCH --exclusive"); // load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; for (int processIdx = evalProcessStartIdx; processIdx < evalProcessEndIdx; ++processIdx) { final EvalProcessData evalProcessData = evalProcessDataList.get(processIdx); final List<String> agentStrings = new ArrayList<String>(); final String agentStr1 = StringRoutines.join ( ";", "algorithm=SoftmaxPolicyLogitTree", "policytrees=/" + StringRoutines.join ( "/", "home", userName, "TrainFeaturesSnelliusAllGames", "Out" + StringRoutines.cleanGameName(evalProcessData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(evalProcessData.rulesetName).replaceAll(Pattern.quote("/"), "_"), "CE_Selection_Logit_Tree_" + evalProcessData.treeDepth1 + ".txt" ), "friendly_name=Depth" + evalProcessData.treeDepth1, "greedy=false" ); final String agentStr2 = StringRoutines.join ( ";", "algorithm=SoftmaxPolicyLogitTree", "policytrees=/" + StringRoutines.join ( "/", "home", userName, "TrainFeaturesSnelliusAllGames", "Out" + StringRoutines.cleanGameName(evalProcessData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(evalProcessData.rulesetName).replaceAll(Pattern.quote("/"), "_"), "CE_Selection_Logit_Tree_" + evalProcessData.treeDepth2 + ".txt" ), "friendly_name=Depth" + evalProcessData.treeDepth2, "greedy=false" ); while (agentStrings.size() < evalProcessData.numPlayers) { agentStrings.add(StringRoutines.quote(agentStr1)); if (agentStrings.size() < evalProcessData.numPlayers) agentStrings.add(StringRoutines.quote(agentStr2)); } // Write Java call for this process String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/EvalFeatureTreesSnelliusAllGames/Ludii.jar"), "--eval-agents", "--game", StringRoutines.quote(evalProcessData.gameName), "--ruleset", StringRoutines.quote(evalProcessData.rulesetName), "-n " + NUM_TRIALS, "--thinking-time 1", "--agents", StringRoutines.join(" ", agentStrings), "--warming-up-secs", String.valueOf(0), "--game-length-cap", String.valueOf(1000), "--out-dir", StringRoutines.quote ( "/home/" + userName + "/EvalFeatureTreesSnelliusAllGames/Out" + StringRoutines.cleanGameName(evalProcessData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(evalProcessData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/" + evalProcessData.treeDepth1 + "_vs_" + evalProcessData.treeDepth2 ), "--output-summary", "--output-alpha-rank-data", "--max-wall-time", String.valueOf(MAX_WALL_TIME), ">", "/home/" + userName + "/EvalFeatureTreesSnelliusAllGames/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } ); } latch.await(); } catch (final Exception e) { e.printStackTrace(); } executor.shutdown(); final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File("/home/" + userName + "/EvalFeatureTreesSnelliusAllGames/SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } System.out.println("Total core hours requested = " + totalCoreHoursRequested.doubleValue()); } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String rulesetName; public final int numPlayers; /** * Constructor * @param gameName * @param rulesetName * @param numPlayers */ public ProcessData(final String gameName, final String rulesetName, final int numPlayers) { this.gameName = gameName; this.rulesetName = rulesetName; this.numPlayers = numPlayers; } } /** * Wrapper around data for a single eval process (multiple processes per job) * * @author Dennis Soemers */ private static class EvalProcessData { public final String gameName; public final String rulesetName; public final int numPlayers; public final int treeDepth1; public final int treeDepth2; /** * Constructor * @param gameName * @param rulesetName * @param numPlayers * @param treeDepth1 * @param treeDepth2 */ public EvalProcessData ( final String gameName, final String rulesetName, final int numPlayers, final int treeDepth1, final int treeDepth2 ) { this.gameName = gameName; this.rulesetName = rulesetName; this.numPlayers = numPlayers; this.treeDepth1 = treeDepth1; this.treeDepth2 = treeDepth2; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Generates decision trees and scripts to run on cluster for feature evaluation." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
26,858
31.051313
174
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/GenerateGatingScripts.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.options.Ruleset; import other.GameLoader; import search.mcts.MCTS; import search.minimax.AlphaBetaSearch; /** * Class with main method to automatically generate all the appropriate evaluation * scripts for gating in ExIt on the cluster. * * @author Dennis Soemers */ public class GenerateGatingScripts { /** Memory to assign per CPU, in MB */ private static final String MEM_PER_CPU = "5120"; /** Memory to assign to JVM, in MB */ private static final String JVM_MEM = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 4000; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; // A bunch of dummy AIs, used to check which trainable algorithms are valid in which game private static final AlphaBetaSearch dummyAlphaBeta = new AlphaBetaSearch(); private static final MCTS dummyUCT = MCTS.createUCT(); //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private GenerateGatingScripts() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDirPath = argParse.getValueString("--scripts-dir"); scriptsDirPath = scriptsDirPath.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDirPath.endsWith("/")) scriptsDirPath += "/"; final File scriptsDir = new File(scriptsDirPath); if (!scriptsDir.exists()) scriptsDir.mkdirs(); String trainingOutDirPath = argParse.getValueString("--training-out-dir"); trainingOutDirPath = trainingOutDirPath.replaceAll(Pattern.quote("\\"), "/"); if (!trainingOutDirPath.endsWith("/")) trainingOutDirPath += "/"; String bestAgentsDataDirPath = argParse.getValueString("--best-agents-data-dir"); bestAgentsDataDirPath = bestAgentsDataDirPath.replaceAll(Pattern.quote("\\"), "/"); if (!bestAgentsDataDirPath.endsWith("/")) bestAgentsDataDirPath += "/"; final File bestAgentsDataDir = new File(bestAgentsDataDirPath); if (!bestAgentsDataDir.exists()) bestAgentsDataDir.mkdirs(); final String userName = argParse.getValueString("--user-name"); final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter ( s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) ) ).toArray(String[]::new); // Loop through all the games we have for (final String fullGamePath : allGameNames) { final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), ""); final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud"); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.hasSubgames()) continue; if (game.isStacking()) continue; if (game.hiddenInformation()) continue; final String filepathsGameName = StringRoutines.cleanGameName(gameName); final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), "")); final File rulesetExItOutDir = new File(trainingOutDirPath + filepathsGameName + filepathsRulesetName); if (rulesetExItOutDir.exists() && rulesetExItOutDir.isDirectory()) { final int numPlayers = game.players().count(); final File bestAgentsDataDirForGame = new File(bestAgentsDataDir.getAbsolutePath() + "/" + filepathsGameName + filepathsRulesetName); // Now write our gating experiment scripts final List<String> agentsToEval = new ArrayList<String>(); final List<List<String>> evalFeatureWeightFilepaths = new ArrayList<List<String>>(); final List<String> evalHeuristicsFilepaths = new ArrayList<String>(); final List<List<String>> gateAgentTypes = new ArrayList<List<String>>(); final File[] trainingOutFiles = rulesetExItOutDir.listFiles(); if (trainingOutFiles == null || trainingOutFiles.length == 0) { System.err.println("No training out files for: " + rulesetExItOutDir.getAbsolutePath()); continue; } // Find latest value function and feature files File latestValueFunctionFile = null; int latestValueFunctionCheckpoint = 0; final File[] latestPolicyWeightFiles = new File[numPlayers + 1]; final int[] latestPolicyWeightCheckpoints = new int[numPlayers + 1]; boolean foundPolicyWeights = false; for (final File file : trainingOutFiles) { String filename = file.getName(); // remove extension filename = filename.substring(0, filename.lastIndexOf('.')); final String[] filenameSplit = filename.split(Pattern.quote("_")); if (filename.startsWith("PolicyWeightsCE_P")) { final int checkpoint = Integer.parseInt(filenameSplit[2]); final int p = Integer.parseInt(filenameSplit[1].substring(1)); if (checkpoint > latestPolicyWeightCheckpoints[p]) { foundPolicyWeights = true; latestPolicyWeightFiles[p] = file; latestPolicyWeightCheckpoints[p] = checkpoint; } } else if (filename.startsWith("ValueFunction")) { final int checkpoint = Integer.parseInt(filenameSplit[1]); if (checkpoint > latestValueFunctionCheckpoint) { latestValueFunctionFile = file; latestValueFunctionCheckpoint = checkpoint; } } } int numMatchups = 0; if (dummyAlphaBeta.supportsGame(game)) { if (latestValueFunctionCheckpoint > 0) { agentsToEval.add("Alpha-Beta"); evalFeatureWeightFilepaths.add(new ArrayList<String>()); evalHeuristicsFilepaths.add(latestValueFunctionFile.getAbsolutePath()); final List<String> gateAgents = new ArrayList<String>(); gateAgents.add("Alpha-Beta"); gateAgents.add("BestAgent"); gateAgentTypes.add(gateAgents); numMatchups += 2; } } if (dummyUCT.supportsGame(game)) { if (foundPolicyWeights) { final List<String> policyWeightFiles = new ArrayList<String>(); for (int p = 1; p < latestPolicyWeightFiles.length; ++p) { policyWeightFiles.add(latestPolicyWeightFiles[p].toString()); } agentsToEval.add("BiasedMCTS"); evalFeatureWeightFilepaths.add(policyWeightFiles); evalHeuristicsFilepaths.add(null); List<String> gateAgents = new ArrayList<String>(); if (new File(bestAgentsDataDirForGame.getAbsolutePath() + "/BestFeatures.txt").exists()) { gateAgents.add("BiasedMCTS"); numMatchups += 1; } gateAgents.add("BestAgent"); numMatchups += 1; gateAgentTypes.add(gateAgents); agentsToEval.add("BiasedMCTSUniformPlayouts"); evalFeatureWeightFilepaths.add(policyWeightFiles); evalHeuristicsFilepaths.add(null); gateAgents = new ArrayList<String>(); if (new File(bestAgentsDataDirForGame.getAbsolutePath() + "/BestFeatures.txt").exists()) { gateAgents.add("BiasedMCTS"); numMatchups += 1; } gateAgents.add("BestAgent"); numMatchups += 1; gateAgentTypes.add(gateAgents); } } final List<String> javaCalls = new ArrayList<String>(); for (int evalAgentIdx = 0; evalAgentIdx < agentsToEval.size(); ++evalAgentIdx) { final String agentToEval = agentsToEval.get(evalAgentIdx); final List<String> featureWeightFilepaths = evalFeatureWeightFilepaths.get(evalAgentIdx); final String heuristicFilepath = evalHeuristicsFilepaths.get(evalAgentIdx); final List<String> gateAgents = gateAgentTypes.get(evalAgentIdx); for (final String gateAgent : gateAgents) { String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/Gating/Ludii.jar"), "--eval-gate", "--game", StringRoutines.quote(gameName + ".lud"), "--ruleset", StringRoutines.quote(fullRulesetName), "--eval-agent", StringRoutines.quote(agentToEval), "-n 70", "--game-length-cap 800", "--thinking-time 1", "--best-agents-data-dir", StringRoutines.quote(bestAgentsDataDirForGame.getAbsolutePath()), "--gate-agent-type", gateAgent, "--max-wall-time", "" + Math.max(1000, (MAX_WALL_TIME / numMatchups)) ); if (featureWeightFilepaths.size() > 0) javaCall += " --eval-feature-weights-filepaths " + StringRoutines.join(" ", featureWeightFilepaths); if (heuristicFilepath != null) javaCall += " --eval-heuristics-filepath " + heuristicFilepath; javaCalls.add(javaCall); } } final String jobScriptFilename = "Gating_" + filepathsGameName + filepathsRulesetName + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "/" + jobScriptFilename), "UTF-8")) { writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J Gating_" + filepathsGameName + filepathsRulesetName); writer.println("#SBATCH -o /work/" + userName + "/Gating/Out" + filepathsGameName + filepathsRulesetName + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/Gating/Err" + filepathsGameName + filepathsRulesetName + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); for (final String javaCall : javaCalls) { writer.println(javaCall); } jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "/SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Generates gating scripts for cluster to evaluate which trained agents outperform current default agents." ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--training-out-dir") .help("Base output directory that contains all the results from training.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--best-agents-data-dir") .help("Base directory in which we store data about the best agents per game.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
15,434
32.122318
131
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/IdentifyTopFeaturesSnelliusScripts.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; /** * Script to generate scripts for evaluation of training runs with vs. without * conf intervals on correlations for feature discovery. * * @author Dennis Soemers */ public class IdentifyTopFeaturesSnelliusScripts { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (7GB per process --> give 6GB for heap) */ private static final String JVM_MEM = "6144"; /** Memory to assign per process (in GB) */ private static final int MEM_PER_PROCESS = 8; /** Memory available per node in GB (this is for Thin nodes on Snellius) */ private static final int MEM_PER_NODE = 256; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 224; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 360; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** Number of cores per Java call */ private static final int CORES_PER_PROCESS = 4; /** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_CORES_THRESHOLD = 96; /** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS; /**Number of processes we can put in a single job (on a single node) */ private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS; /** Games we want to run */ private static final String[] GAMES = new String[] { "Alquerque.lud", "Amazons.lud", "ArdRi.lud", "Arimaa.lud", "Ataxx.lud", "Bao Ki Arabu (Zanzibar 1).lud", "Bizingo.lud", "Breakthrough.lud", "Chess.lud", //"Chinese Checkers.lud", "English Draughts.lud", "Fanorona.lud", "Fox and Geese.lud", "Go.lud", "Gomoku.lud", "Gonnect.lud", "Havannah.lud", "Hex.lud", "Knightthrough.lud", "Konane.lud", //"Level Chess.lud", "Lines of Action.lud", "Omega.lud", "Pentalath.lud", "Pretwa.lud", "Reversi.lud", "Royal Game of Ur.lud", "Surakarta.lud", "Shobu.lud", "Tablut.lud", //"Triad.lud", "XII Scripta.lud", "Yavalath.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private IdentifyTopFeaturesSnelliusScripts() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (final String gameName : GAMES) { processDataList.add(new ProcessData(gameName)); } long totalRequestedCoreHours = 0L; int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "IdentifyTopFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J IdentifyTopFeatures"); writer.println("#SBATCH -p thin"); writer.println("#SBATCH -o /home/" + userName + "/IdentifyTopFeatures/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/IdentifyTopFeatures/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc // Compute memory and core requirements final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB); final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD); final int jobMemRequestGB; if (exclusive) jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory else jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM); writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS); writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60)); if (exclusive) writer.println("#SBATCH --exclusive"); // load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")); // Write Java call for this process final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/IdentifyTopFeatures/Ludii.jar"), "--identify-top-features", "--game", StringRoutines.quote("/" + processData.gameName), "--training-out-dir", StringRoutines.quote ( "/home/" + userName + "/TrainFeaturesSnellius4/Out/" + cleanGameName + "_Baseline" ), "--out-dir", StringRoutines.quote ( "/home/" + userName + "/IdentifyTopFeatures/Out/" + cleanGameName ), ">", "/home/" + userName + "/IdentifyTopFeatures/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "2>", "/home/" + userName + "/IdentifyTopFeatures/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } System.out.println("Total requested core hours = " + totalRequestedCoreHours); final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; /** * Constructor * @param gameName */ public ProcessData(final String gameName) { this.gameName = gameName; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating urgency-based feature selection job scripts." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
10,138
29.265672
135
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/IdentifyTopFeaturesSnelliusScriptsAllGames.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.regex.Pattern; import features.spatial.Walk; import game.Game; import gnu.trove.list.array.TDoubleArrayList; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.ArrayUtils; import main.options.Ruleset; import other.GameLoader; import supplementary.experiments.analysis.RulesetConceptsUCT; import utils.RulesetNames; /** * Script to generate scripts for evaluation of training runs with vs. without * conf intervals on correlations for feature discovery. * * @author Dennis Soemers */ public class IdentifyTopFeaturesSnelliusScriptsAllGames { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (7GB per process --> give 6GB for heap) */ private static final String JVM_MEM = "6144"; /** Memory to assign per process (in GB) */ private static final int MEM_PER_PROCESS = 7; /** Memory available per node in GB (this is for Thin nodes on Snellius) */ private static final int MEM_PER_NODE = 256; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 224; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 1445; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** Number of cores per Java call */ private static final int CORES_PER_PROCESS = 4; /** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_CORES_THRESHOLD = 96; /** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */ private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS; /**Number of processes we can put in a single job (on a single node) */ private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS; /** * Games we should skip since they never end anyway (in practice), but do * take a long time. */ private static final String[] SKIP_GAMES = new String[] { "Chinese Checkers.lud", "Li'b al-'Aqil.lud", "Li'b al-Ghashim.lud", "Mini Wars.lud", "Pagade Kayi Ata (Sixteen-handed).lud", "Taikyoku Shogi.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private IdentifyTopFeaturesSnelliusScriptsAllGames() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); final List<String> gameNames = new ArrayList<String>(); final List<String> rulesetNames = new ArrayList<String>(); final TDoubleArrayList expectedTrialDurations = new TDoubleArrayList(); for (final String gameName : allGameNames) { final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String shortGameName = gameNameSplit[gameNameSplit.length - 1]; boolean skipGame = false; for (final String game : SKIP_GAMES) { if (shortGameName.endsWith(game)) { skipGame = true; break; } } if (skipGame) continue; final Game gameNoRuleset = GameLoader.loadGameFromName(gameName); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName, fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.hasSubgames()) continue; if (game.isDeductionPuzzle()) continue; if (game.isSimulationMoveGame()) continue; if (!game.isAlternatingMoveGame()) continue; if (game.isStacking()) continue; if (game.isBoardless()) continue; if (game.hiddenInformation()) continue; if (Walk.allGameRotations(game).length == 0) continue; if (game.players().count() == 0) continue; if (game.isSimultaneousMoveGame()) continue; double expectedTrialDuration = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves"); if (Double.isNaN(expectedTrialDuration)) expectedTrialDuration = Double.MAX_VALUE; gameNames.add("/" + shortGameName); rulesetNames.add(fullRulesetName); expectedTrialDurations.add(expectedTrialDuration); } } // Sort games in decreasing order of expected duration (in moves per trial) // This ensures that we start with the slow games, and that games of similar // durations are likely to end up in the same job script (and therefore run // on the same node at the same time). final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(gameNames.size(), new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { final double delta = expectedTrialDurations.getQuick(i2.intValue()) - expectedTrialDurations.getQuick(i1.intValue()); if (delta < 0.0) return -1; if (delta > 0.0) return 1; return 0; } }); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (int idx : sortedGameIndices) { processDataList.add(new ProcessData(gameNames.get(idx), rulesetNames.get(idx))); } long totalRequestedCoreHours = 0L; int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "IdentifyTopFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J IdentifyTopFeatures"); writer.println("#SBATCH -p thin"); writer.println("#SBATCH -o /home/" + userName + "/IdentifyTopFeatures/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/IdentifyTopFeatures/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc // Compute memory and core requirements final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB); final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD); final int jobMemRequestGB; if (exclusive) jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory else jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM); writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS); writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60)); if (exclusive) writer.println("#SBATCH --exclusive"); // load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); // Write Java call for this process final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/IdentifyTopFeaturesAllGames/Ludii.jar"), "--identify-top-features", "--game", StringRoutines.quote(processData.gameName), "--ruleset", StringRoutines.quote(processData.rulesetName), "--training-out-dir", StringRoutines.quote ( "/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/" ), "--out-dir", StringRoutines.quote ( "/home/" + userName + "/IdentifyTopFeaturesAllGames/Out" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_" + StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_") + "/" ), ">", "/home/" + userName + "/IdentifyTopFeaturesAllGames/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "2>", "/home/" + userName + "/IdentifyTopFeaturesAllGames/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } System.out.println("Total requested core hours = " + totalRequestedCoreHours); final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String rulesetName; /** * Constructor * @param gameName * @param rulesetName */ public ProcessData(final String gameName, final String rulesetName) { this.gameName = gameName; this.rulesetName = rulesetName; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating urgency-based feature selection job scripts." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
14,523
30.573913
135
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/InitBestAgentsData.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import game.Game; import game.equipment.component.Component; import game.equipment.other.Regions; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.grammar.Report; import main.options.Ruleset; import metadata.ai.Ai; import metadata.ai.agents.BestAgent; import metadata.ai.heuristics.Heuristics; import metadata.ai.heuristics.terms.CentreProximity; import metadata.ai.heuristics.terms.ComponentValues; import metadata.ai.heuristics.terms.CornerProximity; import metadata.ai.heuristics.terms.HeuristicTerm; import metadata.ai.heuristics.terms.Influence; import metadata.ai.heuristics.terms.LineCompletionHeuristic; import metadata.ai.heuristics.terms.Material; import metadata.ai.heuristics.terms.MobilitySimple; import metadata.ai.heuristics.terms.NullHeuristic; import metadata.ai.heuristics.terms.OwnRegionsCount; import metadata.ai.heuristics.terms.PlayerRegionsProximity; import metadata.ai.heuristics.terms.PlayerSiteMapCount; import metadata.ai.heuristics.terms.RegionProximity; import metadata.ai.heuristics.terms.Score; import metadata.ai.heuristics.terms.SidesProximity; import metadata.ai.misc.Pair; import other.GameLoader; import search.minimax.AlphaBetaSearch; import utils.DBGameInfo; import utils.analysis.BestBaseAgents; import utils.analysis.BestStartingHeuristics; /** * Script to initialise directory of best-agents data * * @author Dennis Soemers */ public class InitBestAgentsData { /** * Constructor */ private InitBestAgentsData() { // Should not construct } //------------------------------------------------------------------------- /** * Initialises our best agents data directory * @param argParse */ private static void initBestAgentsData(final CommandLineArgParse argParse) { // Load our tables of best base agents and heuristics final BestBaseAgents bestBaseAgents = BestBaseAgents.loadData(); final BestStartingHeuristics bestStartingHeuristics = BestStartingHeuristics.loadData(); // Create the output directory String bestAgentsDataDirPath = argParse.getValueString("--best-agents-data-dir"); bestAgentsDataDirPath = bestAgentsDataDirPath.replaceAll(Pattern.quote("\\"), "/"); if (!bestAgentsDataDirPath.endsWith("/")) bestAgentsDataDirPath += "/"; final File bestAgentsDataDir = new File(bestAgentsDataDirPath); if (!bestAgentsDataDir.exists()) bestAgentsDataDir.mkdirs(); // Find our files of starting heuristics String startingHeuristicsDir = argParse.getValueString("--starting-heuristics-dir"); startingHeuristicsDir = startingHeuristicsDir.replaceAll(Pattern.quote("\\"), "/"); if (!startingHeuristicsDir.endsWith("/")) startingHeuristicsDir += "/"; final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> ( !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) && !(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/")) )).toArray(String[]::new); for (final String fullGamePath : allGameNames) { final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/")); final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), ""); final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud"); final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets()); gameRulesets.add(null); boolean foundRealRuleset = false; for (final Ruleset ruleset : gameRulesets) { final Game game; String fullRulesetName = ""; if (ruleset == null && foundRealRuleset) { // Skip this, don't allow game without ruleset if we do have real implemented ones continue; } else if (ruleset != null && !ruleset.optionSettings().isEmpty()) { fullRulesetName = ruleset.heading(); foundRealRuleset = true; game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName); } else if (ruleset != null && ruleset.optionSettings().isEmpty()) { // Skip empty ruleset continue; } else { game = gameNoRuleset; } if (game.hasSubgames()) continue; final String filepathsGameName = StringRoutines.cleanGameName(gameName); final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), "")); final File bestAgentsDataDirForGame = new File(bestAgentsDataDir.getAbsolutePath() + "/" + filepathsGameName + filepathsRulesetName); initBestAgentsDataDir(bestAgentsDataDirForGame, game, bestBaseAgents, bestStartingHeuristics, DBGameInfo.getUniqueName(game), startingHeuristicsDir); } } } //------------------------------------------------------------------------- /** * Populates a best agents data directory with initial data. * * @param bestAgentsDataDirForGame * @param game * @param bestBaseAgents * @param bestStartingHeuristics * @param gameRulesetName * @param startingHeuristicsDir */ private static void initBestAgentsDataDir ( final File bestAgentsDataDirForGame, final Game game, final BestBaseAgents bestBaseAgents, final BestStartingHeuristics bestStartingHeuristics, final String gameRulesetName, final String startingHeuristicsDir ) { final Ai aiMetadata = game.metadata().ai(); bestAgentsDataDirForGame.mkdirs(); final File bestAgentFile = new File(bestAgentsDataDirForGame.getAbsolutePath() + "/BestAgent.txt"); final File bestFeaturesFile = new File(bestAgentsDataDirForGame.getAbsolutePath() + "/BestFeatures.txt"); final File bestHeuristicsFile = new File(bestAgentsDataDirForGame.getAbsolutePath() + "/BestHeuristics.txt"); final BestBaseAgents.Entry baseAgentEntry = bestBaseAgents.getEntry(gameRulesetName); if (baseAgentEntry != null) { final BestAgent bestAgent = new BestAgent(baseAgentEntry.topAgent()); try (final PrintWriter writer = new PrintWriter(bestAgentFile, "UTF-8")) { writer.println(bestAgent.toString()); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } else if (aiMetadata.agent() != null) { try (final PrintWriter writer = new PrintWriter(bestAgentFile, "UTF-8")) { writer.println(aiMetadata.agent().toString()); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } if (aiMetadata.features() != null) { try (final PrintWriter writer = new PrintWriter(bestFeaturesFile)) { writer.println(aiMetadata.features().toString()); } catch (final FileNotFoundException e) { e.printStackTrace(); } } if (baseAgentEntry != null && baseAgentEntry.topAgent().equals("AlphaBetaMetadata")) { // Take heuristics as we have them in metadata right now if (aiMetadata.heuristics() != null) { try (final PrintWriter writer = new PrintWriter(bestHeuristicsFile)) { writer.println(aiMetadata.heuristics().toString()); } catch (final FileNotFoundException e) { e.printStackTrace(); } } } else if (new AlphaBetaSearch().supportsGame(game)) { // Load our top starting heuristic final BestStartingHeuristics.Entry startingHeuristicEntry = bestStartingHeuristics.getEntry(gameRulesetName); final Regions[] regions = game.equipment().regions(); final List<Regions> staticRegions = game.equipment().computeStaticRegions(); boolean skipCentreProximity = false; boolean skipComponentValues = false; boolean skipCornerProximity = false; boolean skipLineCompletionHeuristic = false; boolean skipMaterial = false; boolean skipMobilitySimple = false; boolean skipNullHeuristic = false; boolean skipInfluence = false; boolean skipOwnRegionCount = false; final boolean[] skipPlayerRegionsProximity = new boolean[game.players().count() + 1]; boolean skipPlayerSiteMapCount = false; final boolean[] skipRegionProximity = new boolean[regions.length]; boolean skipScore = false; boolean skipSidesProximity = false; // We'll always skip proximity to non-static regions for (int i = 0; i < regions.length; ++i) { if (!staticRegions.contains(regions[i])) skipRegionProximity[i] = true; } // And we'll always skip player region proximity for players who don't own any regions for (int p = 1; p <= game.players().count(); ++p) { boolean foundOwned = false; for (final Regions region : staticRegions) { if (region.owner() == p) { foundOwned = true; break; } } if (!foundOwned) skipPlayerRegionsProximity[p] = true; } final List<HeuristicTerm> heuristicTerms = new ArrayList<HeuristicTerm>(); if (startingHeuristicEntry != null) { try { final Heuristics startingHeuristics = (Heuristics)compiler.Compiler.compileObject ( FileHandling.loadTextContentsFromFile ( startingHeuristicsDir + startingHeuristicEntry.topHeuristic() + ".txt" ), "metadata.ai.heuristics.Heuristics", new Report() ); for (final HeuristicTerm term : startingHeuristics.heuristicTerms()) { heuristicTerms.add(term); if (term instanceof CentreProximity) { skipCentreProximity = true; } else if (term instanceof ComponentValues) { skipComponentValues = true; } else if (term instanceof CornerProximity) { skipCornerProximity = true; } else if (term instanceof LineCompletionHeuristic) { skipLineCompletionHeuristic = true; } else if (term instanceof Material) { skipMaterial = true; } else if (term instanceof MobilitySimple) { skipMobilitySimple = true; } else if (term instanceof NullHeuristic) { skipNullHeuristic = true; } else if (term instanceof Influence) { skipInfluence = true; } else if (term instanceof OwnRegionsCount) { skipOwnRegionCount = true; } else if (term instanceof PlayerRegionsProximity) { final PlayerRegionsProximity playerRegionsProximity = (PlayerRegionsProximity) term; skipPlayerRegionsProximity[playerRegionsProximity.regionPlayer()] = true; } else if (term instanceof PlayerSiteMapCount) { skipPlayerSiteMapCount = true; } else if (term instanceof RegionProximity) { final RegionProximity regionProximity = (RegionProximity) term; skipRegionProximity[regionProximity.region()] = true; } else if (term instanceof Score) { skipScore = true; } else if (term instanceof SidesProximity) { skipSidesProximity = true; } else { System.err.println("Did not recognise class for heuristic term: " + term); } } } catch (final IOException e) { e.printStackTrace(); } } // Add 0-weight heuristics for all the unused terms (so we can train them) if (!skipCentreProximity) { if (CentreProximity.isApplicableToGame(game)) heuristicTerms.add(new CentreProximity(null, Float.valueOf(1.f), zeroWeightPairsArray(game))); } if (!skipComponentValues) { if (ComponentValues.isApplicableToGame(game)) heuristicTerms.add(new ComponentValues(null, Float.valueOf(1.f), zeroWeightPairsArray(game), null)); } if (!skipCornerProximity) { if (CornerProximity.isApplicableToGame(game)) heuristicTerms.add(new CornerProximity(null, Float.valueOf(1.f), zeroWeightPairsArray(game))); } if (!skipLineCompletionHeuristic) { if (LineCompletionHeuristic.isApplicableToGame(game)) heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(0.f), null)); } if (!skipMaterial) { if (Material.isApplicableToGame(game)) heuristicTerms.add(new Material(null, Float.valueOf(1.f), zeroWeightPairsArray(game), null)); } if (!skipMobilitySimple) { if (MobilitySimple.isApplicableToGame(game)) heuristicTerms.add(new MobilitySimple(null, Float.valueOf(0.f))); } if (!skipNullHeuristic) { if (NullHeuristic.isApplicableToGame(game)) heuristicTerms.add(new NullHeuristic()); } if (!skipInfluence) { if (Influence.isApplicableToGame(game)) heuristicTerms.add(new Influence(null, Float.valueOf(0.f))); } if (!skipOwnRegionCount) { if (OwnRegionsCount.isApplicableToGame(game)) heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(0.f))); } for (int p = 1; p <= game.players().count(); ++p) { if (!skipPlayerRegionsProximity[p]) { if (PlayerRegionsProximity.isApplicableToGame(game)) heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(1.f), Integer.valueOf(p), zeroWeightPairsArray(game))); } } if (!skipPlayerSiteMapCount) { if (PlayerSiteMapCount.isApplicableToGame(game)) heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(0.f))); } for (int i = 0; i < regions.length; ++i) { if (!skipRegionProximity[i]) heuristicTerms.add(new RegionProximity(null, Float.valueOf(1.f), Integer.valueOf(i), zeroWeightPairsArray(game))); } if (!skipScore) { if (Score.isApplicableToGame(game)) heuristicTerms.add(new Score(null, Float.valueOf(0.f))); } if (!skipSidesProximity) { if (SidesProximity.isApplicableToGame(game)) heuristicTerms.add(new SidesProximity(null, Float.valueOf(1.f), zeroWeightPairsArray(game))); } try (final PrintWriter writer = new PrintWriter(bestHeuristicsFile)) { writer.println(new Heuristics(heuristicTerms.toArray(new HeuristicTerm[heuristicTerms.size()])).toString()); } catch (final FileNotFoundException e) { e.printStackTrace(); } } } /** * Helper method to generate an array of Pairs for 0-piece-weight heuristics * @param game * @return */ private static Pair[] zeroWeightPairsArray(final Game game) { final Component[] components = game.equipment().components(); final List<Pair> pairs = new ArrayList<Pair>(components.length); for (final Component comp : components) { if (comp != null) pairs.add(new Pair(comp.name(), Float.valueOf(0.f))); } return pairs.toArray(new Pair[pairs.size()]); } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Initialises a directory with best-agents data." ); argParse.addOption(new ArgOption() .withNames("--best-agents-data-dir") .help("Base directory in which we want to store data about the best agents per game.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--starting-heuristics-dir") .help("Directory with our starting heuristic files.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; initBestAgentsData(argParse); } //------------------------------------------------------------------------- }
16,436
30.368321
153
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/OptimLudusHeuristicsScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Script to generate scripts for heuristic optimisation runs for various * Ludus Latrunculorum rulesets. * * @author Dennis Soemers */ public class OptimLudusHeuristicsScriptsGen { /** Memory to assign per CPU, in MB */ private static final String MEM_PER_CPU = "5120"; /** Memory to assign to JVM, in MB */ private static final String JVM_MEM = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 3600; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Games and rulesets we want to use */ private static final String[][] GAMES_RULESETS = new String[][] { {"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Seega Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x18 (Seega Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x18 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules More Pieces) (Suggested)"}, }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private OptimLudusHeuristicsScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); for (final String[] gameRulesetArray : GAMES_RULESETS) { final Game game = GameLoader.loadGameFromName(gameRulesetArray[0], gameRulesetArray[1]); if (game == null) System.err.println("ERROR! Failed to compile " + gameRulesetArray[0] + ", " + gameRulesetArray[1]); final String filepathsGameName = StringRoutines.cleanGameName(gameRulesetArray[0].replaceAll(Pattern.quote("/"), "")); final String filepathsRulesetName = StringRoutines.cleanRulesetName(gameRulesetArray[1].replaceAll(Pattern.quote("Ruleset/"), "")); final String jobScriptFilename = "EvolOptimHeuristics" + filepathsGameName + filepathsRulesetName + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J EvolOptimHeuristics_" + filepathsGameName + filepathsRulesetName); writer.println("#SBATCH -o /work/" + userName + "/EvolOptimHeuristics/Out" + filepathsGameName + filepathsRulesetName + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/EvolOptimHeuristics/Err" + filepathsGameName + filepathsRulesetName + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/EvolOptimHeuristics/Ludii.jar"), "--evol-optim-heuristics", "--game", StringRoutines.quote(gameRulesetArray[0]), "--ruleset", StringRoutines.quote(gameRulesetArray[1]), "--skip-heuristics", StringRoutines.quote("LineCompletionHeuristic"), "--out-dir", StringRoutines.quote ( "/work/" + userName + "/EvolOptimHeuristics/" + filepathsGameName + filepathsRulesetName + "/" ) ); writer.println(javaCall); jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Generates heuristic optimisation scripts for Ludus Latrunculorum / Poprad Game rulesets" ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,493
33.388664
134
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/TrainLudusScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Script to generate scripts for ExIt training runs for various * Ludus Latrunculorum rulesets. * * @author Dennis Soemers */ public class TrainLudusScriptsGen { /** Memory to assign per CPU, in MB */ private static final String MEM_PER_CPU = "5120"; /** Memory to assign to JVM, in MB */ private static final String JVM_MEM = "4096"; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 1800; /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Games and rulesets we want to use */ private static final String[][] GAMES_RULESETS = new String[][] { {"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Kharebga Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Seega Rules) (Suggested)"}, {"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Seega Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x18 (Seega Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x18 (Kharebga Rules) (Suggested)"}, {"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules More Pieces) (Suggested)"}, }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private TrainLudusScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); for (final String[] gameRulesetArray : GAMES_RULESETS) { final Game game = GameLoader.loadGameFromName(gameRulesetArray[0], gameRulesetArray[1]); if (game == null) System.err.println("ERROR! Failed to compile " + gameRulesetArray[0] + ", " + gameRulesetArray[1]); final String filepathsGameName = StringRoutines.cleanGameName(gameRulesetArray[0].replaceAll(Pattern.quote("/"), "")); final String filepathsRulesetName = StringRoutines.cleanRulesetName(gameRulesetArray[1].replaceAll(Pattern.quote("Ruleset/"), "")); final String jobScriptFilename = "TrainLudus" + filepathsGameName + filepathsRulesetName + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/usr/local_rwth/bin/zsh"); writer.println("#SBATCH -J TrainLudus_" + filepathsGameName + filepathsRulesetName); writer.println("#SBATCH -o /work/" + userName + "/TrainLudus/Out" + filepathsGameName + filepathsRulesetName + "_%J.out"); writer.println("#SBATCH -e /work/" + userName + "/TrainLudus/Err" + filepathsGameName + filepathsRulesetName + "_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU); writer.println("#SBATCH -A " + argParse.getValueString("--project")); writer.println("unset JAVA_TOOL_OPTIONS"); final String javaCall = StringRoutines.join ( " ", "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/TrainLudus/Ludii.jar"), "--expert-iteration", "--game", StringRoutines.quote(gameRulesetArray[0]), "--ruleset", StringRoutines.quote(gameRulesetArray[1]), "--out-dir", StringRoutines.quote ( "/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/" ), "-n 200", "--thinking-time 1.5", "--is-episode-durations", "--prioritized-experience-replay", "--wis", "--handle-aliasing", "--expert-ai PVTS", "--init-value-func-dir", StringRoutines.quote ( "/work/" + userName + "/EvolOptimHeuristics/" + filepathsGameName + filepathsRulesetName + "/" ), "--checkpoint-freq 1", "--no-logging", "--max-wall-time", String.valueOf(1500) ); writer.println(javaCall); jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Generates heuristic optimisation scripts for Ludus Latrunculorum / Poprad Game rulesets" ); argParse.addOption(new ArgOption() .withNames("--project") .help("Project for which to submit the job on cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,831
32.454545
134
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/TrainedFeaturesAndDecisionTreesPlayoutTimingScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Generates job scripts to submit to SLURM for running timings of * playouts for a variety of trained feature sets. * * Script generation currently made for Snellius cluster (not RWTH Aachen) * * @author Dennis Soemers */ public class TrainedFeaturesAndDecisionTreesPlayoutTimingScriptsGen { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */ private static final String JVM_MEM = "4096"; /** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */ private static final int MAX_REQUEST_MEM = 224; /** Number of cores per node (this is for Thin nodes on Snellius) */ private static final int CORES_PER_NODE = 128; /** JVM warming up time (in seconds) */ private static final int WARMUP_TIME = 60; /** Time over which we measure playouts */ private static final int MEASURE_TIME = 600; /** Max wall time (in minutes) (warming up time + measure time + some safety margin) */ private static final int MAX_WALL_TIME = 40; /** We get 128 cores per job; we'll give 2 cores per process */ private static final int PROCESSES_PER_JOB = 64; /** Games we want to run */ private static final String[] GAMES = new String[] { "Alquerque.lud", "Amazons.lud", "ArdRi.lud", "Arimaa.lud", "Ataxx.lud", "Bao Ki Arabu (Zanzibar 1).lud", "Bizingo.lud", "Breakthrough.lud", "Chess.lud", "English Draughts.lud", "Fanorona.lud", "Fox and Geese.lud", "Go.lud", "Gomoku.lud", "Gonnect.lud", "Havannah.lud", "Hex.lud", "Knightthrough.lud", "Konane.lud", "Lines of Action.lud", "Omega.lud", "Pentalath.lud", "Pretwa.lud", "Reversi.lud", "Royal Game of Ur.lud", "Shobu.lud", "Surakarta.lud", "Tablut.lud", "XII Scripta.lud", "Yavalath.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private TrainedFeaturesAndDecisionTreesPlayoutTimingScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (final String gameName : GAMES) { // Sanity check: make sure game with this name loads correctly System.out.println("gameName = " + gameName); final Game game = GameLoader.loadGameFromName(gameName); if (game == null) throw new IllegalArgumentException("Cannot load game: " + gameName); for (final String featuresToUse : new String[]{"Tree1", "Tree2", "Tree3", "Tree4", "Tree5", "Tree10", "FullPolicy"}) { processDataList.add(new ProcessData(gameName, featuresToUse)); } } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "BenchmarkTrainedFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J BenchmarkTrainedFeaturesAndDecisionTrees"); writer.println("#SBATCH -o /home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE); writer.println("#SBATCH --mem=" + MAX_REQUEST_MEM + "G"); writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work // Load Java modules writer.println("module load 2021"); writer.println("module load Java/11.0.2"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); String featuresToUseStr = null; if (processData.featuresToUse.equals("FullPolicy")) { featuresToUseStr = StringRoutines.quote ( "latest-trained-" + StringRoutines.join ( "/", "", "home", userName, "TrainFeaturesSnellius4", "Out", StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_Baseline" ) ); } else if (processData.featuresToUse.startsWith("Tree")) { featuresToUseStr = StringRoutines.quote ( "decision-trees-" + StringRoutines.join ( "/", "", "home", userName, "TrainFeaturesSnellius4", "Out", "Trees", StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")), "IQRTree_Playout_" + processData.featuresToUse.substring("Tree".length()) + ".txt" ) ); } else { System.err.println("Cannot recognise features to use: " + processData.featuresToUse); } // Write Java call for this process final String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific core to each process "-c", StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Ludii.jar"), "--time-playouts", "--warming-up-secs", String.valueOf(WARMUP_TIME), "--measure-secs", String.valueOf(MEASURE_TIME), "--game-names", StringRoutines.quote("/" + processData.gameName), "--export-csv", StringRoutines.quote ( "/home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Out/" + StringRoutines.join ( "_", StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")), processData.featuresToUse ) + ".csv" ), //"--suppress-prints", "--features-to-use", featuresToUseStr, ">", "/home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "2>", "/home/" + userName + "/BenchmarkTrainedFeaturesAndDecisionTrees/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String featuresToUse; /** * Constructor * @param gameName * @param featuresToUse */ public ProcessData(final String gameName, final String featuresToUse) { this.gameName = gameName; this.featuresToUse = featuresToUse; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating timing job scripts for playouts with trained feature sets and decision trees." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
11,083
29.201635
126
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/TrainedFeaturesPlayoutTimingScriptsGen.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Generates job scripts to submit to SLURM for running timings of * playouts for a variety of trained feature sets. * * Script generation currently made for Cartesius cluster (not RWTH Aachen) * * @author Dennis Soemers */ public class TrainedFeaturesPlayoutTimingScriptsGen { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */ private static final String JVM_MEM = "4096"; /** JVM warming up time (in seconds) */ private static final int WARMUP_TIME = 60; /** Time over which we measure playouts */ private static final int MEASURE_TIME = 600; /** Max wall time (in minutes) (warming up time + measure time + some safety margin) */ private static final int MAX_WALL_TIME = 40; /** We get 24 cores per job; we'll give 2 cores per process */ private static final int PROCESSES_PER_JOB = 12; /** Only run on the Haswell nodes */ private static final String PROCESSOR = "haswell"; /** Games we want to run */ private static final String[] GAMES = new String[] { "Alquerque.lud", "Amazons.lud", "ArdRi.lud", "Arimaa.lud", "Ataxx.lud", "Bao Ki Arabu (Zanzibar 1).lud", "Bizingo.lud", "Breakthrough.lud", "Chess.lud", "Chinese Checkers.lud", "English Draughts.lud", "Fanorona.lud", "Fox and Geese.lud", "Go.lud", "Gomoku.lud", "Gonnect.lud", "Havannah.lud", "Hex.lud", "Kensington.lud", "Knightthrough.lud", "Konane.lud", "Level Chess.lud", "Lines of Action.lud", "Pentalath.lud", "Pretwa.lud", "Reversi.lud", "Royal Game of Ur.lud", "Surakarta.lud", "Shobu.lud", "Tablut.lud", "Triad.lud", "XII Scripta.lud", "Yavalath.lud" }; /** Different feature set implementations we want to benchmark */ private static final String[] FEATURE_SETS = new String[] { "JITSPatterNet", "SPatterNet", "Legacy", "Naive" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private TrainedFeaturesPlayoutTimingScriptsGen() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (final String gameName : GAMES) { // Sanity check: make sure game with this name loads correctly System.out.println("gameName = " + gameName); final Game game = GameLoader.loadGameFromName(gameName); if (game == null) throw new IllegalArgumentException("Cannot load game: " + gameName); for (final String featureSet : FEATURE_SETS) { for (final String featuresToUse : new String[]{"latest-trained-uniform-", "latest-trained-"}) { processDataList.add(new ProcessData(gameName, featuresToUse, featureSet)); } } } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "BenchmarkTrainedFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J BenchmarkTrainedFeatures"); writer.println("#SBATCH -o /home/" + userName + "/BenchmarkTrainedFeatures/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/BenchmarkTrainedFeatures/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --constraint=" + PROCESSOR); // load Java modules writer.println("module load 2020"); writer.println("module load Java/1.8.0_261"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); // Write Java call for this process final String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific core to each process "-c", StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/BenchmarkTrainedFeatures/Ludii.jar"), "--time-playouts", "--warming-up-secs", String.valueOf(WARMUP_TIME), "--measure-secs", String.valueOf(MEASURE_TIME), "--game-names", StringRoutines.quote("/" + processData.gameName), "--export-csv", StringRoutines.quote ( "/home/" + userName + "/BenchmarkTrainedFeatures/Out/" + StringRoutines.join ( "_", StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")), processData.featuresToUse, processData.featureSet ) + ".csv" ), //"--suppress-prints", "--features-to-use", StringRoutines.quote ( processData.featuresToUse + StringRoutines.join ( "/", "", "home", userName, "TrainFeatures", "Out", StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) ) ), "--feature-set-type", processData.featureSet, ">", "/home/" + userName + "/BenchmarkFeatures/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final String featuresToUse; public final String featureSet; /** * Constructor * @param gameName * @param featuresToUse * @param featureSet */ public ProcessData(final String gameName, final String featuresToUse, final String featureSet) { this.gameName = gameName; this.featuresToUse = featuresToUse; this.featureSet = featureSet; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating timing job scripts for playouts with atomic feature sets." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
10,039
27.603989
118
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/TrainingScriptsGenCorrConfIntervals.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Generates job scripts to submit to SLURM for running ExIt training runs * * Script generation currently made for Cartesius cluster (not RWTH Aachen) * * @author Dennis Soemers */ public class TrainingScriptsGenCorrConfIntervals { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */ private static final String JVM_MEM = "4096"; /** Max number of self-play trials */ private static final int MAX_SELFPLAY_TRIALS = 200; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 1440; /** We get 24 cores per job; we'll give 2 cores per process */ private static final int PROCESSES_PER_JOB = 12; /** Only run on the Haswell nodes */ private static final String PROCESSOR = "haswell"; /** Games we want to run */ private static final String[] GAMES = new String[] { "Amazons.lud", "ArdRi.lud", "Breakthrough.lud", "English Draughts.lud", "Fanorona.lud", "Gomoku.lud", "Havannah.lud", "Hex.lud", "Knightthrough.lud", "Reversi.lud", "Yavalath.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private TrainingScriptsGenCorrConfIntervals() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (final String gameName : GAMES) { // Sanity check: make sure game with this name loads correctly System.out.println("gameName = " + gameName); final Game game = GameLoader.loadGameFromName(gameName); if (game == null) throw new IllegalArgumentException("Cannot load game: " + gameName); processDataList.add(new ProcessData(gameName, false)); processDataList.add(new ProcessData(gameName, true)); } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J TrainFeatures"); writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --constraint=" + PROCESSOR); // load Java modules writer.println("module load 2020"); writer.println("module load Java/1.8.0_261"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); // Write Java call for this process String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific core to each process "-c", StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/TrainFeaturesCorrConfIntervals/Ludii.jar"), "--expert-iteration", "--game", StringRoutines.quote("/" + processData.gameName), "-n", String.valueOf(MAX_SELFPLAY_TRIALS), "--game-length-cap 1000", "--thinking-time 1", "--is-episode-durations", "--prioritized-experience-replay", "--wis", "--handle-aliasing", "--playout-features-epsilon 0.5", "--no-value-learning", "--checkpoint-freq 5", "--num-agent-threads 2", "--num-feature-discovery-threads 2", "--out-dir", StringRoutines.quote ( "/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + (processData.noConfInterval ? "_Without" : "_With") + "/" ), "--no-logging", "--max-wall-time", String.valueOf(MAX_WALL_TIME) ); if (processData.noConfInterval) javaCall += " --critical-value-corr-conf 0"; javaCall += " " + StringRoutines.join ( " ", ">", "/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final boolean noConfInterval; /** * Constructor * @param gameName * @param noConfInterval */ public ProcessData(final String gameName, final boolean noConfInterval) { this.gameName = gameName; this.noConfInterval = noConfInterval; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating training job scripts." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,945
28.140065
157
java
Ludii
Ludii-master/Player/src/supplementary/experiments/scripts/TrainingScriptsGenFinalStatesBuffers.java
package supplementary.experiments.scripts; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; /** * Generates job scripts to submit to SLURM for running ExIt training runs * * Script generation currently made for Cartesius cluster (not RWTH Aachen) * * @author Dennis Soemers */ public class TrainingScriptsGenFinalStatesBuffers { /** Don't submit more than this number of jobs at a single time */ private static final int MAX_JOBS_PER_BATCH = 800; /** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */ private static final String JVM_MEM = "4096"; /** Max number of self-play trials */ private static final int MAX_SELFPLAY_TRIALS = 200; /** Max wall time (in minutes) */ private static final int MAX_WALL_TIME = 1440; /** We get 24 cores per job; we'll give 2 cores per process */ private static final int PROCESSES_PER_JOB = 12; /** Only run on the Haswell nodes */ private static final String PROCESSOR = "haswell"; /** Games we want to run */ private static final String[] GAMES = new String[] { "Amazons.lud", "ArdRi.lud", "Breakthrough.lud", "English Draughts.lud", "Fanorona.lud", "Gomoku.lud", "Havannah.lud", "Hex.lud", "Knightthrough.lud", "Reversi.lud", "Yavalath.lud" }; //------------------------------------------------------------------------- /** * Constructor (don't need this) */ private TrainingScriptsGenFinalStatesBuffers() { // Do nothing } //------------------------------------------------------------------------- /** * Generates our scripts * @param argParse */ private static void generateScripts(final CommandLineArgParse argParse) { final List<String> jobScriptNames = new ArrayList<String>(); String scriptsDir = argParse.getValueString("--scripts-dir"); scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/"); if (!scriptsDir.endsWith("/")) scriptsDir += "/"; final String userName = argParse.getValueString("--user-name"); // First create list with data for every process we want to run final List<ProcessData> processDataList = new ArrayList<ProcessData>(); for (final String gameName : GAMES) { // Sanity check: make sure game with this name loads correctly System.out.println("gameName = " + gameName); final Game game = GameLoader.loadGameFromName(gameName); if (game == null) throw new IllegalArgumentException("Cannot load game: " + gameName); processDataList.add(new ProcessData(gameName, false)); processDataList.add(new ProcessData(gameName, true)); } int processIdx = 0; while (processIdx < processDataList.size()) { // Start a new job script final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh"; try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8")) { writer.println("#!/bin/bash"); writer.println("#SBATCH -J TrainFeatures"); writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/Out_%J.out"); writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/Err_%J.err"); writer.println("#SBATCH -t " + MAX_WALL_TIME); writer.println("#SBATCH --constraint=" + PROCESSOR); // load Java modules writer.println("module load 2020"); writer.println("module load Java/1.8.0_261"); // Put up to PROCESSES_PER_JOB processes in this job int numJobProcesses = 0; while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size()) { final ProcessData processData = processDataList.get(processIdx); // Write Java call for this process String javaCall = StringRoutines.join ( " ", "taskset", // Assign specific core to each process "-c", StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)), "java", "-Xms" + JVM_MEM + "M", "-Xmx" + JVM_MEM + "M", "-XX:+HeapDumpOnOutOfMemoryError", "-da", "-dsa", "-XX:+UseStringDeduplication", "-jar", StringRoutines.quote("/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Ludii.jar"), "--expert-iteration", "--game", StringRoutines.quote("/" + processData.gameName), "-n", String.valueOf(MAX_SELFPLAY_TRIALS), "--game-length-cap 1000", "--thinking-time 1", "--is-episode-durations", "--prioritized-experience-replay", "--wis", "--handle-aliasing", "--playout-features-epsilon 0.5", "--no-value-learning", "--checkpoint-freq 5", "--num-agent-threads 2", "--num-feature-discovery-threads 2", "--out-dir", StringRoutines.quote ( "/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + (processData.finalStatesBuffers ? "_With" : "_Without") + "/" ), "--no-logging", "--max-wall-time", String.valueOf(MAX_WALL_TIME) ); if (processData.finalStatesBuffers) javaCall += " --final-states-buffers"; javaCall += " " + StringRoutines.join ( " ", ">", "/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out", "&" // Run processes in parallel ); writer.println(javaCall); ++processIdx; ++numJobProcesses; } writer.println("wait"); // Wait for all the parallel processes to finish jobScriptNames.add(jobScriptFilename); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } final List<List<String>> jobScriptsLists = new ArrayList<List<String>>(); List<String> remainingJobScriptNames = jobScriptNames; while (remainingJobScriptNames.size() > 0) { if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH) { final List<String> subList = new ArrayList<String>(); for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i) { subList.add(remainingJobScriptNames.get(i)); } jobScriptsLists.add(subList); remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size()); } else { jobScriptsLists.add(remainingJobScriptNames); remainingJobScriptNames = new ArrayList<String>(); } } for (int i = 0; i < jobScriptsLists.size(); ++i) { try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8")) { for (final String jobScriptName : jobScriptsLists.get(i)) { writer.println("sbatch " + jobScriptName); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Wrapper around data for a single process (multiple processes per job) * * @author Dennis Soemers */ private static class ProcessData { public final String gameName; public final boolean finalStatesBuffers; /** * Constructor * @param gameName * @param finalStatesBuffers */ public ProcessData(final String gameName, final boolean finalStatesBuffers) { this.gameName = gameName; this.finalStatesBuffers = finalStatesBuffers; } } //------------------------------------------------------------------------- /** * Main method to generate all our scripts * @param args */ public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Creating training job scripts." ); argParse.addOption(new ArgOption() .withNames("--user-name") .help("Username on the cluster.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); argParse.addOption(new ArgOption() .withNames("--scripts-dir") .help("Directory in which to store generated scripts.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; generateScripts(argParse); } //------------------------------------------------------------------------- }
8,974
28.234528
161
java
Ludii
Ludii-master/Player/src/supplementary/experiments/speed/BreadthFirstExpansion.java
package supplementary.experiments.speed; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.collections.FastArrayList; import other.GameLoader; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Experiment where we measure how far we can get in a certain amount of time in a * complete breadth-first tree expansion, storing a copy of every game state in memory * in the process. * * @author Dennis Soemers */ public class BreadthFirstExpansion { /** * Names of the games to play. Each should end with ".lud". * Use "all" to run all games we can find. Runs all games by default */ private List<String> gameNames; /** List of game directories to exclude from experiment */ private List<String> excludeDirs; /** Options to tweak game (variant, rules, board, etc.) */ private List<String> gameOptions; /** Number of seconds of warming up (per game) */ private int warmingUpSecs; /** Number of seconds over which we create breadth-first tree expansion */ private int measureSecs; /** * Extra seconds we want to wait after measureSecs have passed. * Will still keep the tree in memory. * Useful for creating a memory snapshot during this time in profiler. */ private int postMeasureWaitSecs; //------------------------------------------------------------------------- /** * Constructor */ private BreadthFirstExpansion() { // Nothing to do here } //------------------------------------------------------------------------- /** * Start the experiment */ public void startExperiment() { // Gather all the game names final List<String> gameNamesToTest = new ArrayList<String>(); if (gameNames.get(0).equalsIgnoreCase("all")) { // lowercase all the exclude dirs, makes tests easier for (int i = 0; i < excludeDirs.size(); ++i) { excludeDirs.set(i, excludeDirs.get(i).toLowerCase()); } final String[] allGameNames = FileHandling.listGames(); for (final String gameName : allGameNames) { final String name = gameName.replaceAll(Pattern.quote("\\"), "/"); final String[] nameParts = name.split(Pattern.quote("/")); boolean exclude = false; for (final String part : nameParts) { if ( excludeDirs.contains(part.toLowerCase()) || part.equals("plex") || part.equals("bad") || part.equals("bad_playout") || part.equals("wip") || part.equals("test") ) { exclude = true; break; } } if (!exclude) { gameNamesToTest.add(name); } } } else { final String[] allGameNames = FileHandling.listGames(); for (String gameName : gameNames) { gameName = gameName.replaceAll(Pattern.quote("\\"), "/"); for (String name : allGameNames) { name = name.replaceAll(Pattern.quote("\\"), "/"); if (name.endsWith(gameName)) { gameNamesToTest.add(name); } } } } System.out.println("Starting timings for games: " + gameNamesToTest); System.out.println(); System.out.println("Using " + warmingUpSecs + " warming-up seconds per game."); System.out.println("Measuring results over " + measureSecs + " seconds per game."); System.out.println(); for (final String gameName : gameNamesToTest) { final Game game = GameLoader.loadGameFromName(gameName, gameOptions); final Trial startTrial = new Trial(game); final Context startContext = new Context(game, startTrial); if (!game.isAlternatingMoveGame()) { System.err.println("WARNING: did not properly implement this for non-alternating-move games."); } // Warming up final List<Context> allContexts = new ArrayList<Context>(); game.start(startContext); allContexts.add(new Context(startContext)); int allContextsIdx = 0; long stopAt = 0L; long start = System.nanoTime(); double abortAt = start + warmingUpSecs * 1000000000.0; while (stopAt < abortAt || allContextsIdx >= allContexts.size()) { final Context c = allContexts.get(allContextsIdx++); final FastArrayList<Move> legalMoves = game.moves(c).moves(); for (final Move m : legalMoves) { final Context copyContext = new Context(c); game.apply(copyContext, m); allContexts.add(copyContext); } stopAt = System.nanoTime(); } allContexts.clear(); System.gc(); allContexts.add(new Context(startContext)); allContextsIdx = 0; // The Test stopAt = 0L; start = System.nanoTime(); abortAt = start + measureSecs * 1000000000.0; while (stopAt < abortAt || allContextsIdx >= allContexts.size()) { final Context c = allContexts.get(allContextsIdx++); final FastArrayList<Move> legalMoves = game.moves(c).moves(); for (final Move m : legalMoves) { final Context copyContext = new Context(c); game.apply(copyContext, m); allContexts.add(copyContext); } stopAt = System.nanoTime(); } final double secs = (stopAt - start) / 1000000000.0; final double rate = (allContexts.size() / secs); System.out.println(game.name() + "\t-\t" + rate + " nodes/s"); if (postMeasureWaitSecs > 0) { System.out.println("Waiting for " + postMeasureWaitSecs + " seconds, create memory snapshot now!"); try { Thread.sleep(1000L * postMeasureWaitSecs); } catch (final InterruptedException e) { e.printStackTrace(); } } } } //------------------------------------------------------------------------- /** * Main method * @param args */ @SuppressWarnings("unchecked") public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Measure playouts per second for one or more games." ); argParse.addOption(new ArgOption() .withNames("--games") .help("Names of the games to play. Each should end with \".lud\". " + "Use \"all\" to run all games we can find. " + "Runs all games by default.") .withDefault(Arrays.asList("all")) .withNumVals("+") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--exclude-dirs") .help("List of game directories to exclude from experiment.") .withDefault(Arrays.asList("puzzle")) .withNumVals("*") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--game-options") .help("Game Options to load.") .withDefault(new ArrayList<String>(0)) .withNumVals("*") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--warming-up-secs", "--warming-up") .help("Number of seconds of warming up (per game).") .withDefault(Integer.valueOf(10)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--measure-secs") .help("Number of seconds over which we measure playouts (per game).") .withDefault(Integer.valueOf(30)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--post-measure-wait-secs") .help("Extra seconds we want to wait after measureSecs have passed.") .withDefault(Integer.valueOf(0)) .withNumVals(1) .withType(OptionTypes.Int)); // parse the args if (!argParse.parseArguments(args)) return; // use the parsed args final BreadthFirstExpansion experiment = new BreadthFirstExpansion(); experiment.gameNames = (List<String>) argParse.getValue("--games"); experiment.excludeDirs = (List<String>) argParse.getValue("--exclude-dirs"); experiment.gameOptions = (List<String>) argParse.getValue("--game-options"); experiment.warmingUpSecs = argParse.getValueInt("--warming-up-secs"); experiment.measureSecs = argParse.getValueInt("--measure-secs"); experiment.postMeasureWaitSecs = argParse.getValueInt("--post-measure-wait-secs"); experiment.startExperiment(); } }
8,253
27.364261
103
java
Ludii
Ludii-master/Player/src/supplementary/experiments/speed/PlayoutsPerSec.java
package supplementary.experiments.speed; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import decision_trees.classifiers.DecisionTreeNode; import features.Feature; import features.WeightVector; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.generation.AtomicFeatureGenerator; import features.spatial.SpatialFeature; import function_approx.LinearFunction; import game.Game; import game.types.play.RoleType; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.collections.FVector; import main.grammar.Report; import metadata.ai.features.trees.FeatureTrees; import metadata.ai.features.trees.classifiers.DecisionTree; import other.GameLoader; import other.context.Context; import other.playout.PlayoutMoveSelector; import other.trial.Trial; import playout_move_selectors.DecisionTreeMoveSelector; import playout_move_selectors.FeaturesSoftmaxMoveSelector; import policies.softmax.SoftmaxFromMetadataSelection; import policies.softmax.SoftmaxPolicy; import policies.softmax.SoftmaxPolicyLinear; /** * Experiment for measuring playouts per second. * * @author Dennis Soemers, Eric.Piette */ public final class PlayoutsPerSec { /** Number of seconds of warming up (per game) */ private int warmingUpSecs; /** Number of seconds over which we measure playouts (per game) */ private int measureSecs; /** Maximum number of actions to execute per playout (-1 for no cap) */ private int playoutActionCap; /** Features to use for non-uniform playouts. Empty string means no features, i.e. uniform playouts */ private String featuresToUse; /** Type of feature set to use (ignored if not using any features, or if using features from metadata) */ private String featureSetType; /** Seed for RNG. -1 means just use ThreadLocalRandom.current() */ private int seed; /** List of game names, at least one of which must be contained in a game's name for it to be included */ private List<String> gameNames = null; /** Ruleset name. Will try to compile ALL games that match game name with this ruleset */ private String ruleset = null; /** The name of the csv to export with the results. */ private String exportCSV; /** If true, suppress standard out print messages (will still write CSV with results at the end) */ private boolean suppressPrints; /** If true, we disable custom (optimised) playout strategies on any games played */ private boolean noCustomPlayouts; //------------------------------------------------------------------------- /** * Constructor */ private PlayoutsPerSec() { // Nothing to do here } //------------------------------------------------------------------------- /** * Start the experiment */ public void startExperiment() { final String[] allGameNames = FileHandling.listGames(); final List<String> gameNameToTest = new ArrayList<String>(); for (final String gameName : allGameNames) { final String name = gameName.replaceAll(Pattern.quote("\\"), "/"); boolean nameMatch = false; for (final String mustContain : gameNames) { if (name.contains(mustContain)) { nameMatch = true; break; } } if (!nameMatch) continue; final String[] nameParts = name.split(Pattern.quote("/")); boolean exclude = false; for (int i = 0; i < nameParts.length - 1; i++) { final String part = nameParts[i].toLowerCase(); if (part.contains("plex")) { exclude = true; break; } if (part.contains("wishlist")) { exclude = true; break; } if (part.contains("wip")) { exclude = true; break; } if (part.contains("subgame")) { exclude = true; break; } if (part.contains("deduction")) { exclude = true; break; } if (part.contains("reconstruction")) { exclude = true; break; } if (part.contains("test")) { exclude = true; break; } if (part.contains("def")) { exclude = true; break; } if (part.contains("proprietary")) { exclude = true; break; } } if (!exclude) { gameNameToTest.add(name); } } if (!suppressPrints) { System.out.println("NUM GAMES = " + gameNameToTest.size()); System.out.println(); System.out.println("Using " + warmingUpSecs + " warming-up seconds per game."); System.out.println("Measuring results over " + measureSecs + " seconds per game."); System.out.println(); } final List<String> results = new ArrayList<String>(); results.add(StringRoutines.join(",", new String[]{ "Name", "p/s", "m/s", "TotalPlayouts" })); for (final String gameName : gameNameToTest) { final Game game; if (ruleset != null && !ruleset.equals("")) game = GameLoader.loadGameFromName(gameName, ruleset); else game = GameLoader.loadGameFromName(gameName, new ArrayList<String>()); if (noCustomPlayouts && game.hasCustomPlayouts()) { game.disableCustomPlayouts(); } final String[] result = new String[4]; if (game != null && !suppressPrints) System.out.println("Run: " + game.name()); result[0] = game.name(); // Load features and weights if we want to use them final PlayoutMoveSelector playoutMoveSelector = constructPlayoutMoveSelector(game); final Trial trial = new Trial(game); final Context context = new Context(game, trial); // Warming up long stopAt = 0L; long start = System.nanoTime(); double abortAt = start + warmingUpSecs * 1000000000.0; while (stopAt < abortAt) { game.start(context); game.playout(context, null, 1.0, playoutMoveSelector, -1, playoutActionCap, ThreadLocalRandom.current()); stopAt = System.nanoTime(); } System.gc(); // Set up RNG for this game final Random rng; if (seed == -1) rng = ThreadLocalRandom.current(); else rng = new Random((long)game.name().hashCode() * (long)seed); // The Test stopAt = 0L; start = System.nanoTime(); abortAt = start + measureSecs * 1000000000.0; int playouts = 0; int moveDone = 0; while (stopAt < abortAt) { game.start(context); game.playout(context, null, 1.0, playoutMoveSelector, -1, playoutActionCap, rng); moveDone += context.trial().numMoves(); stopAt = System.nanoTime(); ++playouts; } final double secs = (stopAt - start) / 1000000000.0; final double rate = (playouts / secs); final double rateMove = (moveDone / secs); result[1] = String.valueOf(rate); result[2] = String.valueOf(rateMove); result[3] = String.valueOf(playouts); results.add(StringRoutines.join(",", result)); if (!suppressPrints) System.out.println(game.name() + "\t-\t" + rate + " p/s\t-\t" + rateMove + " m/s\n"); } try (final PrintWriter writer = new UnixPrintWriter(new File(exportCSV), "UTF-8")) { for (final String toWrite : results) writer.println(StringRoutines.join(",", toWrite)); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Helper method to construct playout move selector based on features-related args * @param game * @return */ private PlayoutMoveSelector constructPlayoutMoveSelector(final Game game) { final PlayoutMoveSelector playoutMoveSelector; if (featuresToUse.length() > 0) { if (featuresToUse.toLowerCase().contains("metadata")) { // Load features from metadata final SoftmaxFromMetadataSelection softmax = new SoftmaxFromMetadataSelection(0.0); softmax.initAI(game, -1); final SoftmaxPolicy wrappedSoftmax = softmax.wrappedSoftmax(); if (wrappedSoftmax instanceof SoftmaxPolicyLinear) { final SoftmaxPolicyLinear linearWrappedSoftmax = (SoftmaxPolicyLinear) wrappedSoftmax; if (linearWrappedSoftmax.featureSets().length > 0) { final BaseFeatureSet[] featureSets = linearWrappedSoftmax.featureSets(); final WeightVector[] weights = new WeightVector[linearWrappedSoftmax.linearFunctions().length]; for (int i = 0; i < linearWrappedSoftmax.linearFunctions().length; ++i) { if (linearWrappedSoftmax.linearFunctions()[i] != null) weights[i] = linearWrappedSoftmax.linearFunctions()[i].effectiveParams(); } playoutMoveSelector = new FeaturesSoftmaxMoveSelector(featureSets, weights, false); } else { playoutMoveSelector = null; } } else { playoutMoveSelector = null; } } else if (featuresToUse.toLowerCase().startsWith("atomic-")) { final String[] strSplit = featuresToUse.split(Pattern.quote("-")); final int maxWalkSize = Integer.parseInt(strSplit[1]); final int maxStraightWalkSize = Integer.parseInt(strSplit[2]); final AtomicFeatureGenerator featureGen = new AtomicFeatureGenerator(game, maxWalkSize, maxStraightWalkSize); final BaseFeatureSet featureSet; if (featureSetType.equals("SPatterNet")) { featureSet = new SPatterNetFeatureSet(featureGen.getAspatialFeatures(), featureGen.getSpatialFeatures()); } else if (featureSetType.equals("Legacy")) { featureSet = new LegacyFeatureSet(featureGen.getAspatialFeatures(), featureGen.getSpatialFeatures()); } else if (featureSetType.equals("Naive")) { featureSet = new NaiveFeatureSet(featureGen.getAspatialFeatures(), featureGen.getSpatialFeatures()); } else if (featureSetType.equals("JITSPatterNet")) { featureSet = JITSPatterNetFeatureSet.construct(featureGen.getAspatialFeatures(), featureGen.getSpatialFeatures()); } else { throw new IllegalArgumentException("Cannot recognise --feature-set-type: " + featureSetType); } final int[] supportedPlayers = new int[game.players().count()]; for (int i = 0; i < supportedPlayers.length; ++i) { supportedPlayers[i] = i + 1; } featureSet.init(game, supportedPlayers, null); playoutMoveSelector = new FeaturesSoftmaxMoveSelector ( new BaseFeatureSet[]{featureSet}, new WeightVector[]{new WeightVector(new FVector(featureSet.getNumFeatures()))}, false ); } else if (featuresToUse.startsWith("latest-trained-uniform-")) { // We'll take the latest trained weights from specified directory, but // ignore weights (i.e. continue running uniformly) String trainedDirPath = featuresToUse.substring("latest-trained-uniform-".length()); if (!trainedDirPath.endsWith("/")) trainedDirPath += "/"; final File trainedDir = new File(trainedDirPath); int lastCheckpoint = -1; for (final File file : trainedDir.listFiles()) { if (!file.isDirectory()) { if (file.getName().startsWith("FeatureSet_P") && file.getName().endsWith(".fs")) { final int checkpoint = Integer.parseInt ( file .getName() .split(Pattern.quote("_"))[2] .replaceFirst(Pattern.quote(".fs"), "") ); if (checkpoint > lastCheckpoint) lastCheckpoint = checkpoint; } } } final BaseFeatureSet[] playerFeatureSets = new BaseFeatureSet[game.players().count() + 1]; for (int p = 1; p < playerFeatureSets.length; ++p) { final BaseFeatureSet featureSet; if (featureSetType.equals("SPatterNet")) { featureSet = new SPatterNetFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("Legacy")) { featureSet = new LegacyFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("Naive")) { featureSet = new NaiveFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("JITSPatterNet")) { featureSet = JITSPatterNetFeatureSet.construct ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else { throw new IllegalArgumentException("Cannot recognise --feature-set-type: " + featureSetType); } playerFeatureSets[p] = featureSet; } final WeightVector[] weightVectors = new WeightVector[playerFeatureSets.length]; for (int p = 1; p < playerFeatureSets.length; ++p) { playerFeatureSets[p].init(game, new int[]{p}, null); weightVectors[p] = new WeightVector(new FVector(playerFeatureSets[p].getNumFeatures())); } playoutMoveSelector = new FeaturesSoftmaxMoveSelector ( playerFeatureSets, weightVectors, false ); } else if (featuresToUse.startsWith("latest-trained-")) { // We'll take the latest trained weights from specified directory, // including weights (i.e. not playing uniformly random) String trainedDirPath = featuresToUse.substring("latest-trained-".length()); if (!trainedDirPath.endsWith("/")) trainedDirPath += "/"; final File trainedDir = new File(trainedDirPath); int lastCheckpoint = -1; for (final File file : trainedDir.listFiles()) { if (!file.isDirectory()) { if (file.getName().startsWith("FeatureSet_P") && file.getName().endsWith(".fs")) { final int checkpoint = Integer.parseInt ( file .getName() .split(Pattern.quote("_"))[2] .replaceFirst(Pattern.quote(".fs"), "") ); if (checkpoint > lastCheckpoint) lastCheckpoint = checkpoint; } } } final BaseFeatureSet[] playerFeatureSets = new BaseFeatureSet[game.players().count() + 1]; for (int p = 1; p < playerFeatureSets.length; ++p) { final BaseFeatureSet featureSet; if (featureSetType.equals("SPatterNet")) { featureSet = new SPatterNetFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("Legacy")) { featureSet = new LegacyFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("Naive")) { featureSet = new NaiveFeatureSet ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else if (featureSetType.equals("JITSPatterNet")) { featureSet = JITSPatterNetFeatureSet.construct ( trainedDirPath + String.format ( "%s_%05d.%s", "FeatureSet_P" + p, Integer.valueOf(lastCheckpoint), "fs" ) ); } else { throw new IllegalArgumentException("Cannot recognise --feature-set-type: " + featureSetType); } playerFeatureSets[p] = featureSet; } final WeightVector[] weightVectors = new WeightVector[playerFeatureSets.length]; for (int p = 1; p < playerFeatureSets.length; ++p) { playerFeatureSets[p].init(game, new int[]{p}, null); // Still null since we won't do thresholding final LinearFunction linearFunc = LinearFunction.fromFile ( trainedDirPath + String.format ( "%s_%05d.%s", "PolicyWeightsSelection_P" + p, Integer.valueOf(lastCheckpoint), "txt" ) ); weightVectors[p] = linearFunc.effectiveParams(); } playoutMoveSelector = new FeaturesSoftmaxMoveSelector ( playerFeatureSets, weightVectors, false ); } else if (featuresToUse.startsWith("decision-trees-")) { // We'll take a given decision tree final String treePath = featuresToUse.substring("decision-trees-".length()); try { final List<BaseFeatureSet> featureSetsList = new ArrayList<BaseFeatureSet>(); final List<DecisionTreeNode> roots = new ArrayList<DecisionTreeNode>(); final BaseFeatureSet[] featureSets; final DecisionTreeNode[] decisionTreeRoots; final String featureTreesString = FileHandling.loadTextContentsFromFile(treePath); final FeatureTrees featureTrees = (FeatureTrees)compiler.Compiler.compileObject ( featureTreesString, "metadata.ai.features.trees.FeatureTrees", new Report() ); for (final DecisionTree decisionTree : featureTrees.decisionTrees()) { if (decisionTree.role() == RoleType.Shared || decisionTree.role() == RoleType.Neutral) addFeatureSetRoot(0, decisionTree.root(), featureSetsList, roots); else addFeatureSetRoot(decisionTree.role().owner(), decisionTree.root(), featureSetsList, roots); } featureSets = featureSetsList.toArray(new BaseFeatureSet[featureSetsList.size()]); decisionTreeRoots = roots.toArray(new DecisionTreeNode[roots.size()]); for (int p = 0; p < featureSets.length; ++p) { if (featureSets[p] != null) featureSets[p].init(game, new int[]{p}, null); } playoutMoveSelector = new DecisionTreeMoveSelector(featureSets, decisionTreeRoots, false); } catch (final IOException e) { e.printStackTrace(); return null; } } else { throw new IllegalArgumentException("Cannot understand --features-to-use: " + featuresToUse); } } else { playoutMoveSelector = null; } return playoutMoveSelector; } //------------------------------------------------------------------------- /** * Helper method that adds a Feature Set and a Decision Tree Root for the * given player index * * @param playerIdx * @param rootNode * @param outFeatureSets * @param outRoots */ private static void addFeatureSetRoot ( final int playerIdx, final metadata.ai.features.trees.classifiers.DecisionTreeNode rootNode, final List<BaseFeatureSet> outFeatureSets, final List<DecisionTreeNode> outRoots ) { while (outFeatureSets.size() <= playerIdx) { outFeatureSets.add(null); } while (outRoots.size() <= playerIdx) { outRoots.add(null); } final List<AspatialFeature> aspatialFeatures = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatialFeatures = new ArrayList<SpatialFeature>(); final Set<String> featureStrings = new HashSet<String>(); rootNode.collectFeatureStrings(featureStrings); for (final String featureString : featureStrings) { final Feature feature = Feature.fromString(featureString); if (feature instanceof AspatialFeature) aspatialFeatures.add((AspatialFeature)feature); else spatialFeatures.add((SpatialFeature)feature); } final BaseFeatureSet featureSet = JITSPatterNetFeatureSet.construct(aspatialFeatures, spatialFeatures); outFeatureSets.set(playerIdx, featureSet); outRoots.set(playerIdx, DecisionTreeNode.fromMetadataNode(rootNode, featureSet)); } //------------------------------------------------------------------------- /** * Main method * @param args */ @SuppressWarnings("unchecked") public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Measure playouts per second for one or more games." ); argParse.addOption(new ArgOption() .withNames("--warming-up-secs", "--warming-up") .help("Number of seconds of warming up (per game).") .withDefault(Integer.valueOf(10)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--measure-secs") .help("Number of seconds over which we measure playouts (per game).") .withDefault(Integer.valueOf(30)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--playout-action-cap") .help("Maximum number of actions to execute per playout (-1 for no cap).") .withDefault(Integer.valueOf(-1)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--seed") .help("Seed to use for RNG. Default (-1) just uses ThreadLocalRandom.current().") .withDefault(Integer.valueOf(-1)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--game-names") .help("Only games that include at least one of the provided strings in their name are included.") .withDefault(Arrays.asList("")) .withNumVals("+") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--ruleset") .help("Ruleset to compile. Will assume the ruleset name to be valid for ALL games run.") .withDefault("") .withNumVals(1) .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--export-csv") .help("Filename (or filepath) to write results to. By default writes to ./results.csv") .withDefault("results.csv") .withNumVals(1) .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--suppress-prints") .help("Use this to suppress standard out print messages (will still write CSV at the end).") .withNumVals(0) .withType(OptionTypes.Boolean)); argParse.addOption(new ArgOption() .withNames("--no-custom-playouts") .help("Use this to disable custom (optimised) playout strategies on any games played.") .withNumVals(0) .withType(OptionTypes.Boolean)); argParse.addOption(new ArgOption() .withNames("--features-to-use") .help("Features to use (no features are used by default)") .withNumVals(1) .withType(OptionTypes.String) .withDefault("")); argParse.addOption(new ArgOption() .withNames("--feature-set-type") .help("Type of featureset to use (SPatterNet by default, ignored if --features-to-use left blank or if using features from metadata)") .withNumVals(1) .withType(OptionTypes.String) .withDefault("SPatterNet") .withLegalVals("SPatterNet", "Legacy", "Naive", "JITSPatterNet")); // Parse the args if (!argParse.parseArguments(args)) return; // use the parsed args final PlayoutsPerSec experiment = new PlayoutsPerSec(); experiment.warmingUpSecs = argParse.getValueInt("--warming-up-secs"); experiment.measureSecs = argParse.getValueInt("--measure-secs"); experiment.playoutActionCap = argParse.getValueInt("--playout-action-cap"); experiment.seed = argParse.getValueInt("--seed"); experiment.gameNames = (List<String>) argParse.getValue("--game-names"); experiment.ruleset = argParse.getValueString("--ruleset"); experiment.exportCSV = argParse.getValueString("--export-csv"); experiment.suppressPrints = argParse.getValueBool("--suppress-prints"); experiment.noCustomPlayouts = argParse.getValueBool("--no-custom-playouts"); experiment.featuresToUse = argParse.getValueString("--features-to-use"); experiment.featureSetType = argParse.getValueString("--feature-set-type"); experiment.startExperiment(); } }
24,911
28.342756
138
java
Ludii
Ludii-master/Player/src/supplementary/experiments/speed/TimeTensorsRandomPlayouts.java
package supplementary.experiments.speed; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import game.Game; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import other.GameLoader; import main.FileHandling; import utils.LudiiGameWrapper; import utils.LudiiStateWrapper; /** * Experiment for timing random playouts in which we also create a state tensor * for every state that we encounter. Note that this also means that we cannot * use optimised playout strategies. * * @author Dennis Soemers */ public final class TimeTensorsRandomPlayouts { /** * Names of the games to play. Each should end with ".lud". * Use "all" to run all games we can find. Runs all games by default */ private List<String> gameNames; /** List of game directories to exclude from experiment */ private List<String> excludeDirs; /** Options to tweak game (variant, rules, board, etc.) */ private List<String> gameOptions; /** Number of seconds of warming up (per game) */ private int warmingUpSecs; /** Number of seconds over which we measure playouts (per game) */ private int measureSecs; /** Maximum number of actions to execute per playout (-1 for no cap) */ private int playoutActionCap; //------------------------------------------------------------------------- /** * Constructor */ private TimeTensorsRandomPlayouts() { // Nothing to do here } //------------------------------------------------------------------------- /** * Start the experiment */ public void startExperiment() { // Gather all the game names final List<String> gameNamesToTest = new ArrayList<String>(); if (gameNames.get(0).equalsIgnoreCase("all")) { // lowercase all the exclude dirs, makes tests easier for (int i = 0; i < excludeDirs.size(); ++i) { excludeDirs.set(i, excludeDirs.get(i).toLowerCase()); } final String[] allGameNames = FileHandling.listGames(); for (final String gameName : allGameNames) { final String name = gameName.replaceAll(Pattern.quote("\\"), "/"); final String[] nameParts = name.split(Pattern.quote("/")); boolean exclude = false; for (final String part : nameParts) { if ( excludeDirs.contains(part.toLowerCase()) || part.equals("plex") || part.equals("bad") || part.equals("bad_playout") || part.equals("wip") || part.equals("test") ) { exclude = true; break; } } if (!exclude) { gameNamesToTest.add(name); } } } else { final String[] allGameNames = FileHandling.listGames(); for (String gameName : gameNames) { gameName = gameName.replaceAll(Pattern.quote("\\"), "/"); for (String name : allGameNames) { name = name.replaceAll(Pattern.quote("\\"), "/"); if (name.endsWith(gameName)) { gameNamesToTest.add(name); } } } } System.out.println("Starting timings for games: " + gameNamesToTest); System.out.println(); System.out.println("Using " + warmingUpSecs + " warming-up seconds per game."); System.out.println("Measuring results over " + measureSecs + " seconds per game."); System.out.println(); for (final String gameName : gameNamesToTest) { final Game game = GameLoader.loadGameFromName(gameName, gameOptions); final LudiiGameWrapper gameWrapper = new LudiiGameWrapper(game); final LudiiStateWrapper stateWrapper = new LudiiStateWrapper(gameWrapper); // Warming up long stopAt = 0L; long start = System.nanoTime(); double abortAt = start + warmingUpSecs * 1000000000.0; while (stopAt < abortAt) { stateWrapper.reset(); int numActionsPlayed = 0; while (!stateWrapper.isTerminal() && (numActionsPlayed < playoutActionCap || playoutActionCap < 0)) { // Compute tensor for current state @SuppressWarnings("unused") // Do NOT remove! We need this for accurate timings!!!!!!!!! final float[][][] stateTensor = stateWrapper.toTensor(); // Play random action stateWrapper.applyNthMove(ThreadLocalRandom.current().nextInt(stateWrapper.numLegalMoves())); ++numActionsPlayed; } stopAt = System.nanoTime(); } System.gc(); // The Test stopAt = 0L; start = System.nanoTime(); abortAt = start + measureSecs * 1000000000.0; int playouts = 0; long numDecisions = 0L; while (stopAt < abortAt) { stateWrapper.reset(); int numActionsPlayed = 0; while (!stateWrapper.isTerminal() && (numActionsPlayed < playoutActionCap || playoutActionCap < 0)) { // Compute tensor for current state @SuppressWarnings("unused") // Do NOT remove! We need this for accurate timings!!!!!!!!! final float[][][] stateTensor = stateWrapper.toTensor(); // Play random action stateWrapper.applyNthMove(ThreadLocalRandom.current().nextInt(stateWrapper.numLegalMoves())); ++numActionsPlayed; } numDecisions += stateWrapper.trial().numMoves() - stateWrapper.trial().numInitialPlacementMoves(); stopAt = System.nanoTime(); playouts++; } final double secs = (stopAt - start) / 1000000000.0; final double rate = (playouts / secs); final double decisionsPerPlayout = ((double) numDecisions) / playouts; System.out.println(game.name() + "\t-\t" + rate + " p/s\t-\t" + decisionsPerPlayout + " decisions per playout\n"); } } //------------------------------------------------------------------------- /** * Main method * @param args */ @SuppressWarnings("unchecked") public static void main(final String[] args) { // define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Measure playouts per second for one or more games." ); argParse.addOption(new ArgOption() .withNames("--games") .help("Names of the games to play. Each should end with \".lud\". " + "Use \"all\" to run all games we can find. " + "Runs all games by default.") .withDefault(Arrays.asList("all")) .withNumVals("+") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--exclude-dirs") .help("List of game directories to exclude from experiment.") .withDefault(Arrays.asList("puzzle")) .withNumVals("*") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--game-options") .help("Game Options to load.") .withDefault(new ArrayList<String>(0)) .withNumVals("*") .withType(OptionTypes.String)); argParse.addOption(new ArgOption() .withNames("--warming-up-secs", "--warming-up") .help("Number of seconds of warming up (per game).") .withDefault(Integer.valueOf(10)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--measure-secs") .help("Number of seconds over which we measure playouts (per game).") .withDefault(Integer.valueOf(30)) .withNumVals(1) .withType(OptionTypes.Int)); argParse.addOption(new ArgOption() .withNames("--playout-action-cap") .help("Maximum number of actions to execute per playout (-1 for no cap).") .withDefault(Integer.valueOf(-1)) .withNumVals(1) .withType(OptionTypes.Int)); // parse the args if (!argParse.parseArguments(args)) return; // use the parsed args final TimeTensorsRandomPlayouts experiment = new TimeTensorsRandomPlayouts(); experiment.gameNames = (List<String>) argParse.getValue("--games"); experiment.excludeDirs = (List<String>) argParse.getValue("--exclude-dirs"); experiment.gameOptions = (List<String>) argParse.getValue("--game-options"); experiment.warmingUpSecs = argParse.getValueInt("--warming-up-secs"); experiment.measureSecs = argParse.getValueInt("--measure-secs"); experiment.playoutActionCap = argParse.getValueInt("--playout-action-cap"); experiment.startExperiment(); } }
8,158
28.669091
117
java
Ludii
Ludii-master/Player/src/supplementary/visualisation/FeatureToEPS.java
package supplementary.visualisation; import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import bridge.Bridge; import features.spatial.AbsoluteFeature; import features.spatial.RelativeFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.elements.FeatureElement; import features.spatial.elements.FeatureElement.ElementType; import features.spatial.elements.RelativeFeatureElement; import game.Game; import other.context.Context; import other.trial.Trial; /** * Utility class to create .eps images from features. * * @author Dennis Soemers */ public class FeatureToEPS { //------------------------------------------------------------------------- private static final int J_HEX_RADIUS = 17; // private static final int J_HEX_WIDTH = (int) Math.ceil(Math.sqrt(3.0) * J_HEX_RADIUS); // private static final int J_HEX_HEIGHT = 2 * J_HEX_RADIUS; private static final int J_SQUARE_SIDE = 34; /** Radius of Hex tiles (circumradius = radius of outer circle) */ private static final String HEX_RADIUS = "" + J_HEX_RADIUS; /** Width of a Hex tile (with pointy parts going up/down) */ // private static final String HEX_WIDTH = "3.0 sqrt " + HEX_RADIUS + " mul"; /** Height of a Hex tile (with pointy parts going up/down) */ // private static final String HEX_HEIGHT = "2 " + HEX_RADIUS + " mul"; private static final String SQUARE_SIDE = "" + J_SQUARE_SIDE; //------------------------------------------------------------------------- /** */ private FeatureToEPS() { // do not use } //------------------------------------------------------------------------- /** * Creates a .eps file visualising the given feature * @param feature * @param player * @param game * @param outputFile File to write output to (EPS program) */ public static void createEPS ( final SpatialFeature feature, final int player, final Game game, final File outputFile ) { // Gather some info on game final Bridge bridge = new Bridge(); final Context dummyContext = new Context(game, new Trial(game)); final Color friendColour = bridge.settingsColour().playerColour(dummyContext, player); final int opponentID = player == 2 ? 1 : 2; final Color enemyColour = bridge.settingsColour().playerColour(dummyContext, opponentID); final double friendR = friendColour.getRed() / 255.0; final double friendG = friendColour.getGreen() / 255.0; final double friendB = friendColour.getBlue() / 255.0; final double enemyR = enemyColour.getRed() / 255.0; final double enemyG = enemyColour.getGreen() / 255.0; final double enemyB = enemyColour.getBlue() / 255.0; // boolean squareTiling = (numOrths == 4); // boolean hexTiling = (numOrths == 6); // boolean playOnIntersections = (game.board() instanceof GoBoard); // // final int jCellHeight; // final int jCellWidth; // final String cellHeight; // final String cellWidth; // // if (squareTiling) // { // jCellHeight = J_SQUARE_SIDE; // jCellWidth = J_SQUARE_SIDE; // cellHeight = SQUARE_SIDE; // cellWidth = SQUARE_SIDE; // } // else if (hexTiling) // { // jCellHeight = J_HEX_HEIGHT; // jCellWidth = J_HEX_WIDTH; // cellHeight = HEX_HEIGHT; // cellWidth = HEX_WIDTH; // } // else // { // System.err.println("Unsupported tiling!"); // return; // } // we'll update these as we draw things int bboxLeftX = 0; int bboxLowerY = 0; int bboxRightX = 0; int bboxTopY = 0; if (feature instanceof AbsoluteFeature) { // TODO ? System.err.println("Cannot (yet?) visualise absolute feature"); return; } final RelativeFeature rel = (RelativeFeature) feature; final Walk from = rel.fromPosition(); final Walk to = rel.toPosition(); final FeatureElement[] elements = rel.pattern().featureElements(); double maxX = 0.0; double minX = 0.0; double maxY = 0.0; double minY = 0.0; // Compute all the offsets for all the walks TODO last-from and last-to final double[] fromOffset = computeOffset(from); final double[] toOffset = computeOffset(to); final List<double[]> elementOffsets = new ArrayList<double[]>(); final List<RelativeFeatureElement> relEls = new ArrayList<RelativeFeatureElement>(); for (final FeatureElement element : elements) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement relEl = (RelativeFeatureElement) element; elementOffsets.add(computeOffset(relEl.walk())); relEls.add(relEl); } } // This will contain the program for this image final List<String> imageProgram = new ArrayList<String>(); //final Set<Cell> cellsToDraw = new HashSet<Cell>(); if (fromOffset != null) { // TODO draw from-position } if (toOffset != null) { imageProgram.add(toOffset[0] + " " + toOffset[1] + " IncentiviseTo"); maxX = Math.max(maxX, toOffset[0]); minX = Math.min(minX, toOffset[0]); maxY = Math.max(maxY, toOffset[1]); minY = Math.min(minY, toOffset[1]); // Remember that we should draw this cell //cellsToDraw.add(new Cell(toOffset)); } for (int elIdx = 0; elIdx < relEls.size(); ++elIdx) { final RelativeFeatureElement el = relEls.get(elIdx); final ElementType type = el.type(); final double[] offset = elementOffsets.get(elIdx); maxX = Math.max(maxX, offset[0]); minX = Math.min(minX, offset[0]); maxY = Math.max(maxY, offset[1]); minY = Math.min(minY, offset[1]); if (el.not() && type != ElementType.Off) { imageProgram.add(0, offset[0] + " " + offset[1] + " Not"); } if (type == ElementType.Empty) { // draw a little white circle to indicate empty position imageProgram.add(0, offset[0] + " " + offset[1] + " Empty"); } else if (type == ElementType.Friend) { // draw a friend imageProgram.add(0, offset[0] + " " + offset[1] + " Friend"); } else if (type == ElementType.Enemy) { // draw an enemy imageProgram.add(0, offset[0] + " " + offset[1] + " Enemy"); } else if (type == ElementType.Off) { if (!el.not()) { // mark cell as off-board imageProgram.add(0, offset[0] + " " + offset[1] + " OffBoard"); } } else if (type == ElementType.Any) { // TODO System.err.println("TODO: draw any element"); } else if (type == ElementType.P1) { // TODO System.err.println("TODO: draw P1 element"); } else if (type == ElementType.P2) { // TODO System.err.println("TODO: draw P2 element"); } else if (type == ElementType.Item) { // TODO System.err.println("TODO: draw Item element"); } else if (type == ElementType.IsPos) { // TODO System.err.println("TODO: draw IsPos element"); } // Remember that we should draw this cell //cellsToDraw.add(new Cell(offset)); } // Draw our cells // for (int dx = minCellCol; dx <= maxCellCol; ++dx) // { // for (int dy = minCellRow; dy <= maxCellRow; ++dy) // { // if (cellsToDraw.contains(new Cell(new int[]{dx, dy}))) // { // imageProgram.add(0, dx + " " + dy + " Cell"); // } // } // } // Draw dashed versions of all the unused cells // for (int dx = minCellCol; dx <= maxCellCol; ++dx) // { // for (int dy = minCellRow; dy <= maxCellRow; ++dy) // { // if (!cellsToDraw.contains(new Cell(new int[]{dx, dy}))) // { // imageProgram.add(0, dx + " " + dy + " CellDashed"); // } // } // } // compute bounding box bboxRightX = (int) Math.ceil((maxX - minX + 2) * J_SQUARE_SIDE); bboxTopY = (int) Math.ceil((maxY - minY + 2) * J_SQUARE_SIDE); // we'll collect and generate the feature-specific program lines in here final List<String> program = new ArrayList<String>(); program.add("% translate a bit to ensure we have some whitespace on left and bottom"); program.add(J_SQUARE_SIDE + " " + J_SQUARE_SIDE + " translate"); program.add(""); // start writing program for this row + col program.add("gsave"); program.add("% translate to origin of this particular image"); program.add((-minX) + " " + J_SQUARE_SIDE + " mul " + (-minY) + " " + J_SQUARE_SIDE + " mul translate"); program.add(""); for (final String line : imageProgram) { program.add(line); } program.add(""); program.add("grestore"); program.add(""); // start writing try (final PrintWriter w = new PrintWriter(outputFile.getAbsolutePath(), "ASCII")) { // write some general stuff at start of file w.println("%!PS"); w.println("%%LanguageLevel: 3"); w.println("%%Creator: Ludii"); w.println("%%CreationDate: " + LocalDate.now().toString()); w.println("%%BoundingBox: " + bboxLeftX + " " + bboxLowerY + " " + bboxRightX + " " + bboxTopY); w.println("%%EndComments"); w.println("%%BeginProlog"); w.println("%%EndProlog"); w.println(""); // write page size w.println("<< /PageSize [" + (bboxRightX - bboxLeftX) + " " + (bboxTopY - bboxLowerY) + "] >> setpagedevice"); w.println(""); // write some constants w.println("%---------------- Constants -------------------"); w.println(""); w.println("/Root3 3.0 sqrt def"); w.println(""); // write useful variables for our pieces / cells / shapes / etc. w.println("%--------------- Variables ------------------"); w.println(""); w.println("/HexRadius " + HEX_RADIUS + " def"); w.println("/HexDiameter { HexRadius 2 mul } def"); w.println(""); w.println("/SquareSide " + SQUARE_SIDE + " def"); w.println(""); w.println("/CircleRadius { 17 .75 mul } def"); w.println("/CircleLineWidth 2 def"); w.println(""); w.println("/EmptyRadius { 17 .4 mul } def"); w.println("/EmptyLineWidth 0.75 def"); w.println(""); w.println(""); // write useful functions w.println("% ----------- Functions -------------"); w.println(""); w.println("/inch {72 mul} def"); w.println("/cm {182.88 mul} def"); w.println(""); w.println("/X"); w.println("{ % call: i j X"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(" i SquareSide mul "); w.println(" end"); w.println("} def"); w.println(""); w.println("/Y"); w.println("{ % call: i j Y"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(" j SquareSide mul "); w.println(" end"); w.println("} def"); w.println(""); w.println("/XY"); w.println("{ % call: i j XY"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(" i j X i j Y"); w.println(" end"); w.println("} def"); // if (squareTiling) // { // // functions for square tilings // w.println("/X"); // w.println("{ % call: i j X"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" i SquareSide mul "); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/Y"); // w.println("{ % call: i j Y"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" j SquareSide mul "); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/XY"); // w.println("{ % call: i j XY"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" i j X i j Y"); // w.println(" end"); // w.println("} def"); // // if (playOnIntersections) // { // w.println(""); // w.println("/Cell"); // w.println("{ % call: i j Cell"); // w.println(" 2 dict begin"); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" "); // w.println(" gsave"); // w.println(" "); // w.println(" % fill squares"); // // TODO // w.println(" "); // w.println(" % draw lines"); // w.println(" 0 setgray"); // w.println(" .1 setlinewidth"); // w.println(" "); // w.println(" newpath i j XY moveto SquareSide 0 rlineto stroke"); // w.println(" newpath i j XY moveto SquareSide neg 0 rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide neg rlineto stroke"); // w.println(" "); // w.println(" grestore"); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/CellDashed"); // w.println("{ % call: i j CellDashed"); // w.println(" 2 dict begin"); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" "); // w.println(" gsave"); // w.println(" "); // w.println(" % fill squares"); // // TODO // w.println(" "); // w.println(" % draw lines"); // w.println(" 0 setgray"); // w.println(" .1 setlinewidth"); // w.println(" [4 4] 0 setdash"); // w.println(" "); // w.println(" newpath i j XY moveto SquareSide 0 rlineto stroke"); // w.println(" newpath i j XY moveto SquareSide neg 0 rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide neg rlineto stroke"); // w.println(" "); // w.println(" [] 0 setdash"); // w.println(" grestore"); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/OffBoard"); // w.println("{ % call: i j OffBoard"); // w.println(" 2 dict begin"); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" "); // w.println(" gsave"); // w.println(" "); // w.println(" % fill squares"); // w.println(" 0.75 setgray"); // w.println(" newpath i j XY moveto"); // w.println(" SquareSide 1 sub 0 rmoveto"); // w.println(" 0 SquareSide 1 sub rlineto"); // w.println(" 2 SquareSide 1 sub mul neg 0 rlineto"); // w.println(" 0 2 SquareSide 1 sub mul neg rlineto"); // w.println(" 2 SquareSide 1 sub mul 0 rlineto"); // w.println(" closepath fill"); // w.println(" "); // w.println(" % draw lines"); // w.println(" 0 setgray"); // w.println(" .1 setlinewidth"); // w.println(" [4 4] 0 setdash"); // w.println(" "); // w.println(" newpath i j XY moveto SquareSide 0 rlineto stroke"); // w.println(" newpath i j XY moveto SquareSide neg 0 rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide rlineto stroke"); // w.println(" newpath i j XY moveto 0 SquareSide neg rlineto stroke"); // w.println(" "); // w.println(" [] 0 setdash"); // w.println(" grestore"); // w.println(" end"); // w.println("} def"); // } // else // { // // TODO cells for square tilings where we play inside the cells // } // } // else if (hexTiling) // { // // functions for hex tilings // w.println("/X"); // w.println("{ % call: i j X"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" i j -.5 mul add HexRadius mul Root3 mul "); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/Y"); // w.println("{ % call: i j Y"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" j HexRadius mul 3 mul 2 div "); // w.println(" end"); // w.println("} def"); // w.println(""); // // w.println("/XY"); // w.println("{ % call: i j XY"); // w.println(" 2 dict begin "); // w.println(" /j exch def"); // w.println(" /i exch def"); // w.println(" i j X i j Y"); // w.println(" end"); // w.println("} def"); // } w.println(""); w.println("/Friend"); w.println("{ % call: i j Friend"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(""); w.println(" CircleLineWidth setlinewidth"); w.println(""); w.println(" " + friendR + " " + friendG + " " + friendB + " setrgbcolor"); w.println(" newpath i j XY CircleRadius 0 360 arc fill"); w.println(""); w.println(" 0 setgray"); w.println(" newpath i j XY CircleRadius 0 360 arc stroke"); w.println(" end"); w.println("} def"); w.println(""); w.println("/Enemy"); w.println("{ % call: i j Enemy"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(""); w.println(" CircleLineWidth setlinewidth"); w.println(""); w.println(" " + enemyR + " " + enemyG + " " + enemyB + " setrgbcolor"); w.println(" newpath i j XY CircleRadius 0 360 arc fill"); w.println(""); w.println(" 0 setgray"); w.println(" newpath i j XY CircleRadius 0 360 arc stroke"); w.println(" end"); w.println("} def"); w.println(""); w.println("/Empty"); w.println("{ % call: i j Empty"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(""); w.println(" EmptyLineWidth setlinewidth"); w.println(" [2 2] 0 setdash"); w.println(""); w.println(" 1 setgray"); w.println(" newpath i j XY EmptyRadius 0 360 arc fill"); w.println(""); w.println(" 0 setgray"); w.println(" newpath i j XY EmptyRadius 0 360 arc stroke"); w.println(" [] 0 setdash"); w.println(" end"); w.println("} def"); w.println(""); w.println("/IncentiviseTo"); w.println("{ % call: i j IncentiviseTo"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(""); w.println(" gsave"); w.println(" CircleLineWidth setlinewidth"); w.println(""); w.println(" 0 0 1 setrgbcolor"); w.println(""); w.println(" newpath i j XY EmptyRadius 0 360 arc clip"); w.println(" newpath i j XY moveto SquareSide 0 rmoveto SquareSide -2 mul 0 rlineto stroke"); w.println(" newpath i j XY moveto 0 SquareSide rmoveto 0 SquareSide -2 mul rlineto stroke"); w.println(" grestore"); w.println(" end"); w.println("} def"); w.println(""); w.println("/Not"); w.println("{ % call: i j Not"); w.println(" 2 dict begin "); w.println(" /j exch def"); w.println(" /i exch def"); w.println(""); w.println(" gsave"); w.println(" CircleLineWidth setlinewidth"); w.println(""); w.println(" 1 0 0 setrgbcolor"); w.println(""); w.println(" newpath i j XY EmptyRadius 0 360 arc clip"); w.println(" newpath i j XY moveto SquareSide -2 div SquareSide 2 div rmoveto SquareSide SquareSide neg rlineto stroke"); w.println(" newpath i j XY moveto SquareSide -2 div SquareSide -2 div rmoveto SquareSide SquareSide rlineto stroke"); w.println(" grestore"); w.println(" end"); w.println("} def"); w.println(""); w.println("/textheight"); w.println("{ % based on: https://stackoverflow.com/a/7122326/6735980"); w.println(" gsave % save graphic context"); w.println(" {"); w.println(" 100 100 moveto % move to some point"); w.println(" (HIpg) true charpath pathbbox % gets text path bounding box (LLx LLy URx URy)"); w.println(" exch pop 3 -1 roll pop % keeps LLy and URy"); w.println(" exch sub % URy - LLy"); w.println(" }"); w.println(" stopped % did the last block fail?"); w.println(" {"); w.println(" pop pop % get rid of \"stopped\" junk"); w.println(" currentfont /FontMatrix get 3 get % gets alternative text height"); w.println(" }"); w.println(" if"); w.println(" grestore % restore graphic context"); w.println("} bind def"); w.println(""); w.println("/StringAroundPoint"); w.println("{ % call: newpath i j XY moveto (string) StringAroundPoint"); w.println(" dup stringwidth pop % get width of string"); w.println(" -2 div % negate, and divide by 2"); w.println(" textheight -2.9 div % don't know why, but div by 3 seems to work better than 2"); w.println(" rmoveto % move to left and down by half width and height"); w.println(" show % show the string"); w.println("} def"); w.println(""); // write the actual feature-specific program w.println("%-------------- Program --------------"); // TODO write comment with command-line for generating this image w.println(""); w.println("/Times-Bold findfont 24 scalefont setfont"); w.println(""); for (final String line : program) { w.println(line); } w.println(""); // write final parts of file w.println(""); w.println("%------------------------------------------"); w.println(""); w.println("showpage"); w.println(""); w.println("%%Trailer"); w.println("%%EOF"); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * @param walk * @return Offset in "step-units" resulting in walking the walk, from anchor */ private static double[] computeOffset(final Walk walk) { if (walk == null) return null; double dx = 0.0; double dy = 0.0; // We assume 0.0 points "north", so for normal math that's a 90 degrees angle double currAngle = Math.toRadians(90.0); for (int i = 0; i < walk.steps().size(); ++i) { // Subtract steps because we assume clockwise, but normal math assumes counterclockwise final float step = walk.steps().getQuick(i); currAngle -= step * Math.PI * 2.0; // Take one step in current direction, add to offsets dx += Math.cos(currAngle); dy += Math.sin(currAngle); } return new double[]{dx, dy}; } //------------------------------------------------------------------------- // /** // * A cell on our "board", specified by dx and dy from feature's anchor position. // * // * @author Dennis Soemers // */ // private static class Cell // { // /** dx */ // public final int dx; // // /** dy */ // public final int dy; // // /** // * Constructor // * @param offset // */ // public Cell(final int[] offset) // { // dx = offset[0]; // dy = offset[1]; // } // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + dx; // result = prime * result + dy; // return result; // } // // @Override // public boolean equals(final Object obj) // { // if (!(obj instanceof Cell)) // return false; // // final Cell other = (Cell) obj; // // return (dx == other.dx && dy == other.dy); // } // } //------------------------------------------------------------------------- /** * Main method * @param args */ public static void main(final String[] args) { // TODO } }
23,543
29.457956
126
java
Ludii
Ludii-master/Player/src/supplementary/visualisation/FeatureToTikz.java
package supplementary.visualisation; import features.Feature; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import main.StringRoutines; public class FeatureToTikz { //------------------------------------------------------------------------- /** * Private constructor */ private FeatureToTikz() { // Do nothing } //------------------------------------------------------------------------- /** Feature to write tikz code for*/ protected String feature; //------------------------------------------------------------------------- /** * Do the work */ public void run() { final Feature f = Feature.fromString(feature); System.out.println("% Code generated for feature: " + StringRoutines.quote(feature)); System.out.println(f.generateTikzCode(null)); } //------------------------------------------------------------------------- /** * Main method * @param args */ public static void main(final String[] args) { // Define options for arg parser final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Print tikz code for a given feature." ); argParse.addOption(new ArgOption() .withNames("--feature") .help("Feature to write tikz code for.") .withNumVals(1) .withType(OptionTypes.String) .setRequired()); // parse the args if (!argParse.parseArguments(args)) return; final FeatureToTikz task = new FeatureToTikz(); task.feature = argParse.getValueString("--feature"); task.run(); } //------------------------------------------------------------------------- }
1,681
21.131579
87
java
Ludii
Ludii-master/Player/test/ai/TestDefaultAIs.java
package ai; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import compiler.Compiler; import game.Game; import main.FileHandling; import main.grammar.Description; import other.context.Context; import other.trial.Trial; import utils.LudiiAI; /** * Unit test to ensure that for every game we can load a default AI * that can make at least one move without crashing in that game. * * @author Dennis Soemers */ public class TestDefaultAIs { @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/simulation")) continue; if (path.equals("../Common/res/lud/subgame")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); testDefaultAI(game); } } } /** * Tests default AI on given game * @param game */ public static void testDefaultAI(final Game game) { if (game.isDeductionPuzzle()) return; if (game.hasSubgames()) return; try { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // Create our AI and init it final LudiiAI ai = new LudiiAI(); ai.initAI(game, 1); // Have it select one move ai.selectAction(game, context, 0.1, 10, 1); } catch (final Exception e) { System.err.println("Game = " + game.name()); e.printStackTrace(); fail(); } } }
3,451
21.128205
82
java
Ludii
Ludii-master/Player/test/ai/TestHeuristicStateValues.java
package ai; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.context.Context; import other.model.Model; import other.trial.Trial; /** * Unit tests for heuristic state value estimators. * * @author Dennis Soemers */ public class TestHeuristicStateValues { /** * Unit test which: * - Runs one random playout for every game * - In every encountered state, tries to run the computation of any * heuristic state evaluation term that claims to be applicable to that game * - Ensures we have at least one (non-intercept, non-mover) heuristic state * evaluation term that's applicable for every alternating-move game. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; if (path.equals("../Common/res/lud/test")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } // the following entries should correctly compile and run for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game.hasSubgames()) continue; final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // collect applicable heuristics final int numPlayers = game.players().count(); // final List<Component> components = game.equipment().components(); // final List<Regions> regions = game.equipment().regions(); // final List<StateHeuristicValue> heuristics = new ArrayList<StateHeuristicValue>(); // heuristics.add(new Intercept()); // intercept always applicable // // if (CentreProximity.isApplicableToGame(game)) // heuristics.add(new CentreProximity(game)); // // if (CornerProximity.isApplicableToGame(game)) // heuristics.add(new CornerProximity(game)); // // if (CurrentMoverHeuristic.isApplicableToGame(game)) // heuristics.add(new CurrentMoverHeuristic()); // // if (LineCompletionHeuristic.isApplicableToGame(game)) // heuristics.add(new LineCompletionHeuristic(game)); // // if (Material.isApplicableToGame(game)) // heuristics.add(new Material(game)); // // if (MobilitySimple.isApplicableToGame(game)) // heuristics.add(new MobilitySimple()); // //// if (OpponentPieceProximity.isApplicableToGame(game)) //// heuristics.add(new OpponentPieceProximity(game)); // // if (OwnRegionsCount.isApplicableToGame(game)) // heuristics.add(new OwnRegionsCount(game)); // // if (PlayerRegionsProximity.isApplicableToGame(game)) // { // final FVector pieceWeights = new FVector(components.size()); // pieceWeights.fill(0, pieceWeights.dim(), 1.f); // // for (int p = 1; p <= numPlayers; ++p) // { // heuristics.add(new PlayerRegionsProximity(game, pieceWeights, p)); // } // } // // if (PlayerSiteMapCount.isApplicableToGame(game)) // heuristics.add(new PlayerSiteMapCount()); // // if (RegionProximity.isApplicableToGame(game)) // { // final FVector pieceWeights = new FVector(components.size()); // pieceWeights.fill(0, pieceWeights.dim(), 1.f); // // for (int i = 0; i < regions.size(); ++i) // { // heuristics.add(new RegionProximity(game, pieceWeights, i)); // } // } // // if (Score.isApplicableToGame(game)) // heuristics.add(new Score()); // // if (SidesProximity.isApplicableToGame(game)) // heuristics.add(new SidesProximity(game)); // // assert (heuristics.size() > 1); // // final FVector heuristicTermWeights = new FVector(heuristics.size()); // heuristicTermWeights.fill(0, heuristicTermWeights.dim(), 1.f); // // final List<HeuristicTransformation> transformations = new ArrayList<HeuristicTransformation>(); // for (int i = 0; i < heuristics.size(); ++i) // { // transformations.add(new Identity()); // } // // final HeuristicEnsemble ensemble = new HeuristicEnsemble(heuristicTermWeights, heuristics, transformations); final Model model = context.model(); while (!trial.over()) { // evaluate from every player's perspective for (int p = 1; p <= numPlayers; ++p) { //final float eval = ensemble.computeValue(context, p, -1.f); //assert (!Float.isNaN(eval)); } model.startNewStep(context, null, 0.0); } } } } }
6,220
28.206573
114
java
Ludii
Ludii-master/Player/test/concepts/ConceptTests.java
package concepts; import static org.junit.Assert.fail; import org.junit.Test; import other.concept.Concept; /** * Test for the huge concept enum in order to check taxo and child/parent. * * @author Eric.Piette */ public class ConceptTests { @Test @SuppressWarnings("static-method") public void ConceptLeaf() { for (final Concept concept : Concept.values()) { final boolean leaf = concept.isleaf(); if (leaf) { final String taxo = concept.taxonomy(); final Concept parentConcept = concept.parent(); if (parentConcept != null) { final String parentTaxo = parentConcept.taxonomy(); final String parentShouldBe = taxo.substring(0, taxo.lastIndexOf('.')); if (!parentTaxo.equals(parentShouldBe)) { System.err.println("Something incorrect about parent of " + concept.name()); fail(); } } } else { boolean childFound = false; for (final Concept child : Concept.values()) { if (child.parent() != null) { if (child.parent().equals(concept)) { childFound = true; break; } } } if (!childFound) { System.err.println("No Child for no leaf concept = " + concept.name()); fail(); } } } } }
1,262
18.430769
82
java
Ludii
Ludii-master/Player/test/features/TestAmazonsFeatures.java
package features; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.GameLoader; import other.action.move.ActionAdd; import other.action.move.move.ActionMove; import other.action.state.ActionSetNextPlayer; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit tests for features in Amazons * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestAmazonsFeatures { @Test public void test() { final Game game = GameLoader.loadGameFromName("Amazons.lud"); // generate handcrafted feature set final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}]>:comment=\"move/shoot to empty position\"")); // 0 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0}]>:comment=\"move/shoot next to friend\"")); // 1 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, e{0.0}]>:comment=\"move/shoot next to enemy\"")); // 2 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, I3{0.0}]>:comment=\"move/shoot next to arrow\"")); // 3 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}]>:comment=\"move/shoot next to edge\"")); // 4 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}, #{0.25}]>:comment=\"move/shoot into corner\"")); // 5 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, !-{0.0}]>:comment=\"move/shoot next to a non-empty position\"")); // 6 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[-{}]>:comment=\"move/shoot from empty position (impossible!)\"")); // 7 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[f{0.0}]>:comment=\"move from position next to friend\"")); // 8 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[e{0.0}]>:comment=\"move from position next to enemy\"")); // 9 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[I3{0.0}]>:comment=\"move from position next to arrow\"")); // 10 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[#{0.0}]>:comment=\"move from position next to edge\"")); // 11 features.add((SpatialFeature)Feature.fromString("rel:from=<{}>:pat=<refl=true,rots=all,els=[#{0.0}, #{0.25}]>:comment=\"move/shoot from corner\"")); // 12 features.add // 13 ( (SpatialFeature)Feature.fromString ( "rel:last_to=<{0.0}>:from=<{}>:pat=<refl=true,rots=all,els=[f{}, I3{0.0}]>:" + "comment=\"move from position next to where opponent shot in last move\"" ) ); features.add // 14 ( (SpatialFeature)Feature.fromString ( "rel:last_to=<{0.0}>:to=<{}>:pat=<refl=true,rots=all,els=[-{}, I3{0.0}]>:" + "comment=\"move/shoot to position next to where opponent shot in last move\"" ) ); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N4{}]>:comment=\"Every to-position has connectivity 4.\"")); // 15 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N8{}]>:comment=\"No to-position has connectivity 8.\"")); // 16 // Randomly pick one of the feature set implementations to test final BaseFeatureSet featureSet; final double rand = ThreadLocalRandom.current().nextDouble(); if (rand < 0.25) featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); else if (rand < 0.5) featureSet = JITSPatterNetFeatureSet.construct(new ArrayList<AspatialFeature>(), features); else if (rand < 0.75) featureSet = new LegacyFeatureSet(new ArrayList<AspatialFeature>(), features); else featureSet = new NaiveFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // P1 moves from 39 to 9 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 39, Constants.UNDEFINED, SiteType.Cell, 9, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(1)).withFrom(39).withTo(9)); // P1 shoots at 59 game.apply(context, new Move( new ActionAdd(null, 59, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(59).withTo(59)); // P2 moves from 69 to 36 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 69, Constants.UNDEFINED, SiteType.Cell, 36, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(2)).withFrom(69).withTo(36)); // P2 shoots at 16 game.apply(context, new Move( new ActionAdd(null, 16, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(16).withTo(16)); // P1 moves from 30 to 35 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 30, Constants.UNDEFINED, SiteType.Cell, 35, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(1)).withFrom(30).withTo(35)); // P1 shoots at 95 game.apply(context, new Move( new ActionAdd(null, 95, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(95).withTo(95)); // P2 moves from 93 to 90 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 93, Constants.UNDEFINED, SiteType.Cell, 90, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(2)).withFrom(93).withTo(90)); // P2 shoots at 45 game.apply(context, new Move( new ActionAdd(null, 45, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(45).withTo(45)); // suppose that we tried moving from 3 to 0... TIntArrayList activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 3, Constants.UNDEFINED, SiteType.Cell, 0, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1) ).withFrom(3).withTo(0).withMover(1), false ); // then we should have 6 active features: // 0: move to empty position // 4: move next to edge // 5: move into corner // 6: move next to a non-empty position // 11: move from position next to edge // 15: connectivity 4 //System.out.println(activeFeatures); assertEquals(activeFeatures.size(), 6); assert activeFeatures.contains(0); assert activeFeatures.contains(4); assert activeFeatures.contains(5); assert activeFeatures.contains(6); assert activeFeatures.contains(11); assert activeFeatures.contains(15); // suppose that we tried moving from 3 to 30... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 3, Constants.UNDEFINED, SiteType.Cell, 30, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1)).withFrom(3).withTo(30).withMover(1), false ); // then we should have 5 active features: // 0: move to empty position // 4: move next to edge // 6: move next to a non-empty position // 11: move from position next to edge // 15: connectivity 4 assert activeFeatures.size() == 5; assert activeFeatures.contains(0); assert activeFeatures.contains(4); assert activeFeatures.contains(6); assert activeFeatures.contains(11); assert activeFeatures.contains(15); // suppose that we tried moving from 35 to 32... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 35, Constants.UNDEFINED, SiteType.Cell, 32, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1) ).withFrom(35).withTo(32).withMover(1), false ); // then we should have 5 active features: // 0: move to empty position // 9: move from position next to enemy // 10: move from position next to arrow // 13: move from position next to where opponent just shot // 15: connectivity 4 assertEquals(activeFeatures.size(), 5); assert activeFeatures.contains(0); assert activeFeatures.contains(9); assert activeFeatures.contains(10); assert activeFeatures.contains(13); assert activeFeatures.contains(15); // suppose that we tried moving from 35 to 44... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 35, Constants.UNDEFINED, SiteType.Cell, 44, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1) ).withFrom(35).withTo(44).withMover(1), false ); // then we should have 8 active features: // 0: move to empty position // 3: move next to arrow // 6: move next to a non-empty position // 9: move from position next to enemy // 10: move from position next to arrow // 13: move from position next to where opponent just shot // 14: move to position next to where opponent just shot // 15: connectivity 4 assertEquals(activeFeatures.size(), 8); assert activeFeatures.contains(0); assert activeFeatures.contains(3); assert activeFeatures.contains(6); assert activeFeatures.contains(9); assert activeFeatures.contains(10); assert activeFeatures.contains(13); assert activeFeatures.contains(14); assert activeFeatures.contains(15); // suppose that we tried moving from 35 to 46... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 35, Constants.UNDEFINED, SiteType.Cell, 46, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1)).withFrom(35).withTo(46).withMover(1), false ); // then we should have 9 active features: // 0: move to empty position // 2: move next to enemy // 3: move next to arrow // 6: move next to a non-empty position // 9: move from position next to enemy // 10: move from position next to arrow // 13: move from position next to where opponent just shot // 14: move to position next to where opponent just shot // 15: connectivity 4 assertEquals(activeFeatures.size(), 9); assert activeFeatures.contains(0); assert activeFeatures.contains(2); assert activeFeatures.contains(3); assert activeFeatures.contains(6); assert activeFeatures.contains(9); assert activeFeatures.contains(10); assert activeFeatures.contains(13); assert activeFeatures.contains(14); assert activeFeatures.contains(15); // suppose that we tried moving from 9 to 27... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( ActionMove.construct ( SiteType.Cell, 9, Constants.UNDEFINED, SiteType.Cell, 27, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ).withDecision(true), new ActionSetNextPlayer(1)).withFrom(9).withTo(27).withMover(1), false ); // then we should have 4 active features: // 0: move to empty position // 11: move from position next to edge // 12: move from corner // 15: connectivity 4 assertEquals(activeFeatures.size(), 4); assert activeFeatures.contains(0); assert activeFeatures.contains(11); assert activeFeatures.contains(12); assert activeFeatures.contains(15); } @Test public void testB() { final Game game = GameLoader.loadGameFromName("Amazons.lud"); // generate handcrafted feature set (just a single feature) final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString("rel:from=<{0.0}>:to=<{}>:pat=<refl=true,rots=all,els=[!-{0.25,0.0,0.0,0.0}, #{0.0,0.5,0.0,0.0,0.0}]>")); final BaseFeatureSet featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // P1 moves from 39 to 37 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 39, Constants.UNDEFINED, SiteType.Cell, 37, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(1)).withFrom(39).withTo(37).withMover(1)); // P1 shoots at 97 game.apply(context, new Move( new ActionAdd(null, 97, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(97).withTo(97).withMover(1)); // P2 moves from 96 to 36 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 96, Constants.UNDEFINED, SiteType.Cell, 36, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(2)).withFrom(96).withTo(36).withMover(2)); // P2 shoots at 35 game.apply(context, new Move( new ActionAdd(null, 35, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(35).withTo(35).withMover(2)); // P1 moves from 30 to 32 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 30, Constants.UNDEFINED, SiteType.Cell, 32, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(1)).withFrom(30).withTo(32).withMover(1)); // P1 shoots at 34 game.apply(context, new Move( new ActionAdd(null, 34, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(34).withTo(34).withMover(1)); // P2 moves from 93 to 83 game.apply(context, new Move( ActionMove.construct(SiteType.Cell, 93, Constants.UNDEFINED, SiteType.Cell, 83, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false) .withDecision(true), new ActionSetNextPlayer(2)).withFrom(93).withTo(83).withMover(2)); // P2 shoots at 89 game.apply(context, new Move( new ActionAdd(null, 89, 3, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withFrom(89).withTo(89).withMover(2)); // go through all legal moves for (final Move move : game.moves(context).moves()) { final int lastFrom = FeatureUtils.fromPos(trial.lastMove()); final int lastTo = FeatureUtils.toPos(trial.lastMove()); final int from = FeatureUtils.fromPos(move); final int to = FeatureUtils.toPos(move); final List<FeatureInstance> activeInstances = featureSet.getActiveSpatialFeatureInstances(context.state(), lastFrom, lastTo, from, to, 1); if (from == 3 && to == 2) { assert (activeInstances.size() == 1); } else if (from == 6 && to == 7) { assert (activeInstances.size() == 1); } else if (from == 37 && to == 38) { assert (activeInstances.size() == 1); } else if (from == 37 && to == 27) { assert (activeInstances.size() == 1); } else if (from == 32 && to == 22) { assert (activeInstances.size() == 1); } else if (from == 32 && to == 31) { assert (activeInstances.size() == 1); } else { if (!activeInstances.isEmpty()) { System.out.println("Active instances for " + move + " = " + activeInstances); for (final FeatureInstance instance : activeInstances) { System.out.println("instance = " + instance); } } assert (activeInstances.isEmpty()); } } } }
17,771
36.179916
170
java
Ludii
Ludii-master/Player/test/features/TestFeatureCombinations.java
package features; import static org.junit.Assert.fail; import java.util.List; import org.junit.Test; import features.spatial.Pattern; import features.spatial.RelativeFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.elements.FeatureElement.ElementType; import features.spatial.elements.RelativeFeatureElement; import features.spatial.instances.FeatureInstance; import game.Game; import game.types.board.SiteType; import other.GameLoader; import other.context.Context; import other.state.container.ContainerState; import other.trial.Trial; @SuppressWarnings("static-method") public class TestFeatureCombinations { @Test public void testA() { final Game game = GameLoader.loadGameFromName("Breakthrough.lud"); // active feature A = rel:from=<{}>:pat=<refl=true,rots=all,els=[f{0.0,0.25}]> // rot A = 0.25 // ref A = 1 // anchor A = 22 // active feature B = rel:to=<{}>:pat=<refl=true,rots=all,els=[e{0.0,0.0}]> // rot B = 0.0 // ref B = 1 // anchor B = 29 final Pattern patternA = new Pattern(new RelativeFeatureElement(ElementType.Friend, new Walk(0.f, 0.25f))); final SpatialFeature featureA = new RelativeFeature(patternA, null, new Walk()); final FeatureInstance instanceA = new FeatureInstance(featureA, 22, 1, 0.25f, SiteType.Cell); final Pattern patternB = new Pattern(new RelativeFeatureElement(ElementType.Enemy, new Walk(0.f, 0.f))); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), null); final FeatureInstance instanceB = new FeatureInstance(featureB, 29, 1, 0.f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern( new RelativeFeatureElement(ElementType.Friend, new Walk(0.25f, 0.25f)), new RelativeFeatureElement(ElementType.Enemy, new Walk(0.f, -0.25f, 0.25f, 0.f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(0.f, -0.25f), new Walk()); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { fail(targetInstance + " was not a new instance!"); } } } @Test public void testB() { final Game game = GameLoader.loadGameFromName("Breakthrough.lud"); // active feature A = rel:from=<{}>:pat=<refl=true,rots=all,els=[e{0.0,0.0,0.0}]> // rot A = 0.75 // ref A = 1 // anchor A = 38 // active feature B = rel:to=<{}>:pat=<refl=true,rots=all,els=[-{0.0,0.0}]> // rot B = 0.5 // ref B = 1 // anchor B = 45 final Pattern patternA = new Pattern(new RelativeFeatureElement(ElementType.Enemy, new Walk(0.f, 0.f, 0.f))); final SpatialFeature featureA = new RelativeFeature(patternA, null, new Walk()); final FeatureInstance instanceA = new FeatureInstance(featureA, 38, 1, 0.75f, SiteType.Cell); final Pattern patternB = new Pattern(new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.f))); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), null); final FeatureInstance instanceB = new FeatureInstance(featureB, 45, 1, 0.5f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern( new RelativeFeatureElement(ElementType.Enemy, new Walk(-0.25f, 0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, -0.25f, -0.25f, 0.f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(0.f, -0.25f), new Walk()); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { System.out.println("target feature = " + targetFeature); System.out.println("new feature = " + newFeature); System.out.println("num target instances = " + targetInstances.size()); System.out.println("num new instances = " + newInstances.size()); fail(targetInstance + " was not a new instance!"); } } } @Test public void testC() { final Game game = GameLoader.loadGameFromName("Amazons.lud"); // active feature A = rel:to=<{}>:pat=<refl=true,rots=all,els=[-{0.0,0.0}]> // rot A = 0.75 // ref A = 1 // anchor A = 39 // active feature B = rel:from=<{0.0,0.25}>:to=<{}>:pat=<refl=true,rots=all,els=[!-{0.0,0.0}, !-{0.0,0.25,-0.25,0.25}]> // rot B = 0.75 // ref B = -1 // anchor B = 39 final Pattern patternA = new Pattern(new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.f))); final SpatialFeature featureA = new RelativeFeature(patternA, new Walk(), null); final FeatureInstance instanceA = new FeatureInstance(featureA, 39, 1, 0.75f, SiteType.Cell); final Pattern patternB = new Pattern( new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f, 0.25f, -0.25f, 0.25f))); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), new Walk(0.f, 0.25f)); final FeatureInstance instanceB = new FeatureInstance(featureB, 39, -1, 0.75f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern( new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.5f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.5f, 0.25f, -0.25f, 0.25f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(), new Walk(0.5f, 0.25f)); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(targetInstance + " was not a new instance!"); } } } @Test public void testD() { final Game game = GameLoader.loadGameFromName("Amazons.lud"); // active feature A = rel:from=<{0.5,-0.25}>:to=<{}>:pat=<refl=true,rots=all,els=[-{0.25,0.0}, -{0.5,0.25,-0.25,0.0,0.0,0.0}, !-{0.0,0.25,1.25,0.0,0.0}]> // rot A = 0.0 // ref A = -1 // anchor A = 55 // active feature B = rel:from=<{}>:to=<{0.0,0.25}>:pat=<refl=true,rots=all,els=[!-{-0.25,0.0,0.0,0.0}, -{0.0,0.25,-0.25,0.0,0.0,0.0}]> // rot B = 0.75 // ref B = -1 // anchor B = 44 final Pattern patternA = new Pattern( new RelativeFeatureElement(ElementType.Empty, new Walk(0.25f, 0.f)), new RelativeFeatureElement(ElementType.Empty, new Walk(0.5f, 0.25f, -0.25f, 0.f, 0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f, 0.25f, 1.25f, 0.f, 0.f)) ); final SpatialFeature featureA = new RelativeFeature(patternA, new Walk(), new Walk(0.5f, -0.25f)); final FeatureInstance instanceA = new FeatureInstance(featureA, 55, -1, 0.f, SiteType.Cell); final Pattern patternB = new Pattern( new RelativeFeatureElement(ElementType.Empty, true, new Walk(-0.25f, 0.f, 0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.25f, -0.25f, 0.f, 0.f, 0.f)) ); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(0.f, 0.25f), new Walk()); final FeatureInstance instanceB = new FeatureInstance(featureB, 44, -1, 0.75f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern( new RelativeFeatureElement(ElementType.Empty, new Walk(-0.25f, 0.f)), new RelativeFeatureElement(ElementType.Empty, new Walk(0.25f, 0.f, 0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f, -0.25f, -0.25f, 0.f, 0.f)), new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.5f, 0.f, 0.f, 0.f, 0.f, 0.25f)), new RelativeFeatureElement(ElementType.Empty, new Walk(0.5f, 0.f, 0.f, 0.f, 0.f, -0.25f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(), new Walk(0.5f, 0.25f)); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(targetInstance + " was not a new instance!"); } } } @Test public void testE() { final Game game = GameLoader.loadGameFromName("Amazons.lud"); // Generated inconsistent pattern: refl=true,rots=all,els=[-{0.0,-0.25}, e{0.0,0.5,0.0}, e{0.0,-0.25}] // active feature A = rel:from=<{}>:pat=<refl=true,rots=all,els=[-{0.0,0.25}]> // rot A = 0.25 // ref A = -1 // anchor A = 91 // active feature B = rel:to=<{}>:pat=<refl=true,rots=all,els=[e{0.0,0.0}, e{0.25}]> // rot B = 0.25 // ref B = 1 // anchor B = 92 final Pattern patternA = new Pattern( new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.25f)) ); final SpatialFeature featureA = new RelativeFeature(patternA, null, new Walk()); final FeatureInstance instanceA = new FeatureInstance(featureA, 91, -1, 0.25f, SiteType.Cell); final Pattern patternB = new Pattern( new RelativeFeatureElement(ElementType.Enemy, new Walk(0.f, 0.f)), new RelativeFeatureElement(ElementType.Enemy, new Walk(0.25f)) ); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), null); final FeatureInstance instanceB = new FeatureInstance(featureB, 92, 1, 0.25f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern( new RelativeFeatureElement(ElementType.Empty, new Walk(-0.25f, -0.25f)), new RelativeFeatureElement(ElementType.Enemy, new Walk(0.25f, 0.25f)), new RelativeFeatureElement(ElementType.Enemy, new Walk(0.25f, 0.f, 0.f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(0.25f), new Walk()); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(targetInstance + " was not a new instance!"); } } } @Test public void testF() { final Game game = GameLoader.loadGameFromName("Tic-Tac-Toe.lud"); // Instance A: [Move to 1: (response to last move to 5)] [anchor=1, ref=1, rot=0,00] [rel:last_to=<{0,1/4}>:to=<{}>:pat=<els=[]>] // Instance B: [Move to 1: 4 must NOT be empty, ] [anchor=1, ref=1, rot=0,00] [rel:to=<{}>:pat=<els=[!-{0}]>] into rel:to=<{}>:pat=<els=[!-{0}]> // // Expect to combine into feature: to={}, last_to={0, 1/4}, !-{0} final Pattern patternA = new Pattern(); final SpatialFeature featureA = new RelativeFeature(patternA, new Walk(), null, new Walk(0.f, 0.25f), null); final FeatureInstance instanceA = new FeatureInstance(featureA, 1, 1, 0.f, SiteType.Cell); final Pattern patternB = new Pattern ( new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f)) ); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), null); final FeatureInstance instanceB = new FeatureInstance(featureB, 1, 1, 0.f, SiteType.Cell); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern ( new RelativeFeatureElement(ElementType.Empty, true, new Walk(0.f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(), null, new Walk(0.f, 0.25f), null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); fail(targetInstance + " was not a new instance!"); } } } @Test public void testG() { final Game game = GameLoader.loadGameFromName("Ko-app-paw-na.lud"); // active feature A = rel:last_to=<{0,1/4}>:from=<{}>:to=<{0}>:pat=<els=[R0{0,0,1/4}]> // rot A = 0.0 // ref A = -1 // anchor A = 13 // active feature B = rel:to=<{}>:pat=<els=[-{0,-1/4}, !R0{1/4,1/4}]> // rot B = 0.75 // ref B = -1 // anchor B = 18 // A and B have different anchors, and both have region proximity requirements. We // expect only the R0 test from A to be preserved, and the one from B to be discarded final Pattern patternA = new Pattern(new RelativeFeatureElement(ElementType.RegionProximity, new Walk(0.f, 0.f, 0.25f), 0)); final SpatialFeature featureA = new RelativeFeature(patternA, new Walk(0.f), new Walk(), new Walk(0.f, 0.25f), null); final FeatureInstance instanceA = new FeatureInstance(featureA, 13, -1, 0.f, SiteType.Vertex); final Pattern patternB = new Pattern ( new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, -0.25f)), new RelativeFeatureElement(ElementType.RegionProximity, true, new Walk(0.25f, 0.25f), 0) ); final SpatialFeature featureB = new RelativeFeature(patternB, new Walk(), null); final FeatureInstance instanceB = new FeatureInstance(featureB, 18, -1, 0.75f, SiteType.Vertex); final SpatialFeature newFeature = SpatialFeature.combineFeatures(game, instanceA, instanceB); final Pattern targetPattern = new Pattern ( new RelativeFeatureElement(ElementType.RegionProximity, new Walk(0.f, 0.f, -0.25f), 0), new RelativeFeatureElement(ElementType.Empty, new Walk(0.f, 0.25f, 0.25f)) ); final SpatialFeature targetFeature = new RelativeFeature(targetPattern, new Walk(0.f), new Walk(), new Walk(0.f, -0.25f), null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final ContainerState containerState = context.containerState(0); final List<FeatureInstance> newInstances = newFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); final List<FeatureInstance> targetInstances = targetFeature.instantiateFeature(game, containerState, 1, -1, -1, -1, -1, -1); if (newInstances.size() != targetInstances.size()) { System.out.println("newFeature = " + newFeature); System.out.println("targetFeature = " + targetFeature); } assert(newInstances.size() == targetInstances.size()); for (final FeatureInstance newInstance : newInstances) { boolean found = false; for (final FeatureInstance targetInstance : targetInstances) { if (newInstance.functionallyEquals(targetInstance)) { found = true; break; } } if (!found) { fail(newInstance + " was not a target instance!"); } } for (final FeatureInstance targetInstance : targetInstances) { boolean found = false; for (final FeatureInstance newInstance : newInstances) { if (targetInstance.functionallyEquals(newInstance)) { found = true; break; } } if (!found) { fail(targetInstance + " was not a new instance!"); } } } }
22,476
32.648204
155
java
Ludii
Ludii-master/Player/test/features/TestGomokuFeatures.java
package features; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.spatial.SpatialFeature; import game.Game; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.collections.FastArrayList; import other.GameLoader; import other.action.move.ActionAdd; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit test for features in Gomoku * * @author Dennis Soemers */ public class TestGomokuFeatures { @Test @SuppressWarnings("static-method") public void test() { // Default board size = 15x15 vertices final Game game = GameLoader.loadGameFromName("Gomoku.lud"); // generate handcrafted feature set final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}]>:comment=\"play in empty position\"")); // 0 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}]>:comment=\"play next to edge of board\"")); // 1 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0}]>:comment=\"play next to friendly piece\"")); // 2 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, e{0.0}]>:comment=\"play next to enemy piece\"")); // 3 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0, 0.25}]>:comment=\"play diagonally adjacent to friend\"")); // 4 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}, #{0.25}]>:comment=\"play in corner of board\"")); // 5 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N4{}]>:comment=\"Every to-position has connectivity 4.\"")); // 6 features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N8{}]>:comment=\"No to-position has connectivity 8.\"")); // 7 // Randomly pick one of the feature set implementations to test final BaseFeatureSet featureSet; final double rand = ThreadLocalRandom.current().nextDouble(); if (rand < 0.25) featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); else if (rand < 0.5) featureSet = JITSPatterNetFeatureSet.construct(new ArrayList<AspatialFeature>(), features); else if (rand < 0.75) featureSet = new LegacyFeatureSet(new ArrayList<AspatialFeature>(), features); else featureSet = new NaiveFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // In the initial game state: // - Feature 0 is active for ALL moves (15 * 15 = 225) // - Feature 1 is active for 15 + 15 + 13 + 13 = 56 moves (along edges) // - Feature 5 is active for 4 moves (in corners) // - Feature 6 is active for ALL moves (15 * 15 = 225) final int[] initialStateNumActives = new int[featureSet.spatialFeatures().length]; final FastArrayList<Move> legalMoves = game.moves(context).moves(); final TIntArrayList[] initialStateActiveFeatures = featureSet.computeSparseSpatialFeatureVectors(context, legalMoves, false); for (final TIntArrayList sparse : initialStateActiveFeatures) { for (int i = 0; i < sparse.size(); ++i) { initialStateNumActives[sparse.getQuick(i)] += 1; } } assertEquals(initialStateNumActives[0], 225); assertEquals(initialStateNumActives[1], 56); assertEquals(initialStateNumActives[2], 0); assertEquals(initialStateNumActives[3], 0); assertEquals(initialStateNumActives[4], 0); assertEquals(initialStateNumActives[5], 4); assertEquals(initialStateNumActives[6], 225); assertEquals(initialStateNumActives[7], 0); // P1 places a piece at vertex 16 game.apply(context, new Move(new ActionAdd(SiteType.Vertex, 16, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)).withFrom(16).withTo(16).withMover(1)); // Suppose that P2 tried placing at vertex 15 next... TIntArrayList activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( SiteType.Vertex, 15, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withFrom(15).withTo(15).withMover(2), false ); // then we should have 4 active features: // 0: empty position // 1: next to edge // 3: next to enemy // 6: connectivity = 4 assert activeFeatures.size() == 4; assert activeFeatures.contains(0); assert activeFeatures.contains(1); assert activeFeatures.contains(3); assert activeFeatures.contains(6); // Suppose that P2 tried placing at vertex 0 next... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( SiteType.Vertex, 0, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withFrom(0).withTo(0).withMover(2), false ); // then we should have 4 active features: // 0: empty position // 1: next to edge // 5: in corner // 6: connectivity = 4 assert activeFeatures.size() == 4; assert activeFeatures.contains(0); assert activeFeatures.contains(1); assert activeFeatures.contains(5); assert activeFeatures.contains(6); // Suppose that P2 tried placing at vertex 32 next... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( SiteType.Vertex, 32, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withFrom(32).withTo(32).withMover(2), false ); // then we should have 2 active features: // 0: empty position // 6: connectivity = 4 assert activeFeatures.size() == 2; assert activeFeatures.contains(0); assert activeFeatures.contains(6); // P2 places a piece at vertex 0 game.apply(context, new Move(new ActionAdd(SiteType.Vertex, 0, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)).withFrom(0).withTo(0).withMover(2)); // Suppose that P1 tried placing at vertex 32 next... activeFeatures = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( SiteType.Vertex, 32, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withFrom(32).withTo(32).withMover(1), false ); // then we should have 3 active features: // 0: empty position // 4: diagonally adjacent to friend // 6: connectivity = 4 assert activeFeatures.size() == 3; assert activeFeatures.contains(0); assert activeFeatures.contains(4); assert activeFeatures.contains(6); } }
7,610
33.912844
167
java
Ludii
Ludii-master/Player/test/features/TestHexFeatures.java
package features; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.spatial.SpatialFeature; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.GameLoader; import other.action.move.ActionAdd; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit test for testing some handcrafted active features in Hex * * @author Dennis Soemers */ public class TestHexFeatures { @Test @SuppressWarnings("static-method") public void test() { final Game game = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); // generate handcrafted feature set final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}]>:comment=\"play in empty position\"")); features.add((SpatialFeature)Feature.fromString("rel:last_to=<{0.16666667}>:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0}, f{0.33333334}]>:comment=\"reactive bridge completion\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0}, f{0.33333334}]>:comment=\"proactive bridge completion\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, f{0.0}]>:comment=\"play next to friend\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, e{0.0}]>:comment=\"play next to enemy\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}]>:comment=\"play next to off-board\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N6{}]>:comment=\"To-positions with connectivity 6.\"")); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<refl=true,rots=all,els=[N12{}]>:comment=\"No to-position has connectivity 12.\"")); // Randomly pick one of the feature set implementations to test final BaseFeatureSet featureSet; final double rand = ThreadLocalRandom.current().nextDouble(); if (rand < 0.25) featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); else if (rand < 0.5) featureSet = JITSPatterNetFeatureSet.construct(new ArrayList<AspatialFeature>(), features); else if (rand < 0.75) featureSet = new LegacyFeatureSet(new ArrayList<AspatialFeature>(), features); else featureSet = new NaiveFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // P1 plays above 60 game.apply(context, new Move( new ActionAdd(null, 80, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(80).withFrom(80).withMover(1)); // P2 plays all the way in west corner (unimportant move) game.apply(context, new Move( new ActionAdd(null, 55, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(55).withFrom(55).withMover(2)); // P1 plays lower right of 60 game.apply(context, new Move( new ActionAdd(null, 50, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(50).withFrom(50).withMover(1)); // P2 plays top right of 60, threatening bridge between 80 and 50 game.apply(context, new Move( new ActionAdd(null, 71, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(71).withFrom(71).withMover(2)); // compute active features for P1 moving to 60 (completing the threatened bridge) final TIntArrayList featuresMoveTo60 = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, 60, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(60).withFrom(60).withMover(1), false ); // should have 6 active features: // 0: play in empty position // 1: reactive bridge completion // 2: proactive bridge completion // 3: play next to friend // 4: play next to enemy // 6: connectivity = 6 assert featuresMoveTo60.size() == 6; assert featuresMoveTo60.contains(0); assert featuresMoveTo60.contains(1); assert featuresMoveTo60.contains(2); assert featuresMoveTo60.contains(3); assert featuresMoveTo60.contains(4); assert featuresMoveTo60.contains(6); // playing in the following positions should have only 3 active features: // 0: play in empty position // 3: play next to friend // 6: connectivity = 6 for (final int pos : new int[]{70, 88, 96, 41, 32, 40}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 3; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(3); assert featuresMoveToPos.contains(6); } // playing in the following positions should have only 4 active features: // 0: play in empty position // 3: play next to friend // 4: play next to enemy // 6: connectivity = 6 for (final int pos : new int[]{89, 61}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 4; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(3); assert featuresMoveToPos.contains(4); assert featuresMoveToPos.contains(6); } // playing in the following positions should have only 3 active features: // 0: play in empty position // 4: play next to enemy // 6: connectivity = 6 for (final int pos : new int[]{81}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 3; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(4); assert featuresMoveToPos.contains(6); } // playing in the following positions should have 3 active features: // 0: play in empty position // 5: play in off-board position // 6: connectivity = 6 for ( final int pos : new int[] { 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 1, 3, 6, 10, 15, 21, 28, 36, 76, 85, 93, 100, 106, 111, 115, 118, 120, 75, 84, 92, 99, 105, 110, 114, 117, 119 } ) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 3; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(5); assert featuresMoveToPos.contains(6); } // playing in the following position should have 3 active features: // 0: play in empty position // 5: play in off-board position // 6: connectivity = 6 for (final int pos : new int[]{ 65 }) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 3; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(5); assert featuresMoveToPos.contains(6); } // playing in the following positions should have 4 active features: // 0: play in empty position // 4: play next to enemy // 5: play in off-board position // 6: connectivity = 6 for (final int pos : new int[]{45, 66}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 4; assert featuresMoveToPos.contains(0); assert featuresMoveToPos.contains(4); assert featuresMoveToPos.contains(5); assert featuresMoveToPos.contains(6); } // the following positions should be occupied and not have any active features (except for connectivity 6) for (final int pos : new int[]{50, 71, 80}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 1; assert featuresMoveToPos.contains(6); } // the following position should be occupied and not have any active features (except for connectivity 6) for (final int pos : new int[]{55}) { final TIntArrayList featuresMoveToPos = featureSet.computeSparseSpatialFeatureVector ( context, new Move ( new ActionAdd ( null, pos, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(pos).withFrom(pos).withMover(1), false ); assert featuresMoveToPos.size() == 1; assert featuresMoveToPos.contains(6); } } }
11,083
31.034682
186
java
Ludii
Ludii-master/Player/test/features/TestKharbagaFeatures.java
package features; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.spatial.SpatialFeature; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.collections.FastArrayList; import other.GameLoader; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit test for features in Kharbaga * * @author Dennis Soemers */ public class TestKharbagaFeatures { @Test @SuppressWarnings("static-method") public void test() { final Game game = GameLoader.loadGameFromName("Kharbaga.lud"); // generate handcrafted feature set final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, N8{}]>:comment=\"move to empty N8 position\"")); // 0 features.add((SpatialFeature)Feature.fromString( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, N8{}, #{0.0}]>:comment=\"move to N8 pos at to edge of board\"")); // 1 features.add((SpatialFeature)Feature.fromString( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, N8{}, f{0.0}]>:comment=\"move to N8 pos next to friendly piece\"")); // 2 features.add((SpatialFeature)Feature.fromString( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, N8{}, e{0.0}]>:comment=\"move to N8 pos next to enemy piece\"")); // 3 features.add((SpatialFeature)Feature.fromString( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, #{0.0}, #{0.25}]>:comment=\"move to corner of board\"")); // 4 features.add ( (SpatialFeature)Feature.fromString // 5 ( "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}, N8{}, f{0.0}, f{1/8}, e{2/8}, e{3/8}, e{4/8}, e{5/8}, f{6/8}, f{7/8}]>" + ":comment=\"Move to 8-connected vertex with 4 adjacent friends and 4 adjacent enemies (e.g. opening move)\"" ) ); // Randomly pick one of the feature set implementations to test final BaseFeatureSet featureSet; final double rand = ThreadLocalRandom.current().nextDouble(); if (rand < 0.25) featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); else if (rand < 0.5) featureSet = JITSPatterNetFeatureSet.construct(new ArrayList<AspatialFeature>(), features); else if (rand < 0.75) featureSet = new LegacyFeatureSet(new ArrayList<AspatialFeature>(), features); else featureSet = new NaiveFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // In the initial game state: // - Feature 0, 2, 3, and 5 should all be active for ALL moves (= 3) // - Features 1 and 4 should not be active for ANY move final int[] initialStateNumActives = new int[featureSet.spatialFeatures().length]; final FastArrayList<Move> legalMoves = game.moves(context).moves(); final TIntArrayList[] initialStateActiveFeatures = featureSet.computeSparseSpatialFeatureVectors(context, legalMoves, false); //System.out.println("legal moves = " + legalMoves); for (final TIntArrayList sparse : initialStateActiveFeatures) { //System.out.println("sparse active features = " + sparse); for (int i = 0; i < sparse.size(); ++i) { initialStateNumActives[sparse.getQuick(i)] += 1; } } assert initialStateNumActives[0] == 3; assert initialStateNumActives[1] == 0; assert initialStateNumActives[2] == 3; assert initialStateNumActives[3] == 3; assert initialStateNumActives[4] == 0; assert initialStateNumActives[5] == 3; } }
4,007
36.811321
127
java
Ludii
Ludii-master/Player/test/features/TestSPatterNetFeatureSet.java
package features; import static org.junit.Assert.assertEquals; import java.util.BitSet; import java.util.List; import org.junit.Test; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.generation.AtomicFeatureGenerator; import features.spatial.FeatureUtils; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.collections.FastArrayList; import other.GameLoader; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Tests the SPatterNetFeatureSet with atomic features by running random trials and ensuring * that active feature instances and active features always match. * * @author Dennis Soemers */ public class TestSPatterNetFeatureSet { private static final String[] GAMES = { "Chess.lud", // Many piece types "Amazons.lud", // Neutral piece "Feed the Ducks.lud", // Hex cells, also a neutral piece (I think?) "Kensington.lud", // Weird board "Xiangqi.lud", // Like chess, but on vertices "Hex.lud" // Always a nice game }; private static final int MAX_MOVES_PER_TRIAL = 200; @Test @SuppressWarnings("static-method") public void test() { for (final String gameName : GAMES) { System.out.println("Testing game: " + gameName + "..."); final Game game = GameLoader.loadGameFromName(gameName); final AtomicFeatureGenerator featureGenerator = new AtomicFeatureGenerator(game, 2, 4); final SPatterNetFeatureSet featureSet = new SPatterNetFeatureSet(featureGenerator.getAspatialFeatures(), featureGenerator.getSpatialFeatures()); final JITSPatterNetFeatureSet jitFeatureSet = JITSPatterNetFeatureSet.construct(featureGenerator.getAspatialFeatures(), featureGenerator.getSpatialFeatures()); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final int[] playersArray = new int[game.players().count()]; for (int i = 0; i < playersArray.length; ++i) { playersArray[i] = i + 1; } featureSet.init(game, playersArray, null); jitFeatureSet.init(game, playersArray, null); int numMovesPlayed = 0; while (!trial.over() && numMovesPlayed < MAX_MOVES_PER_TRIAL) { ++numMovesPlayed; final FastArrayList<Move> legalMoves = game.moves(context).moves(); final int lastFrom = FeatureUtils.fromPos(trial.lastMove()); final int lastTo = FeatureUtils.toPos(trial.lastMove()); for (final Move move : legalMoves) { final int from = FeatureUtils.fromPos(move); final int to = FeatureUtils.toPos(move); final List<FeatureInstance> activeInstances = featureSet.getActiveSpatialFeatureInstances(context.state(), lastFrom, lastTo, from, to, move.mover()); final TIntArrayList activeFeatureIndices = featureSet.getActiveSpatialFeatureIndices ( context.state(), lastFrom, lastTo, from, to, move.mover(), Math.random() < 0.5 ? true : false ); final List<FeatureInstance> jitActiveInstances = jitFeatureSet.getActiveSpatialFeatureInstances(context.state(), lastFrom, lastTo, from, to, move.mover()); final TIntArrayList jitActiveFeatureIndices = jitFeatureSet.getActiveSpatialFeatureIndices ( context.state(), lastFrom, lastTo, from, to, move.mover(), Math.random() < 0.5 ? true : false ); // Convert instances to bitset representation, retaining only features (not caring about instances anymore) final BitSet instancesBitSet = new BitSet(); for (final FeatureInstance instance : activeInstances) { instancesBitSet.set(instance.feature().spatialFeatureSetIndex()); } final BitSet jitInstancesBitSet = new BitSet(); for (final FeatureInstance instance : jitActiveInstances) { jitInstancesBitSet.set(instance.feature().spatialFeatureSetIndex()); } // Same with the feature indices list final BitSet featuresBitSet = new BitSet(); for (int i = 0; i < activeFeatureIndices.size(); ++i) { featuresBitSet.set(activeFeatureIndices.getQuick(i)); } final BitSet jitFeaturesBitSet = new BitSet(); for (int i = 0; i < jitActiveFeatureIndices.size(); ++i) { jitFeaturesBitSet.set(jitActiveFeatureIndices.getQuick(i)); } // The two bitsets must be equal assertEquals(instancesBitSet, featuresBitSet); assertEquals(jitInstancesBitSet, jitFeaturesBitSet); // And also equal between JIT and non-JIT assertEquals(instancesBitSet, jitInstancesBitSet); } // Randomly move on to next game state context.model().startNewStep(context, null, 0.0); } } } }
4,849
33.397163
118
java
Ludii
Ludii-master/Player/test/features/TestYavalathFeatures.java
package features; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.feature_sets.LegacyFeatureSet; import features.feature_sets.NaiveFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.feature_sets.network.SPatterNetFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import main.Constants; import other.GameLoader; import other.action.move.ActionAdd; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit test for testing some handcrafted active features in Hex * * @author Dennis Soemers */ public class TestYavalathFeatures { @SuppressWarnings("static-method") @Test public void test() { final Game game = GameLoader.loadGameFromName("/Yavalath.lud"); // generate handcrafted feature set final List<SpatialFeature> features = new ArrayList<SpatialFeature>(); features.add((SpatialFeature)Feature.fromString("rel:to=<{}>:pat=<els=[f{0,1/6}]>")); // Randomly pick one of the feature set implementations to test final BaseFeatureSet featureSet; final double rand = ThreadLocalRandom.current().nextDouble(); if (rand < 0.25) featureSet = new SPatterNetFeatureSet(new ArrayList<AspatialFeature>(), features); else if (rand < 0.5) featureSet = JITSPatterNetFeatureSet.construct(new ArrayList<AspatialFeature>(), features); else if (rand < 0.75) featureSet = new LegacyFeatureSet(new ArrayList<AspatialFeature>(), features); else featureSet = new NaiveFeatureSet(new ArrayList<AspatialFeature>(), features); featureSet.init(game, new int[] {1, 2}, null); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // P1 plays in 60 (irrelevant) game.apply(context, new Move( new ActionAdd(null, 60, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(60).withFrom(60).withMover(1)); // P2 plays in 11 game.apply(context, new Move( new ActionAdd(null, 11, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(11).withFrom(11).withMover(2)); // P1 plays in 56 (irrelevant) game.apply(context, new Move( new ActionAdd(null, 56, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(56).withFrom(56).withMover(1)); // P2 plays in 4 game.apply(context, new Move( new ActionAdd(null, 4, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(4).withFrom(4).withMover(2)); // P1 plays in 58 (irrelevant) game.apply(context, new Move( new ActionAdd(null, 58, 1, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)) .withTo(58).withFrom(58).withMover(1)); // Compute feature instances for P2 moving to 27 final Move move27 = new Move ( new ActionAdd ( null, 27, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(27).withFrom(27).withMover(2); final List<FeatureInstance> instances27 = featureSet.getActiveSpatialFeatureInstances ( context.state(), FeatureUtils.fromPos(context.trial().lastMove()), FeatureUtils.toPos(context.trial().lastMove()), FeatureUtils.fromPos(move27), FeatureUtils.toPos(move27), 2 ); assertEquals(2, instances27.size()); // Compute feature instances for P2 moving to 16 final Move move16 = new Move ( new ActionAdd ( null, 16, 2, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null ).withDecision(true) ).withTo(16).withFrom(16).withMover(2); final List<FeatureInstance> instances16 = featureSet.getActiveSpatialFeatureInstances ( context.state(), FeatureUtils.fromPos(context.trial().lastMove()), FeatureUtils.toPos(context.trial().lastMove()), FeatureUtils.fromPos(move16), FeatureUtils.toPos(move16), 2 ); assertEquals(2, instances16.size()); } }
4,521
30.402778
96
java
Ludii
Ludii-master/Player/test/games/BoardDistanceTest.java
package games; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.junit.Test; import game.Game; import game.equipment.container.board.Board; //import game.util.graph.Graph; import other.GameLoader; import other.topology.Cell; import other.topology.Vertex; //import game.util.graph.Vertex; //import game.util.graph.Face; //----------------------------------------------------------------------------- /** * Check board distance metric. * * @author cambolbro */ public class BoardDistanceTest { @Test @SuppressWarnings("static-method") public void test() { final String[] gameNames = { "Chess.lud", "Halma.lud", "Tic-Tac-Toe.lud", "Mu Torere.lud", "International Draughts.lud", }; for (int a = 0; a < gameNames.length - 1; a++) { final Game gameA = GameLoader.loadGameFromName(gameNames[a]); final Board boardA = gameA.board(); for (int b = a + 1; b < gameNames.length; b++) { final Game gameB = GameLoader.loadGameFromName(gameNames[b]); final Board boardB = gameB.board(); System.out.println("\nComparing games " + gameNames[a] + " and " + gameNames[b] + "..."); System.out.println("Game A graph: " + boardA.topology().vertices().size() + " verts."); System.out.println("Game B graph: " + boardB.topology().vertices().size() + " verts."); System.out.println("Distance is: " + distance(boardA, boardB)); } } } //------------------------------------------------------------------------- public static double distance(final Board boardA, final Board boardB) { // Get ordered list of degrees for vertices and faces or each board final List<Integer> verticesA = new ArrayList<>(); final List<Integer> verticesB = new ArrayList<>(); final List<Integer> cellsA = new ArrayList<>(); final List<Integer> cellsB = new ArrayList<>(); // for (final Vertex vertex : boardA.graph().vertices()) // verticesA.add(Integer.valueOf(vertex.edges().size())); // // for (final Vertex vertex : boardB.graph().vertices()) // verticesB.add(Integer.valueOf(vertex.edges().size())); // // for (final Face face : boardA.graph().faces()) // cellsA.add(Integer.valueOf(face.nbors().size())); // // for (final Face face : boardB.graph().faces()) // cellsB.add(Integer.valueOf(face.nbors().size())); for (final Vertex vertex : boardA.topology().vertices()) verticesA.add(Integer.valueOf(vertex.orthogonal().size() + vertex.diagonal().size())); //neighbours().size())); for (final Vertex vertex : boardB.topology().vertices()) verticesB.add(Integer.valueOf(vertex.orthogonal().size() + vertex.diagonal().size())); //.neighbours().size())); for (final Cell cell : boardA.topology().cells()) cellsA.add(Integer.valueOf(cell.orthogonal().size() + cell.diagonal().size())); //.neighbours().size())); for (final Cell cell : boardB.topology().cells()) cellsB.add(Integer.valueOf(cell.orthogonal().size() + cell.diagonal().size())); //.neighbours().size())); Collections.sort(verticesA); Collections.sort(verticesB); Collections.sort(cellsA); Collections.sort(cellsB); // Find closest of va:vb, va:fb, fa:va, fa:fb //System.out.println("verticesA: " + verticesA); //System.out.println("verticesB: " + verticesB); //System.out.println("cellsA: " + cellsA); //System.out.println("cellsB: " + cellsB); final double sim_V_V = similarity(verticesA, verticesB); final double sim_V_C = similarity(verticesA, cellsB); final double sim_C_V = similarity( cellsA, verticesB); final double sim_C_C = similarity( cellsA, cellsB); // final double wed_V_V = weightedEditDistance(verticesA, verticesB); final double score = Math.max(Math.max(Math.max(sim_V_V, sim_V_C), sim_C_V), sim_C_C); return score; } /** * Destructively modifies lists. * @return Similarity measure between two lists, in range 0..1. */ public static double similarity(final List<Integer> listAin, final List<Integer> listBin) { System.out.println("listAin: " + listAin); System.out.println("listBin: " + listBin); if (listAin.isEmpty() && listBin.isEmpty()) return 1; // perfect match! final List<Integer> listA = new ArrayList<>(listAin); final List<Integer> listB = new ArrayList<>(listBin); // System.out.println("listA before: " + listA); // System.out.println("listB before: " + listB); // Remove matching items from lists for (int a = listA.size() - 1; a >= 0; a--) { boolean remove = false; for (int b = listB.size() - 1; b >= 0; b--) { if (listA.get(a) == listB.get(b)) { // Remove this item from each list listB.remove(b); remove = true; break; } } if (remove) listA.remove(a); } // System.out.println("listA after: " + listA); // System.out.println("listB after: " + listB); double discrepancy = 0; for (final int a : listA) { if (listB.isEmpty()) { discrepancy += a; } else { int minDiff = 1000; // for (final int b : listB) for (final int b : listBin) { final int diff = Math.abs(a - b); if (diff < minDiff) minDiff = diff; } discrepancy += minDiff; } } for (final int b : listB) { if (listA.isEmpty()) { discrepancy += b; } else { int minDiff = 1000; // for (final int a : listA) for (final int a : listAin) { final int diff = Math.abs(a - b); if (diff < minDiff) minDiff = diff; } discrepancy += minDiff; } } discrepancy /= (listA.size() + listB.size()); final double scoreD = 1 - Math.log10(discrepancy + 1); // final List<Integer> listMin = (listA.size() <= listB.size()) ? listA : listB; // final List<Integer> listMax = (listA.size() <= listB.size()) ? listB : listA; // // for (final int a : listMax) // { // if (listMin.isEmpty()) // { // discrepancy += a; // } // else // { // // Find closest match in the other list // int minDiff = 1000; // for (final int b : listMin) // { // final int diff = Math.abs(a - b); // if (diff < minDiff) // minDiff = diff; // } // discrepancy += minDiff; // } // } // // discrepancy /= listMax.size(); // // final double scoreD = 1 - Math.log10(discrepancy + 1); // // final double ratio = Math.min(listAin.size(), listBin.size()) // / // (double)Math.max(listAin.size(), listBin.size()); final int MAX = 8; final double[] talliesA = new double[MAX + 1]; final double[] talliesB = new double[MAX + 1]; double totalA = 0; double totalB = 0; for (final int n : listAin) if (n > MAX) talliesA[MAX]++; else talliesA[n]++; for (final int n : listBin) if (n > MAX) talliesB[MAX]++; else talliesB[n]++; for (int n = 0; n < MAX + 1; n++) { totalA += talliesA[n]; totalB += talliesB[n]; } System.out.print("talliesA:"); for (int n = 0; n < MAX + 1; n++) System.out.print(" " + talliesA[n]); System.out.println(); System.out.print("talliesB:"); for (int n = 0; n < MAX + 1; n++) System.out.print(" " + talliesB[n]); System.out.println(); System.out.println("totalA=" + totalA + ", totalB=" + totalB + "."); totalA = 0; totalB = 0; for (int n = 0; n < MAX + 1; n++) { talliesA[n] = Math.log10(talliesA[n] + 1); talliesB[n] = Math.log10(talliesB[n] + 1); totalA += talliesA[n]; totalB += talliesB[n]; } System.out.print("talliesA:"); for (int n = 0; n < MAX + 1; n++) System.out.print(" " + talliesA[n]); System.out.println(); System.out.print("talliesB:"); for (int n = 0; n < MAX + 1; n++) System.out.print(" " + talliesB[n]); System.out.println(); System.out.println("totalA=" + totalA + ", totalB=" + totalB + "."); final double[] contributionsA = new double[MAX + 1]; final double[] contributionsB = new double[MAX + 1]; for (int n = 0; n < MAX + 1; n++) { contributionsA[n] = talliesA[n] / totalA; contributionsB[n] = talliesB[n] / totalB; } System.out.print("contributionsA:"); for (int n = 0; n < MAX + 1; n++) System.out.print(String.format(" %.3f", Double.valueOf(contributionsA[n]))); System.out.println(); System.out.print("contributionsB:"); for (int n = 0; n < MAX + 1; n++) System.out.print(String.format(" %.3f", Double.valueOf(contributionsB[n]))); System.out.println(); // double total = 0; // for (int n = 0; n < MAX + 1; n++) // { // //final int diff = Math.abs(bucketsA[n] - bucketsB[n]); // if (bucketsA[n] > 0 || bucketsB[n] > 0) // total += Math.min(bucketsA[n], bucketsB[n]) / Math.max(bucketsA[n], bucketsB[n]); // } // total /= (MAX + 1); // // final double scoreD = 1 - total; //Math.log10(total + 1); final double ratio = Math.min(listAin.size(), listBin.size()) / (double)Math.max(listAin.size(), listBin.size()); final double score = (scoreD + ratio) / 2.0; //System.out.println("total=" + total + ", scoreD=" + scoreD + ", ratio=" + ratio + ", score=" + score + "."); System.out.println("discrepancy=" + discrepancy + ", scoreD=" + scoreD + ", ratio=" + ratio + ", score=" + score + "."); return score; } /** * Destructively modifies lists. * @return Similarity measure between two lists, in range 0..1. */ public static double weightedEditDistance(final List<Integer> listAin, final List<Integer> listBin) { if (listAin.isEmpty() && listBin.isEmpty()) return 1; // perfect match! final List<Integer> listA = new ArrayList<>(listAin); final List<Integer> listB = new ArrayList<>(listBin); System.out.println("listA 1: " + listA); System.out.println("listB 1: " + listB); // Remove matching items from lists for (int a = listA.size() - 1; a >= 0; a--) { boolean remove = false; for (int b = listB.size() - 1; b >= 0; b--) { if (listA.get(a) == listB.get(b)) { // Remove this item from each list listB.remove(b); remove = true; break; } } if (remove) listA.remove(a); } System.out.println("listA 2: " + listA); System.out.println("listB 2: " + listB); // Remove most similar items from list, accumulating difference int difference = 0; final int iterations = Math.min(listA.size(), listB.size()); for (int iteration = 0; iteration < iterations; iteration++) { // int bestA = -1; // must be at least one item // int bestB = -1; // must be at least one item int minDiff = 1000; // Find most similar items for (final int a : listA) for (final int b : listB) { final int diff = Math.abs(a - b); if (diff < minDiff) { // bestA = a; // bestB = b; minDiff = diff; } } difference += minDiff; for (int a = listA.size() - 1; a >= 0; a--) { boolean remove = false; for (int b = listB.size() - 1; b >= 0; b--) { if (Math.abs(listA.get(a).intValue() - listB.get(b).intValue()) == minDiff) { // Remove this item from each list listB.remove(b); remove = true; break; } } if (remove) { listA.remove(a); break; } } } System.out.println("listA 3: " + listA); System.out.println("listB 3: " + listB); // Now just accumulate numbers in remaining list for (final int n : listA) difference += n; for (final int n : listB) difference += n; // final double totalSize = (listAin.size() + listBin.size()); final double avgSize = (listAin.size() + listBin.size()) / 2.0; final double score = 1 - Math.log10(difference / avgSize); //totalSize); //10.0); System.out.println("difference=" + difference + ", score=" + score); // double discrepancy = 0; // // discrepancy /= (listA.size() + listB.size()); // // final double scoreD = 1 - Math.log10(discrepancy + 1); // // final double ratio = Math.min(listAin.size(), listBin.size()) // / // (double)Math.max(listAin.size(), listBin.size()); // // final double score = (scoreD + ratio) / 2.0; // // //System.out.println("total=" + total + ", scoreD=" + scoreD + ", ratio=" + ratio + ", score=" + score + "."); // System.out.println("discrepancy=" + discrepancy + ", scoreD=" + scoreD + ", ratio=" + ratio + ", score=" + score + "."); return score; } //------------------------------------------------------------------------- }
12,475
26.299781
124
java
Ludii
Ludii-master/Player/test/games/CompilationTest.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import compiler.Compiler; import game.Game; import main.FileHandling; import main.grammar.Description; import other.GameLoader; /** * Unit Test to compile all the games on the lud folder * * @author Eric.Piette, Dennis Soemers */ public class CompilationTest { // Commented because already done in the playout by option TEST. // @Test // public void testCompilingLudFromFile() // { // System.out.println("=========================================\nTest: Compile all .lud from file:\n"); // // boolean failure = false; // final long startAt = System.nanoTime(); // // final File startFolder = new File("../Common/res/lud/"); // final List<File> gameDirs = new ArrayList<>(); // gameDirs.add(startFolder); // // final List<String> failedGames = new ArrayList<String>(); // // // We compute the .lud files (and not the ludemeplex). // final List<File> entries = new ArrayList<>(); // final List<File> badEntries = new ArrayList<>(); // // for (int i = 0; i < gameDirs.size(); ++i) // { // final File gameDir = gameDirs.get(i); // // for (final File fileEntry : gameDir.listFiles()) // { // if (fileEntry.isDirectory()) // { // final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); // // if (path.equals("../Common/res/lud/plex")) // continue; // // if (path.equals("../Common/res/lud/wip")) // continue; // // if (path.equals("../Common/res/lud/wishlist")) // continue; // // if (path.equals("../Common/res/lud/test")) // continue; // // if (path.equals("../Common/res/lud/bad")) // { // // We'll only find intentionally bad lud files here // for (final File fileEntryInter : fileEntry.listFiles()) // { // badEntries.add(fileEntryInter); // } // } // else // { // // We'll find files that we should be able to compile here // gameDirs.add(fileEntry); // } // } // else // { // if (!fileEntry.getName().contains(".lud")) // continue; // skip non-ludeme .DS_Store files // // entries.add(fileEntry); // } // } // } // // // Test of compilation for each of them. // for (final File fileEntry : entries) // { // final String fileName = fileEntry.getPath(); // // System.out.println("File: " + fileName); // // // Load the string from file // String desc = ""; // // String line = null; // try // { // // final FileReader fileReader = new FileReader(fileName); // // final BufferedReader bufferedReader = new BufferedReader(fileReader); // // while ((line = bufferedReader.readLine()) != null) // // desc += line + "\n"; // // bufferedReader.close(); // desc = FileHandling.loadTextContentsFromFile(fileName); // } // catch (final FileNotFoundException ex) // { // failure = true; // System.err.println("Unable to open file '" + fileName + "'"); // } // catch (final IOException ex) // { // failure = true; // System.err.println("Error reading file '" + fileName + "'"); // } // // // Parse and compile the game // final Game game = (Game)Compiler.compileTest(new Description(desc), false); // if (game != null) // { // System.out.println("Compiled " + game.name() + ".\n"); // } // else // { // failure = true; // failedGames.add(fileName); // System.err.println("** FAILED TO COMPILE GAME."); // } // } // // // Test of compilation for bad entries. // for (final File fileEntry : badEntries) // { // final String fileName = fileEntry.getPath(); // System.out.println("File: " + fileName); // // // Load the string from file // String desc = ""; // try // { // desc = FileHandling.loadTextContentsFromFile(fileName); // } // catch (final FileNotFoundException ex) // { // failure = true; // System.err.println("Unable to open file '" + fileName + "'"); // } // catch (final IOException ex) // { // failure = true; // System.err.println("Error reading file '" + fileName + "'"); // } // // try // { // // Parse and compile the game //// final UserSelections userSelections = new UserSelections(); // final Game game = (Game)Compiler.compileTest // ( //// desc, // new Description(desc), //// new int[GameOptions.MAX_OPTION_CATEGORIES], //// userSelections, // false // ); // if (game != null) // { // failure = true; // System.err.println("Expected to fail compilation of bad file, but compilation was successful: " + game.name() + ".\n"); // } // } // catch (final CompilerException exception) // { // // Ignore exception, we expect exceptions in bad .lud files // } // } // // final long stopAt = System.nanoTime(); // final double secs = (stopAt - startAt) / 1000000000.0; // System.out.println("Compiled " + entries.size() + " games."); // System.out.println("Time: " + secs + "s."); // // if (!failedGames.isEmpty()) // { // System.out.println("The uncompiled games are "); // for (final String name : failedGames) // System.out.println(name); // } // // if (failure) // fail(); // } @SuppressWarnings("static-method") @Test public void testCompilingLudFromMemory() { System.out.println("\n=========================================\nTest: Compile all .lud from memory:\n"); final List<String> failedGames = new ArrayList<String>(); boolean failure = false; final long startAt = System.nanoTime(); // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) continue; // Get game description from resource System.out.println("Game: " + fileName); String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and compile the game Game game = null; try { game = (Game)Compiler.compileTest(new Description(desc), false); } catch (final Exception e) { failure = true; e.printStackTrace(); } if (game != null) { System.out.println("Compiled " + game.name() + "."); } else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName + "."); } // Uncomment this to generate QR codes for all games. //QrCodeGeneration.makeQRCode(game, 5, 2, false); } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); if (!failedGames.isEmpty()) { System.out.println("\nUncompiled games:"); for (final String name : failedGames) System.out.println(name); } if (failure) fail(); } }
7,918
25.48495
126
java
Ludii
Ludii-master/Player/test/games/DuplicateMovesTest.java
package games; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import game.Game; import game.rules.phase.Phase; import game.rules.play.moves.Moves; import main.FileHandling; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.move.Move; import other.trial.Trial; /** * Check if in running a pre-determined number of playouts over all our games, * if some duplicates are present. * * @author Eric.Piette */ public class DuplicateMovesTest { /** The number of playouts to run. */ final int NUM_PLAYOUTS = 1; @Test public void test() { // Compilation of all the games. boolean duplicateMove = false; final String[] allGameNames = FileHandling.listGames(); for (int index = 0; index < allGameNames.length; index++) { final String gameName = allGameNames[index]; final String name = gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()); // if (!name.equals("Chex.lud")) // continue; if (FileHandling.shouldIgnoreLudAnalysis(gameName)) continue; System.out.println("Compilation of : " + gameName); final Game game = GameLoader.loadGameFromName(gameName); if (game.hasSubgames() || game.isDeductionPuzzle() || game.isSimulationMoveGame()) continue; for (int i = 0; i < NUM_PLAYOUTS; i++) { boolean duplicateMoveInPlayout = false; final List<AI> ais = new ArrayList<AI>(); ais.add(null); for (int p = 1; p <= game.players().count(); ++p) ais.add(new utils.RandomAI()); final Context context = new Context(game, new Trial(game)); final Trial trial = context.trial(); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) { final int mover = context.state().mover(); final Phase currPhase = game.rules().phases()[context.state().currentPhase(mover)]; final Moves legal = currPhase.play().moves().eval(context); for (int j = 0; j < legal.moves().size(); j++) { final Move m1 = legal.moves().get(j); for (int k = j + 1; k < legal.moves().size(); k++) { final Move m2 = legal.moves().get(k); if (Model.movesEqual(m1, m2, context)) { duplicateMove = true; if (!duplicateMoveInPlayout) System.err.println("DUPLIATE move in " + name); duplicateMoveInPlayout = true; } } } model.startNewStep(context, ais, 1.0); } } } if (duplicateMove) fail(); } }
2,645
23.5
92
java
Ludii
Ludii-master/Player/test/games/EfficiencyTest.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.context.Context; import other.trial.Trial; /** * Unit Test to run a time random playouts for all the games * * @author Eric.Piette */ public class EfficiencyTest { @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); final List<File> badCompEntries = new ArrayList<File>(); final List<File> badPlayoutEntries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) { // We'll only find intentionally bad lud files here for (final File fileEntryInter : fileEntry.listFiles()) { badCompEntries.add(fileEntryInter); } } else if (path.equals("../Common/res/lud/bad_playout")) { // We'll only find lud files here which should compile, // but fail to run for (final File fileEntryInter : fileEntry.listFiles()) { badPlayoutEntries.add(fileEntryInter); } } else { // We'll find files that we should be able to compile // and run here gameDirs.add(fileEntry); } } else { entries.add(fileEntry); } } } // the following entries should correctly compile and run for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game != null) { System.out.println("Compiled " + game.name() + " successfully."); } else { System.out.println("** FAILED TO COMPILE GAME."); fail("COMPILATION FAILED for the file : " + fileName); } final Trial trial = new Trial(game); final Context context = new Context(game, trial); // Warming long stopAt = 0; long start = System.nanoTime(); double abortAt = start + 10 * 1000000000.0; while (stopAt < abortAt) { game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); stopAt = System.nanoTime(); } stopAt = 0; System.gc(); start = System.nanoTime(); abortAt = start + 30 * 1000000000.0; int playouts = 0; int moveDone = 0; while (stopAt < abortAt) { game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); stopAt = System.nanoTime(); moveDone += context.trial().numMoves(); playouts++; } final double secs = (stopAt - start) / 1000000000.0; final double rate = (playouts / secs); final double rateMove = (moveDone / secs); System.out.println(rate + "p/s"); System.out.println(rateMove + "m/s"); } } } }
4,418
23.966102
82
java
Ludii
Ludii-master/Player/test/games/ErrorHandlingTests.java
package games; import java.util.concurrent.ThreadLocalRandom; import org.junit.Assert; import org.junit.Test; import game.Game; import compiler.Compiler; import main.grammar.Description; import other.context.Context; import other.trial.Trial; //----------------------------------------------------------------------------- /** * Unit Test to compile all the games on the lud folder * * @author Eric.Piette */ public class ErrorHandlingTests { //------------------------------------------------------------------------- private final String TTT = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTMissingKeyword = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (boardBad (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; // private final String TTTMetadataGood = // "(game \"Tic-Tac-Toe\"" + // " { (metadata \"Grammar\" \"v0.1\") }" + // " (mode 2)" + // " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + // " (rules " + // " (play (to (mover) (empty)))" + // " (end (line length:3) (result Mover Win))"+ // " )"+ // ")"; // // private final String TTTMetadataBad = // "(game \"Tic-Tac-Toe\"" + // " (metadata {\"Grammar\" \"v0.1\"})" + // " (mode 2)" + // " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + // " (rules " + // " (play (to (mover) (empty)))" + // " (end (line length:3) (result Mover Win))"+ // " )"+ // ")"; private final String TTTCantDecompose = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ ")"; private final String TTTBadTerminal = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P57) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadArray1 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (to) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTMissingQuote = "(game \"Tic-Tac-Toe" + " (mode 2)" + " (equipment { (board (square 3) (square)) (to) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTT_RECURSIVE_DEFINES = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"+ "(define \"A\" \"B\""; private final String TTTBadRange1 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { " + " (board (square 3) (square)) (disc P1) (cross P2)" + " (track \"Track\" \"Board\" {1.. 12...7} true)" + " })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadRange2 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { " + " (board (square 3) (square)) (disc P1) (cross P2)" + " (track \"Track\" \"Board\" {1..1000000} true)" + " })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTRecursiveOption = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) <1> })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")" + "(option <1> \"Board Size/3x3\" <(option <1> \"Board Size/3x3\" <1>)>)"; private final String TTTBadDefine1 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (define \"step\" (step (in (to) (empty) \"step\")))" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play \"step\")" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadDefine2 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (define \"step\" (step (in (to) (empty)))" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play \"step\")" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadDefine3 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (define \"step\" (step (in (to) (empty)))))" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play \"step\")" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadBrackets1 = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)})" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTURLInString = "(game \"Tic-Tac-Toe (see http://www.bgg.com)\"" + " (mode 2) " + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; private final String TTTBadPieceName = "(game \"Tic-Tac-Toe\"" + " (mode 2)" + " (equipment { (board (square 3) (square)) (disc P1) (cross P2) })" + " (rules " + " (start (place \"DiscWithBadName\" 0))" + " (play (to (mover) (empty)))" + " (end (line length:3) (result Mover Win))"+ " )"+ ")"; //------------------------------------------------------------------------- @Test public void testGoodFile() { verifyDoesCompile(TTT); } @Test public void testMissingKeyword() { verifyCompileFails(TTTMissingKeyword); } @Test public void testCantDecompose() { verifyCompileFails(TTTCantDecompose); } @Test public void testBadTerminal() { verifyCompileFails(TTTBadTerminal); } @Test public void testMissingQuote() { verifyCompileFails(TTTMissingQuote); } @Test public void testBadArray() { verifyCompileFails(TTTBadArray1); } @Test public void testRecursiveDefines() { verifyCompileFails(TTT_RECURSIVE_DEFINES); } @Test public void testRange1() { verifyCompileFails(TTTBadRange1); } @Test public void testRange2() { verifyCompileFails(TTTBadRange2); } @Test public void testRecursiveOption() { verifyCompileFails(TTTRecursiveOption); } @Test public void testBadDefine1() { verifyCompileFails(TTTBadDefine1); } @Test public void testBadDefine2() { verifyCompileFails(TTTBadDefine2); } @Test public void testBadDefine3() { verifyCompileFails(TTTBadDefine3); } @Test public void testBadBrackets1() { verifyCompileFails(TTTBadBrackets1); } @Test public void testURLInString() { verifyDoesCompile(TTTURLInString); } @Test public void testBadPieceName() { verifyCompilesButFailsToRun(TTTBadPieceName); } //------------------------------------------------------------------------- private static void verifyCompileFails(final String rules) { try { final Game game = (Game)Compiler.compileTest(new Description(rules), true); if (game == null) System.out.println("Expected a game but got null"); Assert.fail("An exception should have been thrown."); } catch (final Exception e) { System.out.println(e.getMessage()); } } private static void verifyDoesCompile(final String rules) { final Game game = (Game)Compiler.compileTest(new Description(rules), true); if (game == null) Assert.fail("Game should not be null."); } // private static void verifyCompilesButFailsToInitialise(final String rules) // { // final Game game = Compiler.getCompiler().compileTest(rules, true); // if (game == null) // Assert.fail("Game should not be null."); // try // { // game.create(800); // } // catch (final Exception e) // { // e.printStackTrace(); // System.out.println(e.getMessage()); // } // } private static void verifyCompilesButFailsToRun(final String rules) { final Game game = (Game)Compiler.compileTest(new Description(rules), true); if (game == null) Assert.fail("Game should not be null."); final Trial trial = new Trial(game); final Context context = new Context(game, trial); try { game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); } catch (final Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } // @Test // public void testBadArray() // { // try // { // Compiler.getCompiler().compile(TTTBadArray1, false, false); // Assert.fail("An exception should have been thrown."); // } // catch (Exception e) // { // System.out.println(e.getMessage()); // } // } //------------------------------------------------------------------------- }
10,428
25.402532
84
java
Ludii
Ludii-master/Player/test/games/GameFileNamesTest.java
package games; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; //----------------------------------------------------------------------------- /** * Tests if all game names are equal to their filenames * * @author Dennis Soemers */ public class GameFileNamesTest { @Test public static void testGameFileNames() throws IOException { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<>(); gameDirs.add(startFolder); // We compute the .lud files (and not the ludemeplex). final List<File> entries = new ArrayList<>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } // Test of compilation for each of them. for (final File fileEntry : entries) { final String filepath = fileEntry.getPath(); final String filename = fileEntry.getName(); System.out.println("File: " + filepath); // Load the string from file final String desc = FileHandling.loadTextContentsFromFile(filepath); // Parse and compile the game // final UserSelections userSelections = new UserSelections(); final Game game = (Game)Compiler.compileTest(new Description(desc), false); assert (game != null); assert (filename.substring(0, filename.length() - ".lud".length()).equals(game.name())); } } }
2,200
22.923913
91
java
Ludii
Ludii-master/Player/test/games/GamesWithWebLink.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.GameLoader; /** * To print all the link in each game. * * @author Eric.Piette */ public class GamesWithWebLink { @Test public static void testLinkInGame() { final List<String> failedGames = new ArrayList<String>(); boolean failure = false; // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and compile the game Game game = null; try { game = (Game)Compiler.compileTest(new Description(desc), false); } catch (final Exception e) { failure = true; e.printStackTrace(); } if (game != null) { for(final String source :game.metadata().info().getSource()) { if(source.contains("http") || source.contains("www")) System.out.println("Game: " + game.name() + " has a source with a link"); } for(final String rules :game.metadata().info().getRules()) { if(rules.contains("http") || rules.contains("www")) System.out.println("Game: " + game.name() + " has a rule with a link"); } for(final String publisher : game.metadata().info().getPublisher()) { if(publisher.contains("http")|| publisher.contains("www")) System.out.println("Game: " + game.name() + " has a publisher with a link"); } for(final String description : game.metadata().info().getDescription()) { if(description.contains("http")|| description.contains("www")) System.out.println("Game: " + game.name() + " has a description with a link"); } } else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName + "."); } } if (failure) fail(); // try (OutputStream os = new FileOutputStream(new File("rulesLudii.txt"))) // { // os.write(sb.toString().getBytes(), 0, sb.length()); // } // catch (final IOException e) // { // e.printStackTrace(); // } // finally{ // try { // os.close(); // } catch (final IOException e) { // e.printStackTrace(); // } // } } }
3,325
22.928058
84
java
Ludii
Ludii-master/Player/test/games/GenerateRandomTestTrials.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.junit.Test; import game.Game; import other.GameLoader; import other.context.Context; import other.trial.Trial; /** * A Unit Test to generate, and store, random trials for every game. * Games for which trials are already stored will be skipped. * * @author Dennis Soemers */ public class GenerateRandomTestTrials { /** Number of random trials to generate per game */ private static final int NUM_TRIALS_PER_GAME = 2; /** * Generates trials for Travis tests. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/reconstruction")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); for (int i = 0; i < NUM_TRIALS_PER_GAME; ++i) { final String trialFilepath = trialDirPath + File.separator + "RandomTrial_" + i + ".txt"; final File trialFile = new File(trialFilepath); if (trialFile.exists()) { System.out.println("Skipping " + ludPath + "; trial already exists at: " + trialFilepath); } else { trialFile.getParentFile().mkdirs(); final Game game = GameLoader.loadGameFromFile(fileEntry); System.out.println("Starting playout for: " + ludPath + "..."); // disable custom playouts that cannot properly store history of legal moves per state game.disableMemorylessPlayouts(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); final RandomProviderDefaultState gameStartRngState = (RandomProviderDefaultState) context.rng().saveState(); trial.storeLegalMovesHistorySizes(); if (context.isAMatch()) context.currentInstanceContext().trial().storeLegalMovesHistorySizes(); game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); try { trial.saveTrialToTextFile(trialFile, ludPath, new ArrayList<String>(), gameStartRngState); System.out.println("Saved trial for " + ludPath + " to file: " + trialFilepath); } catch (final IOException e) { e.printStackTrace(); fail("Crashed when trying to save trial to file."); } } } } } } }
4,241
26.907895
114
java
Ludii
Ludii-master/Player/test/games/GraphSize.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.GameLoader; //----------------------------------------------------------------------------- /** * Print the graph size of each game. * * @author Eric.Piette */ public class GraphSize { @Test public static void testCompilingLudFromMemory() { final List<String> list = new ArrayList<String>(); final List<String> failedGames = new ArrayList<String>(); boolean failure = false; // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and compile the game Game game = null; try { game = (Game)Compiler.compileTest(new Description(desc), false); // if ( // !game.isStacking() && // !game.isStochasticGame() && // !game.hiddenInformation() && // !game.board().isMancalaBoard() && // !game.hasCard() && // !game.hasDominoes() && // !game.isDeductionPuzzle() && // game.players().size() == 3) // { // System.out.print(game.name() + "_" + game.board().topology().vertices().size() // + "_" // + game.board().topology().edges().size() + "_" + game.board().topology().faces().size() // + "_"); // System.out.println(); // } System.out.print(game.name() + " - Graph size = (" + game.board().topology().cells().size() + " vertices, " + game.board().topology().edges().size() + " edges, " + game.board().topology().vertices().size() + " faces) "); if (game.equipment().containers().length < 2) System.out.println(); else { for (int i = 1; i < game.equipment().containers().length - 1; i++) System.out.print( "Hand " + i + " size = " + game.equipment().containers()[i].numSites() + " / "); System.out.println("Hand " + (game.equipment().containers().length - 1) + " size = " + game.equipment().containers()[game.equipment().containers().length - 1].numSites()); } } catch (final Exception e) { failure = true; e.printStackTrace(); } if (game != null) list.add(game.name()); else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName + "."); } } if (failure) fail(); } }
3,446
24.917293
103
java
Ludii
Ludii-master/Player/test/games/ListGamesSorted.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.GameLoader; //----------------------------------------------------------------------------- /** * Unit Test to print all our games sorted alphabetically * * @author Eric.Piette */ public class ListGamesSorted { @Test public static void testCompilingLudFromMemory() { final List<String> list = new ArrayList<String>(); final List<String> failedGames = new ArrayList<String>(); boolean failure = false; // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and compile the game Game game = null; try { game = (Game)Compiler.compileTest(new Description(desc), false); } catch (final Exception e) { failure = true; e.printStackTrace(); } if (game != null) list.add(game.name()); else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName + "."); } } if (failure) fail(); Collections.sort(list); for (final String name : list) System.out.println(name); } }
2,423
21.036364
83
java
Ludii
Ludii-master/Player/test/games/MancalaCountConsistency.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.StringRoutines; import main.collections.FastArrayList; import main.grammar.Description; import other.context.Context; import other.move.Move; import other.state.State; import other.state.container.ContainerState; import other.trial.Trial; /** * Unit test to make sure that the sum of counts of all sites in all * Mancala games remains constant throughout random playouts. * * @author Dennis Soemers */ public class MancalaCountConsistency { /** If any of these directories exist, we'll save trials in it where the total count change */ private static final String[] SAVE_TRIALS_DIRS = new String[]{ "D:/Apps/Ludii_Local_Experiments/MancalaCountTrials/", // Dennis desktop "C:/Apps/Ludii_Local_Experiments/MancalaCountTrials/", // Dennis // laptop "C:/Users/eric.piette/MancalaTrials/" // Eric }; /** * The test to run. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if ( fileEntry.getName().contains(".lud") && fileEntry.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/").contains("/mancala/") ) { final String fileName = fileEntry.getPath(); // Load the string from file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) { System.out.println("** FAILED TO COMPILE GAME."); fail("COMPILATION FAILED for the file : " + fileName); } // run our trial final Trial trial = new Trial(game); final Context context = new Context(game, trial); final SplitMix64 playoutRNG = new SplitMix64(); final RandomProviderDefaultState playoutStartRngState = (RandomProviderDefaultState) playoutRNG.saveState(); final RandomProviderDefaultState gameStartRngState = (RandomProviderDefaultState) context.rng().saveState(); // playoutRNG.restoreState(new RandomProviderDefaultState(new byte[] {-32, -120, 27, -51, 86, 12, 88, -112})); // context.rng().restoreState(new RandomProviderDefaultState(new byte[] {-103, -52, -76, -70, 8, -37, -65, 29})); System.out.println("Game = " + fileEntry.getName()); System.out.println("Playout start RNG = " + Arrays.toString(playoutStartRngState.getState())); System.out.println("Game start RNG = " + Arrays.toString(gameStartRngState.getState())); game.start(context); final int startCount = totalCount(context); boolean saved = false; while (!trial.over() && !saved) { final FastArrayList<Move> moves = game.moves(context).moves(); final Move randomMove = moves.get(playoutRNG.nextInt(moves.size())); game.apply(context, randomMove); // Make sure our total count didn't change if (startCount != totalCount(context)) { // Unit test is about to fail. Save trials if any of our directories exist for (final String filepath : SAVE_TRIALS_DIRS) { final File dirFile = new File(filepath); if (dirFile.exists() && dirFile.isDirectory()) { try { final File saveFile = new File(filepath + StringRoutines.cleanGameName(fileEntry.getName()) + ".trl"); trial.saveTrialToTextFile ( saveFile, fileEntry.getPath(), new ArrayList<String>(), gameStartRngState ); saved = true; System.err.println("Saved trial file: " + saveFile.getCanonicalPath()); } catch (final IOException e) { e.printStackTrace(); } } } } assert (startCount == totalCount(context)); } } } } /** * @param context * @return Sum of counts of all sites in given context */ private static final int totalCount(final Context context) { final State state = context.state(); final ContainerState cs = state.containerStates()[0]; int sum = 0; for (int i = 0; i < context.game().equipment().totalDefaultSites(); ++i) { sum += cs.countCell(i); } return sum; } }
6,078
26.885321
116
java
Ludii
Ludii-master/Player/test/games/MemoryUsedGames.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import compiler.Compiler; import game.Game; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import main.grammar.Description; import other.GameLoader; /** * To generate a CSV showing the memory used for each game. * * @author Eric.Piette */ public class MemoryUsedGames { public static void main(final String[] args) { final String output = "MemoryUsageGames.csv"; System.out.println("\n=========================================\nTest: Compile all .lud from memory:\n"); final List<String> failedGames = new ArrayList<String>(); boolean failure = false; final long startAt = System.nanoTime(); // Load from memory final String[] choices = FileHandling.listGames(); try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8")) { for (final String fileName : choices) { if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/validation/")) continue; if (fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/pending/")) continue; // Get game description from resource System.out.println("Game: " + fileName); String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and compile the game Game game = null; try { Thread.sleep(250); System.gc (); System.runFinalization (); Thread.sleep(250); game = (Game)Compiler.compileTest(new Description(desc), false); Runtime rt = Runtime.getRuntime(); long total_mem = rt.totalMemory(); long free_mem = rt.freeMemory(); long used_mem = total_mem - free_mem; System.out.println("Amount of used memory: " + (used_mem/ 1000000) + " MB"); final List<String> lineToWrite = new ArrayList<String>(); lineToWrite.add(game.name()); lineToWrite.add((used_mem/ 1000000) + ""); writer.println(StringRoutines.join(",", lineToWrite)); Thread.sleep(250); } catch (final Exception e) { failure = true; e.printStackTrace(); } if (game != null) { System.out.println("Compiled " + game.name() + "."); } else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName + "."); } } } catch (FileNotFoundException | UnsupportedEncodingException e2) { e2.printStackTrace(); } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); if (!failedGames.isEmpty()) { System.out.println("\nUncompiled games:"); for (final String name : failedGames) System.out.println(name); } if (failure) fail(); } }
4,050
24.639241
107
java
Ludii
Ludii-master/Player/test/games/Node.java
package games; import java.util.ArrayList; import java.util.Collections; import java.util.List; //----------------------------------------------------------------------------- /** * Pseudo UCT node for UCB cache test. * @author cambolbro */ public class Node { public static final int BranchingFactor = 10; private final Node parent; private int visits = 0; private final List<Integer> actions = new ArrayList<>(); private final List<Node> children = new ArrayList<>(); //------------------------------------------------------------------------- public Node(final int action, final Node parent) { this.parent = parent; this.visits = 1; for (int n = 0; n < BranchingFactor; n++) actions.add(Integer.valueOf(n)); Collections.shuffle(actions); } //------------------------------------------------------------------------- public int visits() { return visits; } public void visit() { visits++; if (parent != null) parent.visit(); } public boolean allVisited() { return actions.isEmpty(); } public List<Node> children() { return children; } public int choose() { final int choice = actions.get(0).intValue(); actions.remove(0); return choice; } public int size() { int count = 1; for (final Node child : children) count += child.size(); return count; } //------------------------------------------------------------------------- }
1,412
17.84
79
java
Ludii
Ludii-master/Player/test/games/OnePlayoutByGameTest.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import other.GameLoader; import other.context.Context; import other.trial.Trial; /** * Unit Test to run one playout by game * * @author Eric.Piette, Dennis Soemers */ public class OnePlayoutByGameTest { @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); final List<File> badPlayoutEntries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) { // We'll only find lud files here which should compile, but fail to run for (final File fileEntryInter : fileEntry.listFiles()) { badPlayoutEntries.add(fileEntryInter); } } else { // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } } else { entries.add(fileEntry); } } } // the following entries should correctly compile and run for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); final Game game = GameLoader.loadGameFromFile(fileEntry); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); System.out.println("PLAYOUT COMPLETE FOR " + game.name()); } } // the following entries should compile, but then fail to run for (final File fileEntry : badPlayoutEntries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); final Game game = GameLoader.loadGameFromFile(fileEntry); try { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); game.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); System.err.println("PLAYOUT COMPLETE FOR " + game.name()); fail("COMPLETED PLAYOUT for file which was supposed to file: " + fileName); } catch (final Exception exception) { System.out.println("Running game failed as expected."); } } } } }
3,466
24.492647
82
java
Ludii
Ludii-master/Player/test/games/ParseAllLud.java
package games; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import grammar.Grammar; import parser.Parser; import main.FileHandling; import main.grammar.Description; import main.grammar.Report; import main.options.UserSelections; import other.GameLoader; //----------------------------------------------------------------------------- /** * Unit Test to parse all the game descriptions. * Basically a speed test. * * @author cambolbro */ public class ParseAllLud { @Test public static void testCompilingLudFromMemory() { System.out.println("\n========================================="); System.out.println("Test: Compile all .lud from memory:\n"); // Cause grammar to be initialised Grammar.grammar(); //final Parser parser = new Parser(); final Report report = new Report(); final List<String> failed = new ArrayList<String>(); final long startAt = System.nanoTime(); // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if ( fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/") || fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/") || fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/") || fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/") ) continue; // Get game description from resource System.out.println("Parsing " + fileName + "..."); String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; try (final InputStream in = GameLoader.class.getResourceAsStream(path)) { try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } } catch (final IOException e) { e.printStackTrace(); } // Parse this game description final Description description = new Description(desc); final UserSelections userSelections = new UserSelections(new ArrayList<String>()); Parser.expandAndParse(description, userSelections, report, false); if (report.isError()) { failed.add(fileName); System.out.println("X"); for (final String error : report.errors()) System.out.println("X: " + error); } } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); if (!failed.isEmpty()) { System.out.println("\n" + failed.size() + " games did not parse:"); for (final String name : failed) System.out.println(name); } } }
2,903
25.4
85
java
Ludii
Ludii-master/Player/test/games/SanityChecks.java
package games; import static org.junit.Assert.assertEquals; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import other.context.Context; import other.trial.Trial; /** * Unit Test to test efficiency for all the games on the lud folder * * @author Eric.Piette */ public class SanityChecks { private void recurseFrom ( final List<String> results, final List<String> resultsCompFail, final List<String> resultsPlayFail, final File folder ) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { if (fileEntry.getName().equals("plex")) continue; else if (fileEntry.getName().equals("wip")) continue; else if (fileEntry.getName().equals("test")) continue; else if (fileEntry.getName().equals("bad")) recurseFrom(resultsCompFail, null, null, fileEntry); else if (fileEntry.getName().equals("bad_playout")) recurseFrom(resultsPlayFail, null, null, fileEntry); else recurseFrom(results, resultsCompFail, resultsPlayFail, fileEntry); } else if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); results.add(fileName); } } } @Test public void test() { final List<String> failList = new ArrayList<>(); final List<String> results = new ArrayList<>(); final List<String> resultsCompFail = new ArrayList<>(); final List<String> resultsPlayFail = new ArrayList<>(); final URL url = getClass().getResource("/lud/board/space/connection/Hex.lud"); final File folder = new File(url.getPath()).getParentFile().getParentFile().getParentFile().getParentFile(); recurseFrom(results, resultsCompFail, resultsPlayFail, folder); System.out.println("Found " + results.size() + " normal .lud files"); System.out.println("Found " + resultsCompFail.size() + " .lud files expected to fail compilation"); System.out.println("Found " + resultsPlayFail.size() + " .lud files expected to fail in playout"); final int MOVE_LIMIT = 200; int count = 0; int fails = 0; int timeouts = 0; for (final String fileName : results) { System.out.print("#"+(++count)+". "+fileName+": "); try { final String desc = FileHandling.loadTextContentsFromFile(fileName); final Game game = (Game)Compiler.compileTest(new Description(desc), false); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); game.playout(context, null, 0.01, null, 0, MOVE_LIMIT, ThreadLocalRandom.current()); if (context.trial().over()) { System.out.println(" success!"); } else { System.out.println(" move limit (" + MOVE_LIMIT + ") exceeded!"); timeouts++; } } catch (final Throwable e) { failList.add(fileName); e.printStackTrace(); System.err.println(" ERROR - "+e.getMessage()); fails++; } } for (final String fileName : resultsCompFail) { System.out.print("#"+(++count)+". "+fileName+": "); try { final String desc = FileHandling.loadTextContentsFromFile(fileName); //final Game game = (Game)Compiler.compileTest(new Description(desc), false); Compiler.compileTest(new Description(desc), false); failList.add(fileName); System.err.println(" ERROR - we expected compilation to fail for " + fileName); fails++; } catch (final Throwable e) { System.out.println("Compilation failed as expected for " + fileName); } } for (final String fileName : resultsPlayFail) { System.out.print("#"+(++count)+". "+fileName+": "); try { final String desc = FileHandling.loadTextContentsFromFile(fileName); final Game game = (Game)Compiler.compileTest(new Description(desc), false); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); game.playout(context, null, 0.01, null, 0, MOVE_LIMIT, ThreadLocalRandom.current()); if (!context.trial().over()) { System.out.println(" move limit (" + MOVE_LIMIT + ") exceeded!"); timeouts++; } failList.add(fileName); fails++; System.err.println(" ERROR - we expected playout to fail for " + fileName); } catch (final Throwable e) { System.out.println("Playout failed as expected for " + fileName); } } System.out.println ( "Test complete. " + (results.size() + resultsCompFail.size() + resultsPlayFail.size()) + " games, " + fails + " errors, " + timeouts + " not terminated"); System.out.println(failList); assertEquals(0, fails); } }
4,835
26.953757
110
java
Ludii
Ludii-master/Player/test/games/TestCustomPlayouts.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit test that checks for games with custom playouts * that all the moves they pick are indeed legal. * * @author Dennis Soemers */ public class TestCustomPlayouts { /** * We populate this with game names for which we know for sure that we want them * to be using custom (AddToEmpty) playouts */ public static Set<String> ADD_TO_EMPTY_GAMES; static { ADD_TO_EMPTY_GAMES = new HashSet<String>(); ADD_TO_EMPTY_GAMES.add("Cross"); ADD_TO_EMPTY_GAMES.add("Havannah"); ADD_TO_EMPTY_GAMES.add("Hex"); ADD_TO_EMPTY_GAMES.add("Y (Hex)"); ADD_TO_EMPTY_GAMES.add("Squava"); ADD_TO_EMPTY_GAMES.add("Tic-Tac-Four"); ADD_TO_EMPTY_GAMES.add("Tic-Tac-Mo"); ADD_TO_EMPTY_GAMES.add("Tic-Tac-Toe"); ADD_TO_EMPTY_GAMES.add("Yavalade"); ADD_TO_EMPTY_GAMES.add("Yavalath"); //ADD_TO_EMPTY_GAMES.add("Four-Player Hex"); ADD_TO_EMPTY_GAMES.add("Three-Player Hex"); ADD_TO_EMPTY_GAMES.add("Gomoku"); ADD_TO_EMPTY_GAMES.add("Sim"); } /** * The test to run. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); final Game game = GameLoader.loadGameFromFile(fileEntry); if (!game.hasCustomPlayouts()) continue; // Remember that we've hit this one ADD_TO_EMPTY_GAMES.remove(game.name()); System.out.println("Testing game with custom playouts: " + fileName); testCustomPlayout(game); } } // Make sure that we found all the games we expected to find if (!ADD_TO_EMPTY_GAMES.isEmpty()) { System.err.println("Expected the following games to have AddToEmpty playouts:"); for (final String game : ADD_TO_EMPTY_GAMES) { System.err.println(game); } fail(); } } /** * Tests custom playout implementation for given game * @param game */ public static void testCustomPlayout(final Game game) { // Play our trial (with custom playouts) final Context playedContext = new Context(game, new Trial(game)); final RandomProviderDefaultState gameStartRngState = (RandomProviderDefaultState) playedContext.rng().saveState(); game.start(playedContext); final Trial playedTrial = game.playout(playedContext, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); // Ensure that all played moves were legal and outcome is correct final List<Move> loadedMoves = playedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(gameStartRngState); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { assert(loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in ByScore End condition) // so we just check if they're equal, without applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context).equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context) ); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; assert(!trial.over()); final Moves legalMoves = game.moves(context); if (game.mode().mode() == ModeType.Alternating) { final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedAllActions = loadedMove.getActionsWithConsequences(context); Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedAllActions)) { matchingMove = move; break; } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.out.println("No matching move found for: " + loadedAllActions); for (final Move move : legalMoves.moves()) { System.out.println("legal move: " + move.getActionsWithConsequences(context)); } // try // { // System.out.println("Saving trial at time of crash to: " + new File("./Trial.trl").getAbsolutePath()); // trial.saveTrialToTextFile(new File("./Trial.trl"), game.name(), new ArrayList<String>(), gameStartRngState); // } // catch (final IOException e) { // e.printStackTrace(); // } fail(); } game.apply(context, matchingMove); } else { // simultaneous-move game // we expect each of the actions of the loaded move to be contained // in at least one of the legal moves boolean foundNonMatch = false; for (final Action subAction : loadedMoves.get(moveIdx).actions()) { boolean foundMatch = false; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).contains(subAction)) { foundMatch = true; break; } } if (!foundMatch) { foundNonMatch = true; break; } } assert (!foundNonMatch); game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert(playedTrial.status() == null); else assert(trial.status().winner() == playedTrial.status().winner()); assert(Arrays.equals(context.trial().ranking(), playedContext.trial().ranking())); } }
7,627
25.394464
134
java
Ludii
Ludii-master/Player/test/games/TestDecision.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import compiler.Compiler; import main.FileHandling; import main.collections.FastArrayList; import main.collections.ListUtils; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * A Unit Test to load Trials from the TravisTrials repository, and check if they contains non decision moves. * * @author Eric.Piette */ public class TestDecision { /** * The test to run * * @throws FileNotFoundException * @throws IOException */ @Test @SuppressWarnings("static-method") public void test() throws FileNotFoundException, IOException { final File startFolder = new File("../Common/res/lud"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); // final String moreSpecificFolder = "../Common/res/lud/board/sow"; final String moreSpecificFolder = ""; for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; gameDirs.add(fileEntry); } else { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder)) entries.add(fileEntry); } } } boolean gameReached = false; final String gameToReached = ""; final String gameToSkip = ""; final long startTime = System.currentTimeMillis(); for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { if (fileEntry.getName().contains(gameToReached) || gameToReached.length() == 0) gameReached = true; if (!gameReached) continue; if (!gameToSkip.equals("") && fileEntry.getName().contains(gameToSkip)) continue; final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) fail("COMPILATION FAILED for the file : " + ludPath); if (game.hasSubgames() || game.isSimulationMoveGame()) continue; for (final File trialFile : trialFiles) { System.out.println("Testing re-play of trial: " + trialFile); final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.moves().get(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); assert (loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { final Move loadedMove = loadedMoves.get(moveIdx); if (!loadedMove.isDecision()) System.err.println("NON DECISION LOADED MOVE = " + loadedMove); final List<Action> loadedAllActions = loadedMove.getActionsWithConsequences(context); final List<Action> trialMoveAllActions = trial.getMove(moveIdx).getActionsWithConsequences(context); assert (loadedAllActions.equals(trialMoveAllActions)) : ("Loaded Move Actions = " + loadedAllActions + ", trial actions = " + trialMoveAllActions); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } final Moves legalMoves = game.moves(context); // make sure that the number of legal moves is the same // as stored in file if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } assert (legalMoves.moves().size() == loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + " from is " + loadedMoves.get(moveIdx).fromType() + " to is " + loadedMoves.get(moveIdx).toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } } assert (matchingMove != null); game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert (loadedTrial.status() == null); else assert (trial.status().winner() == loadedTrial.status().winner()); assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } } System.out.println("Finished TestTrialsIntegrity!"); final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0; final int seconds = (int) (allSeconds % 60.0); final int minutes = (int) ((allSeconds - seconds) / 60.0); System.out.println("Done in " + minutes + " minutes " + seconds + " seconds"); } }
12,187
31.501333
132
java
Ludii
Ludii-master/Player/test/games/TestEmptyInfo.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; /** * Unit Test to check if one of our "official" games has no info * * @author Eric.Piette */ public class TestEmptyInfo { @Test public static void testCompilingLudFromFile() { System.out.println("=========================================\nTest: Compile all .lud from file:\n"); boolean failure = false; final long startAt = System.nanoTime(); final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<>(); gameDirs.add(startFolder); final List<String> failedGames = new ArrayList<String>(); final List<String> noInfoGames = new ArrayList<String>(); // We compute the .lud files (and not the ludemeplex). final List<File> entries = new ArrayList<>(); final List<File> badEntries = new ArrayList<>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.contains("lud/plex")) continue; if (path.contains("lud/wip")) continue; if (path.contains("wishlist")) continue; if (path.contains("lud/test")) continue; if (path.contains("lud/bad")) { // We'll only find intentionally bad lud files here for (final File fileEntryInter : fileEntry.listFiles()) { badEntries.add(fileEntryInter); } } else { // We'll find files that we should be able to compile // here gameDirs.add(fileEntry); } } else { if (!fileEntry.getName().contains(".lud")) continue; // skip non-ludeme .DS_Store files entries.add(fileEntry); } } } // Test of compilation for each of them. for (final File fileEntry : entries) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; // String line = null; try { // final FileReader fileReader = new FileReader(fileName); // final BufferedReader bufferedReader = new // BufferedReader(fileReader); // while ((line = bufferedReader.readLine()) != null) // desc += line + "\n"; // bufferedReader.close(); desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { failure = true; System.err.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { failure = true; System.err.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game != null && (game.metadata().info().getItem().size() != 0 || (game.metadata().info().getItem().size() == 1 && game.metadata().info().getItem().get(0) != null))) { System.out.println("Compiled and has info " + game.name() + ".\n"); } else if (game == null) { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE GAME."); } else if (game.metadata().info().getItem().size() == 0 || (game.metadata().info().getItem().size() == 1 && game.metadata().info().getItem().get(0) == null)) { failure = true; noInfoGames.add(fileName); System.err.println("** HAS NO INFO."); } } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("Compiled " + entries.size() + " games."); System.out.println("Time: " + secs + "s."); if (!failedGames.isEmpty()) { System.out.println("The uncompiled games are "); for (final String name : failedGames) System.out.println(name); } if (!noInfoGames.isEmpty()) { System.out.println("The games without info are "); for (final String name : noInfoGames) System.out.println(name); } if (failure) fail(); } }
4,347
24.727811
107
java
Ludii
Ludii-master/Player/test/games/TestParallelPlayouts.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import game.types.state.GameType; import main.collections.FastArrayList; import main.collections.ListUtils; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * Unit test that, for every game, tests whether we can * correctly run playouts in parallel. * * @author Dennis Soemers */ public class TestParallelPlayouts { /** Number of parallel playouts we run */ private static final int NUM_PARALLEL = 4; /** * The test to run. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("Trying game file: " + fileName); final Game game = GameLoader.loadGameFromFile(fileEntry); if (game.isSimulationMoveGame()) continue; if (game.hasSubgames()) continue; // run parallel trials final Context[] contexts = new Context[NUM_PARALLEL]; final RandomProviderDefaultState[] gameStartRngStates = new RandomProviderDefaultState[NUM_PARALLEL]; for (int i = 0; i < NUM_PARALLEL; ++i) { contexts[i] = new Context(game, new Trial(game)); gameStartRngStates[i] = (RandomProviderDefaultState) contexts[i].rng().saveState(); } final ExecutorService executorService = Executors.newFixedThreadPool(NUM_PARALLEL); final List<Future<Context>> playedContexts = new ArrayList<Future<Context>>(NUM_PARALLEL); for (int i = 0; i < NUM_PARALLEL; ++i) { final Context context = contexts[i]; playedContexts.add(executorService.submit(() -> { game.start(context); game.playout(context, null, 1.0, null, 0, 30, ThreadLocalRandom.current()); return context; })); } // store outcomes of all parallel trials final Context[] endContexts = new Context[NUM_PARALLEL]; try { for (int i = 0; i < NUM_PARALLEL; ++i) { endContexts[i] = playedContexts.get(i).get(); } } catch (final InterruptedException | ExecutionException e) { e.printStackTrace(); fail(); } executorService.shutdown(); // check if we can still execute them all the same way in serial mode for (int parallelPlayout = 0; parallelPlayout < NUM_PARALLEL; ++parallelPlayout) { final Context parallelContext = endContexts[parallelPlayout]; final Trial parallelTrial = parallelContext.trial(); final List<Move> loadedMoves = parallelTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(gameStartRngStates[parallelPlayout]); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { assert(loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in ByScore End condition) // so we just check if they're equal, without applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context).equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context) ); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Serial trial already over after moves:"); for (final Move move : trial.generateCompleteMovesList()) { System.out.println(move); } System.out.println("When run in parallel, trial only ended after moves:"); for (final Move move : parallelTrial.generateCompleteMovesList()) { System.out.println(move); } fail(); } final Moves legalMoves = game.moves(context); final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { System.out.println("No matching move found for: " + loadedMoveAllActions); for (final Move move : legalMoves.moves()) { System.out.println("legal move: " + move.getActionsWithConsequences(context)); } fail(); } //assert(matchingMove != null); assert ( matchingMove.fromNonDecision() == matchingMove.toNonDecision() || (game.gameFlags() & GameType.UsesFromPositions) != 0L ); game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert(parallelTrial.status() == null); else assert(trial.status().winner() == parallelTrial.status().winner()); if (!Arrays.equals(context.trial().ranking(), parallelContext.trial().ranking())) { System.out.println("Ranking when run in parallel: " + Arrays.toString(parallelContext.trial().ranking())); System.out.println("Ranking when run serially: " + Arrays.toString(context.trial().ranking())); fail(); } // we're done with this one, let's allow memory to be cleared endContexts[parallelPlayout] = null; } } } } }
10,676
29.593123
138
java
Ludii
Ludii-master/Player/test/games/TestParser.java
package games; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test; import grammar.Grammar; import parser.Parser; import main.FileHandling; import main.grammar.Description; import main.grammar.Report; import main.options.UserSelections; import other.GameLoader; //----------------------------------------------------------------------------- /** * Parses all files in res/lud/test/parser. * * @author cambolbro */ public class TestParser { @Test public static void testCompilingLudFromMemory() { System.out.println("\n======================================================"); System.out.println("Test: Parsing test .lud from memory:\n"); // Cause grammar to be initialised Grammar.grammar(); final Report report = new Report(); final long startAt = System.currentTimeMillis(); // Load from memory final String[] choices = FileHandling.listGames(); for (final String fileName : choices) { if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/parser")) continue; // Get game description from resource System.out.println("---------------------------------------------------"); System.out.println("File: " + fileName); String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; try (final InputStream in = GameLoader.class.getResourceAsStream(path)) { try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } } catch (final IOException e) { e.printStackTrace(); } // Parse this game description final Description description = new Description(desc); final UserSelections userSelections = new UserSelections(new ArrayList<String>()); Parser.expandAndParse(description, userSelections, report, false); if (!report.isError()) { if (report.isWarning()) for (final String warning : report.warnings()) System.out.println("- Warning: " + warning); System.out.println("Parsed okay."); } else { //System.out.println("\nFailed to parse:"); System.out.println(description.expanded()); for (final String error : report.errors()) System.out.println("* " + error); } } final long stopAt = System.currentTimeMillis(); final double secs = (stopAt - startAt) / 1000.0; System.out.println("\nDone in " + secs + "s."); } }
2,661
25.888889
85
java
Ludii
Ludii-master/Player/test/games/TestTrialSerialization.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.collections.FastArrayList; import main.collections.ListUtils; import manager.utils.game_logs.MatchRecord; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * Unit Test to test serialization and deserialization of trials. * * For every game, we run one playout, serialize it to a temporary file, * deserialize it again, and immediately test if we can reproduce the trial. * * @author Dennis Soemers */ public class TestTrialSerialization { /** File for temp trials */ public static final File TEMP_TRIAL_FILE = new File("./TempLudiiTrialTestFile.txt"); /** * The test to run. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; if (path.equals("../Common/res/lud/reconstruction")) continue; if (path.equals("../Common/res/lud/simulation")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final Game game = GameLoader.loadGameFromFile(fileEntry); System.out.println("Attempting to run, save, load and validate trial for game: " + fileEntry.getName()); testTrialSerialization(game); } } // delete temp file if we succeeded unit test TEMP_TRIAL_FILE.delete(); } /** * Tests trial serialization for given game * @param game */ public static void testTrialSerialization(final Game game) { if (game.isDeductionPuzzle()) return; // disable custom playouts that cannot properly store history of legal moves per state game.disableMemorylessPlayouts(); Trial trial = new Trial(game); Context context = new Context(game, trial); final RandomProviderDefaultState gameStartRngState = (RandomProviderDefaultState) context.rng().saveState(); // trial.storeLegalMovesHistory(); // if (context.isAMatch()) // context.currentInstanceContext().trial().storeLegalMovesHistory(); game.start(context); final int maxNumMoves = 10 + (int) (Math.random() * 21); game.playout(context, null, 1.0, null, 0, maxNumMoves, ThreadLocalRandom.current()); try { // save it to temp file trial.saveTrialToTextFile(TEMP_TRIAL_FILE, game.name(), new ArrayList<String>(), gameStartRngState); // and immediately load and check it final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(TEMP_TRIAL_FILE, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); trial = new Trial(game); context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < context.currentInstanceContext().trial().numInitialPlacementMoves()) { assert(loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in ByScore End condition) // so we just check if they're equal, without applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context).equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context) ); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; assert(!trial.over()); final Moves legalMoves = game.moves(context); final List<List<Action>> legalMovesAllActions = new ArrayList<List<Action>>(); for (final Move legalMove : legalMoves.moves()) { legalMovesAllActions.add(legalMove.getActionsWithConsequences(context)); } // final List<List<Action>> loadedLegalMovesAllActions = new ArrayList<List<Action>>(); // final Trial subtrial = context.currentInstanceContext().trial(); // for (final Move loadedLegalMove : loadedTrial.auxilTrialData().legalMovesHistory().get(moveIdx - subtrial.numInitialPlacementMoves())) // { // loadedLegalMovesAllActions.add(loadedLegalMove.getActionsWithConsequences(context)); // } // // // make sure that all of the stored legal moves are also currently legal moves // for (int loadedIdx = 0; loadedIdx < loadedLegalMovesAllActions.size(); ++loadedIdx) // { // boolean foundMatch = false; // // for (int i = 0; i < legalMovesAllActions.size(); ++i) // { // if (loadedLegalMovesAllActions.get(loadedIdx).equals(legalMovesAllActions.get(i))) // { // foundMatch = true; // break; // } // } // //// if (!foundMatch) //// { //// for (final Move legalMove : legalMoves.moves()) //// { //// System.out.println(loadedLegalMovesAllActions.get(loadedIdx) + " not equal to " + legalMove.getAllActions(context)); //// } //// } // // assert (foundMatch) : loadedTrial.auxilTrialData().legalMovesHistory().get(moveIdx - trial.numInitialPlacementMoves()) + " was legal in stored trial, but not found in " + legalMoves.moves(); // } // // // make sure that all of the currently legal moves are also stored legal moves // for (int i = 0; i < legalMovesAllActions.size(); ++i) // { // boolean foundMatch = false; // // for (int loadedIdx = 0; loadedIdx < loadedLegalMovesAllActions.size(); ++loadedIdx) // { // if (loadedLegalMovesAllActions.get(loadedIdx).equals(legalMovesAllActions.get(i))) // { // foundMatch = true; // break; // } // } // //// if (!foundMatch) //// { //// for (final Move move : loadedTrial.legalMovesHistory().get(moveIdx - trial.numInitPlace())) //// { //// System.out.println(legalMove.getAllActions(context) + " not equal to " + move.getAllActions(context)); //// } //// } // // assert (foundMatch); // } final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (int i = 0; i < legalMovesAllActions.size(); ++i) { if (legalMovesAllActions.get(i).equals(loadedMoveAllActions)) { matchingMove = legalMoves.moves().get(i); break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } // if (matchingMove == null) // { // for (int i = 0; i < legalMovesAllActions.size(); ++i) // { // System.out.println(legalMovesAllActions.get(i) + " does not match " + loadedMoves.get(moveIdx).getAllActions(context)); // } // } assert(matchingMove != null); game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert(loadedTrial.status() == null); else assert(trial.status().winner() == loadedTrial.status().winner()); assert(Arrays.equals(trial.ranking(), loadedTrial.ranking())); } catch (final IOException e) { e.printStackTrace(); fail("Crashed when trying to save or load trial."); } } }
11,487
29.472149
197
java
Ludii
Ludii-master/Player/test/games/TestTrialsIntegrityDENNIS.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Test; import compiler.Compiler; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.FileHandling; import main.collections.FastArrayList; import main.collections.ListUtils; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * A Unit Test to load Trials from the TravisTrials repository, and check if they * all still play out the same way in the current Ludii codebase. * * @author Dennis Soemers and Eric.Piette */ public class TestTrialsIntegrityDENNIS { /** * The test to run * * @throws FileNotFoundException * @throws IOException */ @Test public static void test() throws FileNotFoundException, IOException { final File startFolder = new File("../Common/res/lud"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); // final String moreSpecificFolder = "../Common/res/lud/board/sow"; final String moreSpecificFolder = ""; for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/reconstruction")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; // // We exclude that game from the tests because the legal // // moves are too slow to test. // if (fileEntryPath.contains("Residuel")) // continue; gameDirs.add(fileEntry); } else { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder)) entries.add(fileEntry); } } } boolean gameReached = false; final String gameToReached = ""; final String gameToSkip = ""; final long startTime = System.currentTimeMillis(); for (final File fileEntry : entries) { if (fileEntry.getName().contains("")) { if (fileEntry.getName().contains(gameToReached) || gameToReached.length() == 0) gameReached = true; if (!gameReached) continue; if (!gameToSkip.equals("") && fileEntry.getName().contains(gameToSkip)) continue; final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) fail("COMPILATION FAILED for the file : " + ludPath); if (game.hasSubgames() || game.isSimulationMoveGame()) continue; for (final File trialFile : trialFiles) { System.out.println("Testing re-play of trial: " + trialFile); final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.getMove(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); assert (loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. // in ByScore End condition) // so we just check if they're equal, without // applying them again from loaded file final List<Action> loadedAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); final List<Action> trialMoveAllActions = trial.getMove(moveIdx).getActionsWithConsequences(context); assert (loadedAllActions.equals(trialMoveAllActions)) : ("Loaded Move Actions = " + loadedAllActions + ", trial actions = " + trialMoveAllActions); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } final Moves legalMoves = game.moves(context); // make sure that the number of legal moves is the same // as stored in file if (loadedTrial.auxilTrialData() != null) { if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } assert (legalMoves.moves().size() == loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMove.getActionsWithConsequences(context) + " from is " + loadedMove.fromType() + " to is " + loadedMove.toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } } assert (matchingMove != null); game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) { if (loadedTrial.status() != null) System.out .println("Game not over but should be in moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); assert (loadedTrial.status() == null); } else assert (trial.status().winner() == loadedTrial.status().winner()); if (!Arrays.equals(trial.ranking(), loadedTrial.ranking())) { System.out.println("trial.ranking() = " + Arrays.toString(trial.ranking())); System.out.println("loadedTrial.ranking() = " + Arrays.toString(loadedTrial.ranking())); } Assert.assertArrayEquals(trial.ranking(), loadedTrial.ranking(), 0.00001); } } } System.out.println("Finished TestTrialsIntegrity!"); final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0; final int seconds = (int) (allSeconds % 60.0); final int minutes = (int) ((allSeconds - seconds) / 60.0); System.out.println("Done in " + minutes + " minutes " + seconds + " seconds"); } }
13,152
31.718905
132
java
Ludii
Ludii-master/Player/test/games/TestTrialsIntegrityERIC.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import compiler.Compiler; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.FileHandling; import main.collections.FastArrayList; import main.collections.ListUtils; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * A Unit Test to load Trials from the TravisTrials repository, and check if they * all still play out the same way in the current Ludii codebase. * * @author Dennis Soemers and Eric.Piette */ @SuppressWarnings("static-method") public class TestTrialsIntegrityERIC { /** * The test to run * * @throws FileNotFoundException * @throws IOException */ @Test public void test() throws FileNotFoundException, IOException { final File startFolder = new File("../Common/res/lud"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); //final String moreSpecificFolder = "../Common/res/lud/board/war/leaping/diagonal"; final String moreSpecificFolder = ""; for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/reconstruction")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; // // We exclude that game from the tests because the legal // // moves are too slow to test. // if (fileEntryPath.contains("Residuelllllllll")) // continue; gameDirs.add(fileEntry); } else { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder)) entries.add(fileEntry); } } } boolean gameReached = false; final String gameToReached = ""; final String gameToSkip = ""; final long startTime = System.currentTimeMillis(); for (final File fileEntry : entries) { if (fileEntry.getName().contains("MensaSpiel")) { if (fileEntry.getName().contains(gameToReached) || gameToReached.length() == 0) gameReached = true; if (!gameReached) continue; if (!gameToSkip.equals("") && fileEntry.getName().contains(gameToSkip)) continue; final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) fail("COMPILATION FAILED for the file : " + ludPath); if (game.hasSubgames() || game.isSimulationMoveGame()) continue; for (final File trialFile : trialFiles) { System.out.println("Testing re-play of trial: " + trialFile); final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Context context = new Context(game, new Trial(game)); context.rng().restoreState(loadedRecord.rngState()); final Trial trial = context.trial(); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.getMove(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); assert (loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. // in ByScore End condition) // so we just check if they're equal, without // applying them again from loaded file final List<Action> loadedAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); final List<Action> trialMoveAllActions = trial.getMove(moveIdx).getActionsWithConsequences(context); if(!loadedAllActions.equals(trialMoveAllActions)) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("loadedAllActions = " + loadedAllActions); System.out.println("trialMoveAllActions = " + trialMoveAllActions); } assert (loadedAllActions.equals(trialMoveAllActions)) : ("Loaded Move Actions = " + loadedAllActions + ", trial actions = " + trialMoveAllActions); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } final Moves legalMoves = game.moves(context); // make sure that the number of legal moves is the same // as stored in file if (loadedTrial.auxilTrialData() != null) { if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } assert (legalMoves.moves().size() == loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMove.getActionsWithConsequences(context) + " from is " + loadedMove.fromType() + " to is " + loadedMove.toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } } assert (matchingMove != null); game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) { if (loadedTrial.status() != null) System.out .println("Game not over but should be in moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); assert (loadedTrial.status() == null); } else assert (trial.status().winner() == loadedTrial.status().winner()); assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } } System.out.println("Finished TestTrialsIntegrity!"); final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0; final int seconds = (int) (allSeconds % 60.0); final int minutes = (int) ((allSeconds - seconds) / 60.0); System.out.println("Done in " + minutes + " minutes " + seconds + " seconds"); } }
13,260
31.824257
132
java
Ludii
Ludii-master/Player/test/games/TestTrialsUndo.java
package games; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import compiler.Compiler; import game.Game; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.ModeType; import gnu.trove.list.array.TIntArrayList; import main.FileHandling; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import other.state.owned.Owned; import other.trial.Trial; import other.state.State; /** * A Unit Test to load Trials from the TravisTrials repository, and check if they * all still play out the same way in the current Ludii codebase. * * @author Eric.Piette */ public class TestTrialsUndo { /** * The test to run * * @throws FileNotFoundException * @throws IOException */ @Test public static void test() throws FileNotFoundException, IOException { final boolean stateComparaison = false; final File startFolder = new File("../Common/res/lud"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); // final String moreSpecificFolder = "../Common/res/lud/board/sow"; final String moreSpecificFolder = ""; for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/reconstruction")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; // // We exclude that game from the tests because the legal // // moves are too slow to test. // if (fileEntryPath.contains("Residuelllllllll")) // continue; gameDirs.add(fileEntry); } else { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder)) entries.add(fileEntry); } } } boolean gameReached = false; final String gameToReached = ""; final ArrayList<String> gamesToSkip = new ArrayList<String>(); gamesToSkip.add("Galatjang"); gamesToSkip.add("Seesaw Draughts"); gamesToSkip.add("Sahkku"); gamesToSkip.add("Kriegsspiel"); final long startTime = System.currentTimeMillis(); for (final File fileEntry : entries) { if (fileEntry.getPath().contains("")) //if (fileEntry.getName().equals("Ludus Latrunculorum.lud")) { if (fileEntry.getName().contains(gameToReached) || gameToReached.length() == 0) gameReached = true; if (!gameReached) continue; boolean skip = false; for(String gameToSkip : gamesToSkip) if (!gameToSkip.equals("") && fileEntry.getName().contains(gameToSkip)) { skip = true; break; } if(skip) continue; final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) fail("COMPILATION FAILED for the file : " + ludPath); if (game.hasSubgames() || game.isSimulationMoveGame()) continue; for (final File trialFile : trialFiles) { System.out.println("Testing playing trial and undo move by move: " + trialFile); final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Context context = new Context(game, new Trial(game)); context.rng().restoreState(loadedRecord.rngState()); final Trial trial = context.trial(); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) ++moveIdx; // Apply all the trial. if(game.isStochasticGame()) { while (!trial.over()) { final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); final Moves legalMoves = context.game().moves(context); boolean legalMoveFound = false; for(Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { game.apply(context, move); if(!trial.over()) ++moveIdx; legalMoveFound= true; break; } } } if(!legalMoveFound) { System.err.println("BUG no legal moves found"); fail(); } } } else { while (!trial.over()) { final Move loadedMove = loadedMoves.get(moveIdx); game.apply(context, loadedMove); if(!trial.over()) ++moveIdx; } } // -------------------------------------------TEST Undo all the trial. --------------------------------------------------------------------------------------- while (moveIdx > trial.numInitialPlacementMoves() && moveIdx > 0) { game.undo(context); // Apply the trial from the initial state to the specific state we want to compare. if(stateComparaison) { final Context contextToCompare = new Context(game, new Trial(game)); contextToCompare.rng().restoreState(loadedRecord.rngState()); final Trial trialToCompare = contextToCompare.trial(); final State stateToCompare = contextToCompare.state(); final State state = context.state(); game.start(contextToCompare); int indexTrialToCompare = 0; while (indexTrialToCompare < trialToCompare.numInitialPlacementMoves()) ++indexTrialToCompare; if(game.isStochasticGame()) { while(indexTrialToCompare < moveIdx) { final Move loadedMove = loadedMoves.get(indexTrialToCompare); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(contextToCompare); final Moves legalMoves = context.game().moves(contextToCompare); boolean legalMoveFound = false; for(Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(contextToCompare).equals(loadedMoveAllActions)) { game.apply(contextToCompare, move); legalMoveFound= true; if(!trialToCompare.over()) ++indexTrialToCompare; break; } } } if(!legalMoveFound) { System.err.println("STATE COMPARAISON BUG no legal moves found"); fail(); } } } else { while (indexTrialToCompare < moveIdx) { final Move loadedMove = loadedMoves.get(indexTrialToCompare); game.apply(contextToCompare, loadedMove); if(!trialToCompare.over()) ++indexTrialToCompare; } } // Check the container states. for(int cid = 0; cid < context.state().containerStates().length; cid++) { final ContainerState cs = context.containerState(cid); final ContainerState csToCompare = contextToCompare.containerState(cid); for(SiteType type : SiteType.values()) { if(cid == 0 || (cid != 0 && type.equals(SiteType.Cell))) { for(int index = context.sitesFrom()[cid] ; index < (context.sitesFrom()[cid] + game.equipment().containers()[cid].topology().getGraphElements(type).size()); index++) { if(cs.sizeStack(index, type) != csToCompare.sizeStack(index, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != stack size for " + type + " " + index); System.out.println("correct one is " + csToCompare.sizeStack(index, type)); System.out.println("undo one is " + cs.sizeStack(index, type)); fail(); } for(int level = 0; level < cs.sizeStack(index, type); level++) { if(cs.what(index, level, type) != csToCompare.what(index, level, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != What at " + index + " level " + level); System.out.println("correct one is " + csToCompare.what(index, level, type)); System.out.println("undo one is " + cs.what(index, level, type)); fail(); } if(cs.who(index, level, type) != csToCompare.who(index, level, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " +type + " != Who at " + index + " level " + level); System.out.println("correct one is " + csToCompare.who(index, level, type)); System.out.println("undo one is " + cs.who(index, level, type)); fail(); } if(cs.state(index, level, type) != csToCompare.state(index, level, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != State at " + index + " level " + level); System.out.println("correct one is " + csToCompare.state(index, level, type)); System.out.println("undo one is " + cs.state(index, level, type)); fail(); } if(cs.rotation(index, level, type) != csToCompare.rotation(index, level, type)) { System.out.println(type + " != Rotation at " + index + " level " + level); fail(); } if(cs.value(index, level, type) != csToCompare.value(index, level, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != Value at " + index + " level " + level); System.out.println("correct one is " + csToCompare.value(index, level, type)); System.out.println("undo one is " + cs.value(index, level, type)); fail(); } for(int pid = 1; pid < game.players().size() ; pid++) { if(cs.isHidden(pid, index, level, type) != csToCompare.isHidden(pid, index, level, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != isHidden at " + index + " level " + level + " player " + pid); System.out.println("correct one is " + csToCompare.isHidden(pid, index, level, type)); System.out.println("undo one is " + cs.isHidden(pid, index, level, type)); fail(); } if(cs.isHiddenWhat(pid, index, level, type) != csToCompare.isHiddenWhat(pid, index, level, type)) { System.out.println(type + " != isHiddenWhat at " + index + " level " + level + " player " + pid); fail(); } if(cs.isHiddenWho(pid, index, level, type) != csToCompare.isHiddenWho(pid, index, level, type)) { System.out.println(type + " != isHiddenWho at " + index + " level " + level + " player " + pid); fail(); } if(cs.isHiddenValue(pid, index, level, type) != csToCompare.isHiddenValue(pid, index, level, type)) { System.out.println(type + " != isHiddenValue at " + index + " level " + level + " player " + pid); fail(); } if(cs.isHiddenState(pid, index, level, type) != csToCompare.isHiddenState(pid, index, level, type)) { System.out.println(type + " != isHiddenState at " + index + " level " + level + " player " + pid); fail(); } if(cs.isHiddenRotation(pid, index, level, type) != csToCompare.isHiddenRotation(pid, index, level, type)) { System.out.println(type + " != isHiddenRotation at " + index + " level " + level + " player " + pid); fail(); } if(cs.isHiddenCount(pid, index, level, type) != csToCompare.isHiddenCount(pid, index, level, type)) { System.out.println(type + " != isHiddenCount at " + index + " level " + level + " player " + pid); fail(); } } } if(!game.isStacking()) { if(cs.count(index, type) != csToCompare.count(index, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != Count at " + index); System.out.println("correct one is " + csToCompare.count(index, type)); System.out.println("undo one is " + cs.count(index, type)); fail(); } } if(cs.isEmpty(index, type) != csToCompare.isEmpty(index, type)) { System.out.println("IN MOVE " + trial.numberRealMoves() + " " + type + " != Empty at " + index); System.out.println("correct one is " + csToCompare.isEmpty(index, type)); System.out.println("undo one is " + cs.isEmpty(index, type)); fail(); } if(game.isBoardless() && type == game.board().defaultSite()) if(cs.isPlayable(index) != csToCompare.isPlayable(index)) { System.out.println(type + " != Playable at " + index); fail(); } } } } } // Check the trial data. if(trial.numTurns() != trialToCompare.numTurns()) { System.out.println("!= num of turns"); fail(); } if(trial.numForcedPasses() != trialToCompare.numForcedPasses()) { System.out.println("!= num forced passes"); fail(); } if(!trial.previousState().equals(trialToCompare.previousState())) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != previous states"); System.out.println("correct one is " + trialToCompare.previousState()); System.out.println("undo one is " + trial.previousState()); fail(); } if(!trial.previousStateWithinATurn().equals(trialToCompare.previousStateWithinATurn())) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != previous states within turn"); System.out.println("correct one is " + trialToCompare.previousStateWithinATurn()); System.out.println("undo one is " + trial.previousStateWithinATurn()); fail(); } // Check the state data. if(state.mover() != stateToCompare.mover()) { System.out.println("!= mover"); fail(); } if(state.prev() != stateToCompare.prev()) { System.out.println("!= prev"); fail(); } if(state.next() != stateToCompare.next()) { System.out.println("!= next"); fail(); } if(state.counter() != stateToCompare.counter()) { System.out.println("!= counter"); fail(); } if(state.temp() != stateToCompare.temp()) { System.out.println("!= tempValue"); fail(); } if(state.temp() != stateToCompare.temp()) { System.out.println("!= tempValue"); fail(); } if(state.pendingValues() != null) { if(state.pendingValues().size() != stateToCompare.pendingValues().size()) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != pendingValues"); System.out.println("correct one is " + stateToCompare.pendingValues()); System.out.println("undo one is " + state.pendingValues()); fail(); } else { final int[] pendingValuesUndo = state.pendingValues().toArray(); final int[] pendingValuesToCompare = stateToCompare.pendingValues().toArray(); for(int pendingValue : pendingValuesUndo) { boolean found = false; for(int pendingValueToCompare : pendingValuesToCompare) { if(pendingValue == pendingValueToCompare) { found = true; break; } } if(!found) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != pendingValues"); System.out.println("correct one is " + stateToCompare.pendingValues()); System.out.println("undo one is " + state.pendingValues()); fail(); } } } } for(int pid = 0; pid < game.players().size(); pid++) { if(state.amount(pid) != stateToCompare.amount(pid)) { System.out.println("!= amount for player " + pid); fail(); } } if(state.pot() != stateToCompare.pot()) { System.out.println("!= money pot"); fail(); } for(int pid = 0; pid < game.players().size(); pid++) { if(state.currentPhase(pid) != stateToCompare.currentPhase(pid)) { System.out.println("!= phase for player " + pid); fail(); } } if(state.sumDice() != null) { for(int indexHandDice = 0; indexHandDice < state.sumDice().length; indexHandDice++) if(state.sumDice(indexHandDice) != stateToCompare.sumDice(indexHandDice)) { System.out.println("!= sumDice for handDice " + indexHandDice); fail(); } } if(state.currentDice() != null) { for(int indexHandDice = 0; indexHandDice < state.currentDice().length; indexHandDice++) for(int indexDie = 0; indexDie < state.currentDice()[indexHandDice].length; indexDie++) if(state.currentDice()[indexHandDice][indexDie] != stateToCompare.currentDice()[indexHandDice][indexDie]) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != currentdice for handDice " + indexHandDice + " die index " + indexDie); System.out.println("correct one is " + stateToCompare.currentDice()[indexHandDice][indexDie]); System.out.println("undo one is " + state.currentDice()[indexHandDice][indexDie]); fail(); } } if(state.getValueMap() != null) { if(!state.getValueMap().equals(stateToCompare.getValueMap())) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != value Map"); System.out.println("correct one is " + stateToCompare.getValueMap()); System.out.println("undo one is " + state.getValueMap()); fail(); } } if(state.isDiceAllEqual() != stateToCompare.isDiceAllEqual()) { System.out.println("!= diceAllEqual"); fail(); } if(state.numTurnSamePlayer() != stateToCompare.numTurnSamePlayer()) { System.out.println("!= numTurnSamePlayer"); fail(); } if(state.numTurn() != stateToCompare.numTurn()) { System.out.println("!= numTurn"); fail(); } if(state.trumpSuit() != stateToCompare.trumpSuit()) { System.out.println("!= trumpSuit"); fail(); } if(state.propositions() != null) { if(!state.propositions().equals(stateToCompare.propositions())) { System.out.println("!= propositions"); fail(); } } if(state.votes() != null) { if(state.votes().size() != stateToCompare.votes().size()) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != votes"); System.out.println("correct one is " + stateToCompare.votes()); System.out.println("undo one is " + state.votes()); fail(); } else { final int[] votesUndo = state.votes().toArray(); final int[] votesToCompare = stateToCompare.votes().toArray(); for(int vote : votesUndo) { boolean found = false; for(int voteToCompare : votesToCompare) { if(vote == voteToCompare) { found = true; break; } } if(!found) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != votes"); System.out.println("correct one is " + stateToCompare.votes()); System.out.println("undo one is " + state.votes()); fail(); } } } } for(int pid = 1; pid < game.players().size(); pid++) { if(state.getValue(pid) != stateToCompare.getValue(pid)) { System.out.println("!= value player " + pid); fail(); } } if(state.isDecided() != stateToCompare.isDecided()) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != isDecided"); System.out.println("correct one is " + stateToCompare.isDecided()); System.out.println("undo one is " + state.isDecided()); fail(); } if(state.rememberingValues() != null) { if(!state.rememberingValues().equals(stateToCompare.rememberingValues())) { System.out.println("!= rememberingValues"); fail(); } } if(state.mapRememberingValues() != null) { if(!state.mapRememberingValues().equals(stateToCompare.mapRememberingValues())) { System.out.println("!= mapRememberingValues"); fail(); } } if(state.getNotes() != null) { if(!state.getNotes().equals(stateToCompare.getNotes())) { System.out.println("!= notes"); fail(); } } if(state.visited() != null) { if(!state.visited().equals(stateToCompare.visited())) { System.out.println("IN MOVE " + trial.numberRealMoves() +" != visited"); System.out.println("correct one is " + stateToCompare.visited()); System.out.println("undo one is " + state.visited()); fail(); } } if(state.sitesToRemove() != null) { if(!state.sitesToRemove().equals(stateToCompare.sitesToRemove())) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != sitesToRemove"); System.out.println("correct one is " + stateToCompare.sitesToRemove()); System.out.println("undo one is " + state.sitesToRemove()); fail(); } } for(int pid = 1; pid < game.players().size(); pid++) if(state.getTeam(pid) != stateToCompare.getTeam(pid)) { System.out.println("!= team player " + pid); fail(); } if(state.remainingDominoes() != null) { if(!state.remainingDominoes().equals(stateToCompare.remainingDominoes())) { System.out.println("!= remainingDominoes"); fail(); } } if(state.numConsecutivesPasses() != stateToCompare.numConsecutivesPasses()) { System.out.println("!= numConsecutivesPasses"); fail(); } if(state.storedState() != stateToCompare.storedState()) { System.out.println("!= storedState"); fail(); } if(state.onTrackIndices() != null) { if(!state.onTrackIndices().equals(stateToCompare.onTrackIndices())) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != onTrackIndices"); for(int i = 0; i < state.onTrackIndices().onTrackIndices().length; i++) { System.out.println("What is " + i); System.out.println("correct one is " + stateToCompare.onTrackIndices().whats(i)); System.out.println("undo one is " + state.onTrackIndices().whats(i)); } fail(); } } // Check the owned structure. for(int pid = 0; pid <= game.players().size(); pid++) { final Owned ownedUndo = state.owned(); final TIntArrayList ownedSitesUndo = ownedUndo.sites(pid); final List<? extends Location>[] ownedPositionsUndo = ownedUndo.positions(pid); final Owned ownedToCompare = stateToCompare.owned(); final TIntArrayList ownedSitesToCompare = ownedToCompare.sites(pid); final List<? extends Location>[] ownedPositionsToCompare = ownedToCompare.positions(pid); if(ownedSitesToCompare.size() != ownedSitesUndo.size()) { System.out.println("IN MOVE " + trial.numberRealMoves() + " != owned for pid = " + pid); System.out.println("correct one is"); for(int i = 0; i < ownedPositionsToCompare.length ;i++) for(Location loc: ownedPositionsToCompare[i]) System.out.println(loc.site() + " lvl = " + loc.level()); System.out.println("undo one is "); for(int i = 0; i < ownedPositionsUndo.length ;i++) for(Location loc: ownedPositionsUndo[i]) System.out.println(loc.site() + " lvl = " + loc.level()); fail(); } else { for(int i = 0; i < ownedPositionsUndo.length ;i++) for(Location loc: ownedPositionsUndo[i]) { final int site = loc.site(); final int level = loc.level(); boolean found = false; for(int j = 0; j < ownedPositionsToCompare.length ;j++) { for(Location locToCompare: ownedPositionsToCompare[j]) { final int siteToCompare = locToCompare.site(); final int levelToCompare = locToCompare.level(); if(site == siteToCompare && level == levelToCompare) { found = true; break; } } if(found) break; } if(!found) { System.out.println("IN MOVE " + trial.numberRealMoves() + " site " + site + " level = " + level +" should not be owned by " + pid); System.out.println("correct one is"); for(int j = 0; j < ownedPositionsToCompare.length ;j++) for(Location locToCompare: ownedPositionsToCompare[j]) System.out.println(locToCompare.site() + " lvl = " + locToCompare.level()); fail(); } } // for(int i = 0 ; i < ownedSitesUndo.size() ; i++) // { // final int site = ownedSitesUndo.get(i); // final int site = ownedSitesUndo.get(i); // if(!ownedSitesToCompare.contains(site)) // { // System.out.println("IN MOVE " + trial.numberRealMoves() + " site " + site + " should not be owned by " + pid); // } // } } } } // When undo, never has to be over. if (trial.over()) { System.out.println("Fail(): Testing undo trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } if(trial.numMoves() != moveIdx) System.out.println("Number of moves is wrong (currently = " + trial.numMoves()+") correct value should be " + moveIdx); assert(trial.numMoves() == moveIdx); final List<Action> loadedAllActions = loadedMoves.get(moveIdx-1).getActionsWithConsequences(context); final List<Action> trialMoveAllActions = trial.getMove(moveIdx-1).getActionsWithConsequences(context); assert (loadedAllActions.equals(trialMoveAllActions)) : ("Loaded Move Actions = " + loadedAllActions + ", trial actions = " + trialMoveAllActions); final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); final Moves legalMoves = game.moves(context); if (loadedTrial.auxilTrialData() != null) { if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); for(Move move : legalMoves.moves()) System.out.println(move.getActionsWithConsequences(context)); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } assert (legalMoves.moves().size() == loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - trial.numInitialPlacementMoves())); } if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { final List<Action> moveAllActions = move.getActionsWithConsequences(context); if(moveAllActions.size() == loadedMoveAllActions.size()) { boolean moveFound = true; for(Action action: moveAllActions) { if(!loadedMoveAllActions.contains(action)) { moveFound = false; break; } } if(moveFound) { matchingMove = move; break; } } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMove.getActionsWithConsequences(context) + " from is " + loadedMove.fromType() + " to is " + loadedMove.toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } } assert (matchingMove != null); } moveIdx--; } // simultaneous-move game // else // { // // the full loaded move should be equal to one of the possible large combined moves // final FastArrayList<Move> legal = legalMoves.moves(); // // final int numPlayers = game.players().count(); // @SuppressWarnings("unchecked") // final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; // final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); // // for (int p = 1; p <= numPlayers; ++p) // { // legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); // // final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); // for (int i = 0; i < legalPerPlayer[p].size(); ++i) // { // legalMoveIndices.add(Integer.valueOf(i)); // } // legalMoveIndicesPerPlayer.add(legalMoveIndices); // } // // final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); // // boolean foundMatch = false; // for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) // { // // Combined all the per-player moves for this combination of indices // final List<Action> actions = new ArrayList<>(); // final List<Moves> topLevelCons = new ArrayList<Moves>(); // // for (int p = 1; p <= numPlayers; ++p) // { // final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); // if (move != null) // { // final Move moveToAdd = new Move(move.actions()); // actions.add(moveToAdd); // // if (move.then() != null) // { // for (int i = 0; i < move.then().size(); ++i) // { // if (move.then().get(i).applyAfterAllMoves()) // topLevelCons.add(move.then().get(i)); // else // moveToAdd.then().add(move.then().get(i)); // } // } // } // } // // final Move combinedMove = new Move(actions); // combinedMove.setMover(numPlayers + 1); // combinedMove.then().addAll(topLevelCons); // // final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); // if (loadedMoveAllActions.equals(combinedMoveAllActions)) // { // foundMatch = true; // break; // } // } // // if (!foundMatch) // { // System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); // fail(); // } // // game.apply(context, loadedMoves.get(moveIdx)); // } // if (trial.status() == null) // { // if (loadedTrial.status() != null) // System.out // .println("Game not over but should be in moveIdx = " // + (moveIdx - trial.numInitialPlacementMoves())); // assert (loadedTrial.status() == null); // } // else // assert (trial.status().winner() == loadedTrial.status().winner()); // // assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } } System.out.println("Finished TestTrialsUndo!"); final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0; final int seconds = (int) (allSeconds % 60.0); final int minutes = (int) ((allSeconds - seconds) / 60.0); System.out.println("Done in " + minutes + " minutes " + seconds + " seconds"); } }
37,134
34.13245
175
java
Ludii
Ludii-master/Player/test/games/TokensTest.java
package games; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Test; import main.FileHandling; /** * Unit Test to count the number of Tokens for each game * * @author Eric.Piette */ public class TokensTest { @Test public static void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<>(); gameDirs.add(startFolder); // We compute the .lud files (and not the ludemeplex). final List<File> entries = new ArrayList<>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { if (fileEntry.getPath().equals("..\\Common\\res\\lud\\plex")) continue; if (fileEntry.getPath().equals("..\\Common\\res\\lud\\wip")) continue; if (fileEntry.getPath().equals("..\\Common\\res\\lud\\test")) continue; if (fileEntry.getPath().equals("..\\Common\\res\\lud\\bad")) continue; // We'll find files that we should be able to compile here gameDirs.add(fileEntry); } else if (fileEntry.getName().endsWith(".lud") || fileEntry.getName().endsWith(".rbg")) { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; // String line = null; try { // final FileReader fileReader = new FileReader(fileName); // final BufferedReader bufferedReader = new BufferedReader(fileReader); // while ((line = bufferedReader.readLine()) != null) // desc += line + "\n"; // bufferedReader.close(); desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } int tokens = 0; boolean onAToken = false; String currentToken = ""; for (int i = 0; i < desc.length(); i++) { if (desc.charAt(i) != ' ' && desc.charAt(i) != '(' && desc.charAt(i) != ')' && desc.charAt(i) != '}' && desc.charAt(i) != '{' && desc.charAt(i) != '\n') { if (!onAToken) onAToken = true; currentToken += desc.charAt(i); } else { if (currentToken.equals("metadata")) { break; } else if (onAToken) { tokens++; onAToken = false; currentToken = ""; } } } System.out.println(tokens + " tokens for " + fileName); } else if (fileEntry.getName().contains(".rbg")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; // String line = null; try { // final FileReader fileReader = new FileReader(fileName); // final BufferedReader bufferedReader = new BufferedReader(fileReader); // while ((line = bufferedReader.readLine()) != null) // desc += line + "\n"; // bufferedReader.close(); desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } int tokens = 0; boolean onAToken = false; for(int i = 0 ; i < desc.length() ; i++) { if (desc.charAt(i) != ' ' && desc.charAt(i) != '(' && desc.charAt(i) != ')' && desc.charAt(i) != '}' && desc.charAt(i) != '{' && desc.charAt(i) != '$' && desc.charAt(i) != '\n' && desc.charAt(i) != ',' && desc.charAt(i) != ';' && desc.charAt(i) != '=' && desc.charAt(i) != '=' && desc.charAt(i) != '^' && desc.charAt(i) != '+' && desc.charAt(i) != '-' && desc.charAt(i) != '/' && desc.charAt(i) != '*' && desc.charAt(i) != '\n') { if (!onAToken) onAToken = true; } else { if (onAToken) { tokens++; onAToken=false; } } } System.out.println(tokens + " tokens for " + fileName); } } } }
4,474
25.323529
433
java
Ludii
Ludii-master/Player/test/games/UCBCacheTest.java
package games; import java.util.HashMap; import java.util.Map; import org.junit.Test; //----------------------------------------------------------------------------- /** * Test whether caching of UCB calculation helps. * @author cambolbro */ public class UCBCacheTest { private static final double C = 0.5; int numUCB; final Map<Long, Double> ucbMap = new HashMap<>(); //------------------------------------------------------------------------- @Test public void test() { //fail("Not yet implemented"); System.out.println("UCB cache test."); final int numTests = 10; // Without map numUCB = 0; long startAt = System.nanoTime(); for (int test = 0; test < numTests; test++) makeTree(false); long endAt = System.nanoTime(); double secs = (endAt - startAt) / 1000000000.0; System.out.println("Without : " + numTests + " tests in " + secs + "s."); System.out.println((numUCB / numTests) + " UCB on average per test."); // With map numUCB = 0; startAt = System.nanoTime(); for (int test = 0; test < numTests; test++) makeTree(true); endAt = System.nanoTime(); secs = (endAt - startAt) / 1000000000.0; System.out.println("With map: " + numTests + " tests in " + secs + "s."); System.out.println((numUCB / numTests) + " UCB on average per test."); System.out.println("ucbMap has " + ucbMap.size() + " entries."); } //------------------------------------------------------------------------- void makeTree(final boolean useMap) { final Node root = new Node(-1, null); final int numIterations = 1000000; for (int n = 0; n < numIterations; n++) { Node node = descend(root, useMap); node = expand(node); node.visit(); } // System.out.println("Tree size " + root.size() + "."); } //------------------------------------------------------------------------- Node descend(final Node nodeIn, final boolean useMap) { Node node = nodeIn; while (node.allVisited()) node = ucb(node, useMap); return node; } //------------------------------------------------------------------------- @SuppressWarnings("static-method") Node expand(final Node parent) { final Node child = new Node(parent.choose(), parent); parent.children().add(child); return child; } //------------------------------------------------------------------------- @SuppressWarnings("static-method") Long key(final int parentVisits, final int childVisits) { return Long.valueOf((((long) parentVisits) << 32) | childVisits); } //------------------------------------------------------------------------- Node ucb(final Node parent, final boolean useMap) { Node choice = null; double bestScore = -1000; numUCB++; if (useMap) { double parentLog = -1; //Math.log(Math.max(1, parent.visits())); for (final Node child : parent.children()) { final double exploit = 0.5; // remove reward variation double explore = 0; final Long key = key(parent.visits(), child.visits()); final Double item = ucbMap.get(key); if (item == null) { if (parentLog == -1) parentLog = Math.log(Math.max(1, parent.visits())); explore = Math.sqrt(2 * parentLog / child.visits()); ucbMap.put(key, Double.valueOf(explore)); } else { explore = item.doubleValue(); } final double score = exploit + C * explore; if (score > bestScore) { bestScore = score; choice = child; } } } else { final double parentLog = Math.log(Math.max(1, parent.visits())); for (final Node child : parent.children()) { final double exploit = 0.5; // remove reward variation final double explore = Math.sqrt(2 * parentLog / child.visits()); final double score = exploit + C * explore; if (score > bestScore) { bestScore = score; choice = child; } } } return choice; } }
3,868
23.487342
79
java
Ludii
Ludii-master/Player/test/games/WarningCrashTest.java
package games; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import main.FileHandling; import main.grammar.Description; import other.GameLoader; /** * Unit Test for testing that no game has any required ludeme or will crash. * * @author Eric.Piette */ public class WarningCrashTest { @Test @SuppressWarnings("static-method") public void runTests() { // Load from memory final String[] choices = FileHandling.listGames(); for (final String filePath : choices) { if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; // Get game description from resource // System.out.println("Game: " + filePath); String path = filePath.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { e1.printStackTrace(); fail(); } // Parse and compile the game Game game = null; try { game = (Game)compiler.Compiler.compileTest(new Description(desc), false); } catch (final Exception e) { System.err.println("** FAILED TO COMPILE: " + filePath + "."); e.printStackTrace(); fail(); } if (game != null) { System.out.println("Compiled " + game.name() + "."); final int indexLastSlash = filePath.lastIndexOf('/'); final String fileName = filePath.substring(indexLastSlash + 1, filePath.length() - ".lud".length()); if (!fileName.equals(game.name())) { System.err.println("The fileName of " + fileName + ".lud is not equals to the name of the game which is " + game.name()); fail(); } } else { System.err.println("** FAILED TO COMPILE: " + filePath + "."); fail(); } if (game.hasMissingRequirement()) { System.err.println(game.name() + " has missing requirements."); fail(); } if (game.willCrash()) { System.err.println(game.name() + " is going to crash."); fail(); } } } }
2,852
22.195122
104
java
Ludii
Ludii-master/Player/test/games/options/CompilationTestWithOptions.java
package games.options; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import main.StringRoutines; import main.collections.ListUtils; import main.options.Option; import other.GameLoader; //----------------------------------------------------------------------------- /** * Unit Test to compile all the games on the lud folder, with all possible * combinations of options. * * @author Dennis Soemers and Eric.Piette and cambolbro */ public class CompilationTestWithOptions { @Test public static void testCompilingLudFromFile() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<>(); gameDirs.add(startFolder); // We compute the .lud files (and not the ludemeplex). final List<File> entries = new ArrayList<>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/bad")) continue; gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } // Test of compilation for each of them. for (final File fileEntry : entries) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); final Game game = GameLoader.loadGameFromFile(fileEntry); assert (game != null); final List<List<String>> optionCategories = new ArrayList<List<String>>(); for (int o = 0; o < game.description().gameOptions().numCategories(); o++) { final List<Option> options = game.description().gameOptions().categories().get(o).options(); final List<String> optionCategory = new ArrayList<String>(); for (int i = 0; i < options.size(); i++) { final Option option = options.get(i); optionCategory.add(StringRoutines.join("/", option.menuHeadings().toArray(new String[0]))); } if (optionCategory.size() > 0) optionCategories.add(optionCategory); } final List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories); if (optionCombinations.size() > 1) { for (final List<String> optionCombination : optionCombinations) { System.out.println("Compiling with options: " + optionCombination); assert (GameLoader.loadGameFromFile(fileEntry, optionCombination) != null); } } } } }
2,857
24.517857
96
java
Ludii
Ludii-master/Player/test/games/options/OnePlayoutPerGameTestWithOptions.java
package games.options; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import main.StringRoutines; import main.collections.ListUtils; import main.options.Option; import other.GameLoader; import other.context.Context; import other.trial.Trial; /** * Unit Test to run one playout per game, for every possible * combination of options * * @author Eric.Piette, Dennis Soemers and cambolbro */ public class OnePlayoutPerGameTestWithOptions { @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } // The following entries should correctly compile and run for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); final Game game = GameLoader.loadGameFromFile(fileEntry); System.out.println(game.name()); assert (game != null); final List<List<String>> optionCategories = new ArrayList<List<String>>(); for (int o = 0; o < game.description().gameOptions().numCategories(); o++) { final List<Option> options = game.description().gameOptions().categories().get(o).options(); final List<String> optionCategory = new ArrayList<String>(); for (int i = 0; i < options.size(); i++) { final Option option = options.get(i); optionCategory.add(StringRoutines.join("/", option.menuHeadings().toArray(new String[0]))); } if (optionCategory.size() > 0) optionCategories.add(optionCategory); } final List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories); // If no option (just the default game) we do not run the test. if (optionCombinations.size() == 1) continue; for (final List<String> optionCombination : optionCombinations) { System.out.println("Compiling and running playout with options: " + optionCombination); final Game gameWithOptions = GameLoader.loadGameFromFile(fileEntry, optionCombination); final Trial trial = new Trial(gameWithOptions); final Context context = new Context(gameWithOptions, trial); gameWithOptions.start(context); gameWithOptions.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); } } } } }
3,605
26.112782
97
java
Ludii
Ludii-master/Player/test/games/options/TestHexOptions.java
package games.options; import java.util.ArrayList; import java.util.List; import org.junit.Test; import game.Game; import other.GameLoader; /** * A small unit test to make sure that we can correctly compile * Hex with options. This unit test tries a couple of different * board sizes and makes sure we end up with a board with the * correct number of cells. * * @author Dennis Soemers */ public class TestHexOptions { @Test public static void testHexBoardSizes() { final List<String> options = new ArrayList<String>(); // First load default Hex (should be 11x11 board --> 121 cells) final Game defaultHex = GameLoader.loadGameFromName("/Hex.lud"); assert(defaultHex.board().numSites() == 121); // Now try 3x3 Hex (9 cells) options.add("Board Size/3x3"); final Game hexThreeByThree = GameLoader.loadGameFromName("/Hex.lud", options); assert(hexThreeByThree.board().numSites() == 9); // Finally try 15x15 Hex (225 cells) options.clear(); options.add("Board Size/15x15"); final Game hexFifteenByFifteen = GameLoader.loadGameFromName("/Hex.lud", options); assert(hexFifteenByFifteen.board().numSites() == 225); } }
1,164
25.477273
84
java
Ludii
Ludii-master/Player/test/games/options/TestParallelPlayoutsWithOptions.java
package games.options; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.StringRoutines; import main.collections.FastArrayList; import main.collections.ListUtils; import main.options.Option; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * Unit test that, for every game, and for all combinations of options, * tests whether we can correctly run playouts in parallel. * * @author Dennis Soemers */ public class TestParallelPlayoutsWithOptions { /** Number of parallel playouts we run */ private static final int NUM_PARALLEL = 4; /** * The test to run. */ @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("Trying game file: " + fileName); final Game gameNoOptions = GameLoader.loadGameFromFile(fileEntry); final List<List<String>> optionCategories = new ArrayList<List<String>>(); for (int o = 0; o < gameNoOptions.description().gameOptions().numCategories(); o++) { final List<Option> options = gameNoOptions.description().gameOptions().categories().get(o).options(); final List<String> optionCategory = new ArrayList<String>(); for (int i = 0; i < options.size(); i++) { final Option option = options.get(i); optionCategory.add(StringRoutines.join("/", option.menuHeadings().toArray(new String[0]))); } if (optionCategory.size() > 0) optionCategories.add(optionCategory); } final List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories); for (final List<String> optionCombination : optionCombinations) { System.out.println("Parallel Playouts test with options: " + optionCombination); final Game gameWithOptions = GameLoader.loadGameFromFile(fileEntry, optionCombination); // run parallel trials final Context[] contexts = new Context[NUM_PARALLEL]; final RandomProviderDefaultState[] gameStartRngStates = new RandomProviderDefaultState[NUM_PARALLEL]; for (int i = 0; i < NUM_PARALLEL; ++i) { contexts[i] = new Context(gameWithOptions, new Trial(gameWithOptions)); gameStartRngStates[i] = (RandomProviderDefaultState) contexts[i].rng().saveState(); } final ExecutorService executorService = Executors.newFixedThreadPool(NUM_PARALLEL); final List<Future<Context>> playedContexts = new ArrayList<Future<Context>>(NUM_PARALLEL); for (int i = 0; i < NUM_PARALLEL; ++i) { final Context context = contexts[i]; playedContexts.add(executorService.submit(() -> { gameWithOptions.start(context); gameWithOptions.playout(context, null, 1.0, null, 0, 30, ThreadLocalRandom.current()); return context; })); } // store outcomes of all parallel trials final Context[] endContexts = new Context[NUM_PARALLEL]; try { for (int i = 0; i < NUM_PARALLEL; ++i) { endContexts[i] = playedContexts.get(i).get(); } } catch (final InterruptedException | ExecutionException e) { e.printStackTrace(); fail(); } // check if we can still execute them all the same way in serial mode for (int parallelPlayout = 0; parallelPlayout < NUM_PARALLEL; ++parallelPlayout) { final Context parallelContext = endContexts[parallelPlayout]; final Trial parallelTrial = parallelContext.trial(); final List<Move> loadedMoves = parallelTrial.generateCompleteMovesList(); final Trial trial = new Trial(gameWithOptions); final Context context = new Context(gameWithOptions, trial); context.rng().restoreState(gameStartRngStates[parallelPlayout]); gameWithOptions.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { assert(loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in ByScore End condition) // so we just check if they're equal, without applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context).equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context) ); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Serial trial already over after moves:"); for (final Move move : trial.generateCompleteMovesList()) { System.out.println(move); } System.out.println("When run in parallel, trial only ended after moves:"); for (final Move move : parallelTrial.generateCompleteMovesList()) { System.out.println(move); } fail(); } final Moves legalMoves = gameWithOptions.moves(context); final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (gameWithOptions.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { System.out.println("No matching move found for: " + loadedMoveAllActions); for (final Move move : legalMoves.moves()) { System.out.println("legal move: " + move.getActionsWithConsequences(context)); } fail(); } //assert(matchingMove != null); gameWithOptions.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = gameWithOptions.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } gameWithOptions.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert(parallelTrial.status() == null); else assert(trial.status().winner() == parallelTrial.status().winner()); if (!Arrays.equals(context.trial().ranking(), parallelContext.trial().ranking())) { System.out.println("Ranking when run in parallel: " + Arrays.toString(parallelContext.trial().ranking())); System.out.println("Ranking when run serially: " + Arrays.toString(context.trial().ranking())); fail(); } // we're done with this one, let's allow memory to be cleared endContexts[parallelPlayout] = null; } } } } } }
11,815
31.640884
139
java
Ludii
Ludii-master/Player/test/games/symmetry/TestCanonicalHashes.java
package games.symmetry; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; import game.Game; import main.Constants; import other.GameLoader; import other.action.move.ActionAdd; import other.context.Context; import other.move.Move; import other.state.symmetry.AcceptNone; import other.state.symmetry.ReflectionsOnly; import other.state.symmetry.RotationsOnly; import other.state.symmetry.SubstitutionsOnly; import other.topology.Cell; import other.trial.Trial; public class TestCanonicalHashes { /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testPlayerEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); // Game 1 has a white piece at cell #0, game 2 has a black piece add(game1, context1, 0, 1); add(game2, context2, 0, 2); Assert.assertEquals ( context1.state().canonicalHash(new SubstitutionsOnly(), false), context2.state().canonicalHash(new SubstitutionsOnly(), false) ); } /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testPlayerNonEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); // Game 1 has a white piece at cell #0, game 2 has a black piece add(game1, context1, 0, 1); add(game2, context2, 0, 2); Assert.assertNotEquals ( context1.state().canonicalHash(new AcceptNone(), false), context2.state().canonicalHash(new AcceptNone(), false) ); } /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testRotationEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); final List<Cell> cells = context1.containers()[0].topology().cells(); final Map<String, Integer> nameToCell = new HashMap<>(); for (int c = 0; c < cells.size(); c++) { nameToCell.put(cells.get(c).label(), Integer.valueOf(c)); } final boolean whoOnly = false; // Two cells chosen to have rotational symmetry only... add(game1, context1, nameToCell.get("B12").intValue(), 1); add(game2, context2, nameToCell.get("T10").intValue(), 1); Assert.assertEquals ( context1.state().canonicalHash(new RotationsOnly(), whoOnly), context2.state().canonicalHash(new RotationsOnly(), whoOnly) ); // Centre... add(game1, context1, nameToCell.get("K11").intValue(), 1); add(game2, context2, nameToCell.get("K11").intValue(), 1); Assert.assertEquals ( context1.state().canonicalHash(new RotationsOnly(), whoOnly), context2.state().canonicalHash(new RotationsOnly(), whoOnly) ); // Break the symmetry... add(game1, context1, nameToCell.get("A11").intValue(), 1); add(game2, context2, nameToCell.get("F8").intValue(), 1); Assert.assertNotEquals ( context1.state().canonicalHash(new RotationsOnly(), whoOnly), context2.state().canonicalHash(new RotationsOnly(), whoOnly) ); } /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testRotationNonEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); final List<Cell> cells = context1.containers()[0].topology().cells(); final Map<String,Integer> nameToCell = new HashMap<>(); for (int c = 0; c < cells.size(); c++) { System.out.println(cells.get(c).label()); nameToCell.put(cells.get(c).label(), Integer.valueOf(c)); } // Two cells chosen to have rotational symmetry only... add(game1, context1, nameToCell.get("B12").intValue(), 1); add(game2, context2, nameToCell.get("T10").intValue(), 1); // Different with no symmetry Assert.assertNotEquals ( context1.state().canonicalHash(new AcceptNone(), false), context2.state().canonicalHash(new AcceptNone(), false) ); } /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testReflectionEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); final List<Cell> cells = context1.containers()[0].topology().cells(); final Map<String, Integer> nameToCell = new HashMap<>(); for (int c = 0; c < cells.size(); c++) { nameToCell.put(cells.get(c).label(), Integer.valueOf(c)); } // Two cells chosen to have reflection... final boolean whoOnly = false; // Note that reflections alone don't give the full set of hashes, so reflection canonical hashes are flawed unless there is half-turn symmetry add(game1, context1, nameToCell.get("B10").intValue(), 1); add(game2, context2, nameToCell.get("B12").intValue(), 1); add(game1, context1, nameToCell.get("T10").intValue(), 1); add(game2, context2, nameToCell.get("T12").intValue(), 1); Assert.assertEquals ( context1.state().canonicalHash(new ReflectionsOnly(), whoOnly), context2.state().canonicalHash(new ReflectionsOnly(), whoOnly) ); // Centre... add(game1, context1, nameToCell.get("K11").intValue(), 1); add(game2, context2, nameToCell.get("K11").intValue(), 1); Assert.assertEquals ( context1.state().canonicalHash(new ReflectionsOnly(), whoOnly), context2.state().canonicalHash(new ReflectionsOnly(), whoOnly) ); // Break the symmetry... add(game1, context1, nameToCell.get("G13").intValue(), 1); add(game2, context2, nameToCell.get("G15").intValue(), 1); Assert.assertNotEquals ( context1.state().canonicalHash(new ReflectionsOnly(), whoOnly), context2.state().canonicalHash(new ReflectionsOnly(), whoOnly) ); final Game game3 = GameLoader.loadGameFromName("board/space/blocking/Mu Torere.lud"); final Trial trial3 = new Trial(game3); final Context context3 = new Context(game3, trial3); game3.start(context3); final Game game4 = GameLoader.loadGameFromName("board/space/blocking/Mu Torere.lud"); final Trial trial4 = new Trial(game4); final Context context4 = new Context(game4, trial4); game4.start(context4); Assert.assertEquals ( context3.state().canonicalHash(new ReflectionsOnly(), whoOnly), context4.state().canonicalHash(new ReflectionsOnly(), whoOnly) ); } /** * Plays different 2 hex moves, verifies canonical hash is the same */ @Test public static void testReflectionNonEquivalence() { final Game game1 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); final Game game2 = GameLoader.loadGameFromName("board/space/connection/Hex.lud"); final Trial trial2 = new Trial(game2); final Context context2 = new Context(game2, trial2); game2.start(context2); final List<Cell> cells = context1.containers()[0].topology().cells(); final Map<String, Integer> nameToCell = new HashMap<>(); for (int c = 0; c < cells.size(); c++) { nameToCell.put(cells.get(c).label(), Integer.valueOf(c)); } // Note that reflections alone don't give the full set of hashes, so reflection canonical hashes are flawed unless there is half-turn symmetry add(game1, context1, nameToCell.get("B10").intValue(), 1); add(game2, context2, nameToCell.get("S13").intValue(), 1); add(game1, context1, nameToCell.get("T10").intValue(), 1); add(game2, context2, nameToCell.get("T12").intValue(), 1); // Different with no symmetry Assert.assertNotEquals ( context1.state().canonicalHash(new AcceptNone(), false), context2.state().canonicalHash(new AcceptNone(), false) ); } private static void add(final Game game, final Context context, final int cell, final int who) { game.apply(context, new Move(new ActionAdd(null, cell, who, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null) .withDecision(true)).withFrom(cell).withTo(cell)); } }
9,565
32.921986
144
java
Ludii
Ludii-master/Player/test/games/symmetry/TestHexSymmetries.java
package games.symmetry; import org.junit.Assert; import org.junit.Test; import game.equipment.container.Container; import game.equipment.container.board.Board; import game.functions.dim.DimConstant; import game.functions.graph.generators.basis.hex.HexagonOnHex; import game.types.board.SiteType; import other.topology.Topology; import other.topology.TopologyElement; public class TestHexSymmetries { @Test public static void testHexRotations() { final Board board = createBoard(); Container.createSymmetries(board.topology()); testOneRotation(board.topology().cellRotationSymmetries()); testOneRotation(board.topology().edgeRotationSymmetries()); testOneRotation(board.topology().vertexRotationSymmetries()); } @Test public static void testHexReflections() { final Board board = createBoard(); Container.createSymmetries(board.topology()); testOneReflection(board.topology().cellReflectionSymmetries()); testOneReflection(board.topology().edgeReflectionSymmetries()); testOneReflection(board.topology().vertexReflectionSymmetries()); } private static Board createBoard() { final Board board = new Board(new HexagonOnHex(new DimConstant(5)), null, null, null, null, SiteType.Cell, Boolean.FALSE); board.createTopology(0, 0); final Topology topology = board.topology(); for (final SiteType type : SiteType.values()) { topology.computeRelation(type); topology.computeSupportedDirection(type); // Convert the properties to the list of each pregeneration. for (final TopologyElement element : topology.getGraphElements(type)) topology.convertPropertiesToList(type, element); topology.crossReferencePhases(type); topology.computeRows(type, false); topology.computeColumns(type, false); topology.computeLayers(type); topology.computeCoordinates(type); topology.preGenerateDistanceTables(type); topology.computeDoesCross(); } topology.optimiseMemory(); return board; } private static void testOneRotation(final int[][] syms) { Assert.assertEquals("Hexagonal rotational symmetries", 6, syms.length); // Properties = rotation of zero is the identity // rotation[1].rotation[3] is the identity // rotation[2].rotation[2] is the identity int different5 = 0; int different4 = 0; int different3 = 0; int different2 = 0; int different1 = 0; int different0 = 0; for (int idx = 0; idx < syms.length; idx++) { final int r0 = syms[0][idx]; final int r1 = syms[1][idx]; final int r2 = syms[2][idx]; final int r3 = syms[3][idx]; final int r4 = syms[4][idx]; final int r5 = syms[5][idx]; if (r0 != idx) different0++; if (r1 != idx) different1++; if (r2 != idx) different2++; if (r3 != idx) different3++; if (r4 != idx) different4++; if (r5 != idx) different5++; // Each reflection should be its own dual Assert.assertEquals("rotation by 0 is identity", idx, r0); Assert.assertEquals("rot(1/6)+rot(5/6) is identity", idx, syms[1][r5]); Assert.assertEquals("rot(2/6)+rot(4/6) is identity", idx, syms[2][r4]); Assert.assertEquals("rot(3/6)+rot(3/6) is identity", idx, syms[3][r3]); Assert.assertEquals("rot(4/6)+rot(2/6) is identity", idx, syms[4][r2]); Assert.assertEquals("rot(5/6)+rot(1/6) is identity", idx, syms[5][r1]); } Assert.assertTrue("rotation by 0 is identity", different0 == 0); Assert.assertTrue("Some rotations by 1/6 should be different", different1 > 0); Assert.assertTrue("Some rotations by 2/6 should be different", different2 > 0); Assert.assertTrue("Some rotations by 3/6 should be different", different3 > 0); Assert.assertTrue("Some rotations by 4/6 should be different", different4 > 0); Assert.assertTrue("Some rotations by 5/6 should be different", different5 > 0); } private static void testOneReflection(final int[][] syms) { Assert.assertEquals("Hexagonal reflection symmetries", 6, syms.length); int different = 0; for (final int[] symmetry : syms) { for (int idx = 0; idx < symmetry.length; idx++) { final int reflected = symmetry[idx]; final int restored = symmetry[reflected]; if (idx!= reflected) different++; // Each reflection should be its own dual Assert.assertEquals("Invariant under double reflection", idx, restored); } } Assert.assertTrue("Some reflections should be different", different > 0); } }
4,404
30.464286
124
java
Ludii
Ludii-master/Player/test/games/symmetry/TestSmallGameHashes.java
package games.symmetry; import org.junit.Test; import game.Game; import other.GameLoader; import other.context.Context; import other.state.symmetry.AcceptAll; import other.trial.Trial; public class TestSmallGameHashes { @Test public static void testBicycleGameDoesntCrash() { final Game game1 = GameLoader.loadGameFromName("board/war/other/Ja-Jeon-Geo-Gonu.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); context1.state().canonicalHash(new AcceptAll(), true); } @Test public static void testBoseogGonuGameDoesntCrash() { final Game game1 = GameLoader.loadGameFromName("board/war/other/Boseog Gonu.lud"); final Trial trial1 = new Trial(game1); final Context context1 = new Context(game1, trial1); game1.start(context1); context1.state().canonicalHash(new AcceptAll(), true); } }
887
24.371429
89
java
Ludii
Ludii-master/Player/test/games/symmetry/TestSquareSymmetries.java
package games.symmetry; import org.junit.Assert; import org.junit.Test; import game.equipment.container.Container; import game.equipment.container.board.Board; import game.functions.dim.DimConstant; import game.functions.graph.generators.basis.square.RectangleOnSquare; import game.types.board.SiteType; import other.topology.Topology; import other.topology.TopologyElement; /** * JUnit test for the pregeneration of square tiling for a square shape. * * @author Eric.Piette * */ public class TestSquareSymmetries { @Test public static void testSquareRotations() { final Board board = createBoard(); Container.createSymmetries(board.topology()); testOneRotation(board.topology().cellRotationSymmetries()); testOneRotation(board.topology().edgeRotationSymmetries()); testOneRotation(board.topology().vertexRotationSymmetries()); } @Test public static void testSquareReflections() { final Board board = createBoard(); Container.createSymmetries(board.topology()); testOneReflection(board.topology().cellReflectionSymmetries()); testOneReflection(board.topology().edgeReflectionSymmetries()); testOneReflection(board.topology().vertexReflectionSymmetries()); } private static Board createBoard() { final Board board = new Board(new RectangleOnSquare(new DimConstant(8), null, null, null), null, null, null, null, null, Boolean.FALSE); board.createTopology(0, 0); final Topology topology = board.topology(); for (final SiteType type : SiteType.values()) { topology.computeRelation(type); topology.computeSupportedDirection(type); // Convert the properties to the list of each pregeneration. for (final TopologyElement element : topology.getGraphElements(type)) topology.convertPropertiesToList(type, element); topology.crossReferencePhases(type); topology.computeRows(type, false); topology.computeColumns(type, false); topology.computeLayers(type); topology.computeCoordinates(type); topology.preGenerateDistanceTables(type); topology.computeDoesCross(); } topology.optimiseMemory(); return board; } private static void testOneRotation(final int[][] syms) { Assert.assertEquals("Square rotational symmetries", 4, syms.length); // Properties = rotation of zero is the identity // rotation[1].rotation[3] is the identity // rotation[2].rotation[2] is the identity int different3 = 0; int different2 = 0; int different1 = 0; int different0 = 0; for (int idx = 0; idx < syms.length; idx++) { final int r0 = syms[0][idx]; final int r1 = syms[1][idx]; final int r2 = syms[2][idx]; final int r3 = syms[3][idx]; if (r0 != idx) different0++; if (r1 != idx) different1++; if (r2 != idx) different2++; if (r3 != idx) different3++; // Each reflection should be its own dual Assert.assertEquals("rotation by 0 is identity", idx, r0); Assert.assertEquals("rotation by 1/4 is inverse of rotation by 3/4", idx, syms[3][r1]); Assert.assertEquals("rotation by 3/4 is inverse of rotation by 1/4", idx, syms[1][r3]); Assert.assertEquals("rotation by 1/2 is inverse of itself", idx, syms[2][r2]); } Assert.assertTrue("rotation by 0 is identity", different0 == 0); Assert.assertTrue("Some rotations by 1/4 should be different", different1 > 0); Assert.assertTrue("Some rotations by 1/2 should be different", different2 > 0); Assert.assertTrue("Some rotations by 3/4 should be different", different3 > 0); } private static void testOneReflection(final int[][] syms) { Assert.assertEquals("Reflection symmetries", 4, syms.length); int different = 0; for (final int[] symmetry : syms) { for (int idx = 0; idx < symmetry.length; idx++) { final int reflected = symmetry[idx]; final int restored = symmetry[reflected]; if (idx!= reflected) different++; // Each reflection should be its own dual Assert.assertEquals("Invariant under double reflection", idx, restored); } } Assert.assertTrue("Some reflections should be different", different > 0); } }
4,091
28.652174
98
java
Ludii
Ludii-master/Player/test/other/TestChunkSets.java
package other; import static org.junit.Assert.assertEquals; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; import gnu.trove.list.array.TIntArrayList; import main.collections.ChunkSet; /** * Some tests for ChunkSets * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestChunkSets { @Test public void testViolatesNotA() { // State chunkset: 0011 1111 0011 0001 0111 final ChunkSet s = new ChunkSet(4, 5); s.setChunk(0, 3); s.setChunk(1, 15); s.setChunk(2, 3); s.setChunk(3, 1); s.setChunk(4, 7); // Pattern chunkset: 1111 0111 0000 0111 0111 final ChunkSet p = new ChunkSet(4, 5); p.setChunk(0, 15); p.setChunk(1, 7); p.setChunk(2, 0); p.setChunk(3, 7); p.setChunk(4, 7); // Mask chunkset: 1111 1111 1111 1111 1111 final ChunkSet m = new ChunkSet(4, 5); m.set(0, 4 * 5); // The last chunk is same for both state and pattern, so we violate the "not" pattern assert(s.violatesNot(m, p)); } @Test public void testViolatesNotB() { // State chunkset: 0011 1111 0011 0001 0111 final ChunkSet s = new ChunkSet(4, 5); s.setChunk(0, 3); s.setChunk(1, 15); s.setChunk(2, 3); s.setChunk(3, 1); s.setChunk(4, 7); // Pattern chunkset: 1111 0111 0000 0111 0110 final ChunkSet p = new ChunkSet(4, 5); p.setChunk(0, 15); p.setChunk(1, 7); p.setChunk(2, 0); p.setChunk(3, 7); p.setChunk(4, 6); // Mask chunkset: 1111 1111 1111 1111 1111 final ChunkSet m = new ChunkSet(4, 5); m.set(0, 4 * 5); // No chunks same for both state and pattern, so we do not violate the "not" pattern assert(!s.violatesNot(m, p)); } @Test public void testViolatesNotC() { // State chunkset: 0011 1111 0011 0001 0111 final ChunkSet s = new ChunkSet(4, 5); s.setChunk(0, 3); s.setChunk(1, 15); s.setChunk(2, 3); s.setChunk(3, 1); s.setChunk(4, 7); // Pattern chunkset: 1111 0111 0000 0111 0000 final ChunkSet p = new ChunkSet(4, 5); p.setChunk(0, 15); p.setChunk(1, 7); p.setChunk(2, 0); p.setChunk(3, 7); p.setChunk(4, 0); // Mask chunkset: 1111 1111 1111 1111 1111 final ChunkSet m = new ChunkSet(4, 5); m.set(0, 4 * 5); // No chunks same for both state and pattern, so we do not violate the "not" pattern assert(!s.violatesNot(m, p)); } @Test public void testViolatesNotD() { // State chunkset: 0011 1111 0011 0000 0111 final ChunkSet s = new ChunkSet(4, 5); s.setChunk(0, 3); s.setChunk(1, 15); s.setChunk(2, 3); s.setChunk(3, 0); s.setChunk(4, 7); // Pattern chunkset: 1111 0111 0000 0111 0110 final ChunkSet p = new ChunkSet(4, 5); p.setChunk(0, 15); p.setChunk(1, 7); p.setChunk(2, 0); p.setChunk(3, 7); p.setChunk(4, 6); // Mask chunkset: 1111 1111 1111 1111 1111 final ChunkSet m = new ChunkSet(4, 5); m.set(0, 4 * 5); // No chunks same for both state and pattern, so we do not violate the "not" pattern assert(!s.violatesNot(m, p)); } @Test public void testViolatesNotE() { // State chunkset: 0011 1111 0011 0000 0111 final ChunkSet s = new ChunkSet(4, 5); s.setChunk(0, 3); s.setChunk(1, 15); s.setChunk(2, 3); s.setChunk(3, 0); s.setChunk(4, 7); // Pattern chunkset: 1111 0111 0000 0000 0110 final ChunkSet p = new ChunkSet(4, 5); p.setChunk(0, 15); p.setChunk(1, 7); p.setChunk(2, 0); p.setChunk(3, 0); p.setChunk(4, 6); // Mask chunkset: 1111 1111 1111 1111 1111 final ChunkSet m = new ChunkSet(4, 5); m.set(0, 4 * 5); // The fourth chunk is same for both state and pattern, so we violate the "not" pattern assert(s.violatesNot(m, p)); } @Test public void testGetNonzeroChunks() { // Pick a random power of 2 (up to and including 4, for max chunksize of 16) final int power = ThreadLocalRandom.current().nextInt(5); final int chunkSize = 1 << power; // Pick a random number of chunks between 1 and 100 (should be no need to test excessively big ones) final int numChunks = ThreadLocalRandom.current().nextInt(1, 101); final ChunkSet chunkset = new ChunkSet(chunkSize, numChunks); // Randomly pick a number of chunks to set to non-zero values final int numNonzeroChunks = ThreadLocalRandom.current().nextInt(numChunks + 1); // Randomly pick which chunks are nonzero final TIntArrayList nonzeroChunks = new TIntArrayList(numChunks); for (int i = 0; i < numChunks; ++i) { nonzeroChunks.add(i); } while (nonzeroChunks.size() > numNonzeroChunks) { nonzeroChunks.removeAt(ThreadLocalRandom.current().nextInt(nonzeroChunks.size())); } // Set random values to all selected nonzero chunks for (int i = 0; i < nonzeroChunks.size(); ++i) { chunkset.setChunk(nonzeroChunks.getQuick(i), ThreadLocalRandom.current().nextInt(1, (1 << chunkSize))); } final TIntArrayList nonzeroChunkIndices = chunkset.getNonzeroChunks(); assertEquals(nonzeroChunkIndices.size(), numNonzeroChunks); for (int i = 0; i < numNonzeroChunks; ++i) { assertEquals(nonzeroChunkIndices.getQuick(i), nonzeroChunks.getQuick(i)); } } }
5,099
24.888325
106
java
Ludii
Ludii-master/Player/test/other/TestDefaultGameLudPath.java
package other; import org.junit.Test; import game.Game; import main.Constants; /** * Unit test to ensure that our lud path for the default game * in Constants is set correctly, to something that actually loads * a game. * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestDefaultGameLudPath { /** * Unit test to ensure that our lud path for the default game * in Constants is set correctly, to something that actually loads * a game. */ @Test public void testDefaultGameLudPath() { final Game game = GameLoader.loadGameFromName(Constants.DEFAULT_GAME_PATH); assert(game != null); } }
643
19.125
77
java
Ludii
Ludii-master/Player/test/other/TestLudFilesOnlyASCII.java
package other; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Test; //----------------------------------------------------------------------------- /** * Unit Test to check that all our .lud files only contain ASCII characters * * @author Dennis Soemers */ public class TestLudFilesOnlyASCII { @Test @SuppressWarnings("static-method") public void test() throws IOException { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } // Test of compilation for each of them. for (final File fileEntry : entries) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); try (final BufferedReader br = new BufferedReader(new FileReader(fileName))) { int lineNumber = 1; while (true) { final String line = br.readLine(); if (line == null) break; for (int i = 0; i < line.length(); ++i) { final char c = line.charAt(i); if (c >= 128) { System.err.println("Non-ASCII character in line " + lineNumber + ": " + Character.toString(c) + " (" + (i + 1) + "th character)"); fail(); } } ++lineNumber; } } } } }
1,756
20.168675
137
java
Ludii
Ludii-master/Player/test/other/TestMath.java
package other; import static org.junit.Assert.assertEquals; import org.junit.Test; import main.collections.ListUtils; /** * Some tests for math functions * * @author Dennis Soemers */ public class TestMath { @SuppressWarnings("static-method") @Test public void testCombinations() { assertEquals(ListUtils.numCombinationsWithReplacement(5, 1), 5); assertEquals(ListUtils.numCombinationsWithReplacement(5, 2), 15); assertEquals(ListUtils.numCombinationsWithReplacement(5, 3), 35); assertEquals(ListUtils.numCombinationsWithReplacement(5, 4), 70); assertEquals(ListUtils.numCombinationsWithReplacement(5, 5), 126); assertEquals(ListUtils.numCombinationsWithReplacement(5, 8), 495); assertEquals(ListUtils.numCombinationsWithReplacement(49, 2), 1225); } }
782
24.258065
70
java
Ludii
Ludii-master/Player/test/other/TestZhangShasha.java
package other; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import utils.data_structures.support.zhang_shasha.Tree; /** * Tests for Zhang Shasha tree edit distance * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestZhangShasha { @Test public void testZhangShashaFromStrings() throws IOException { // Sample trees (in preorder). final String tree1Str1 = "f(d(a c(b)) e)"; final String tree1Str2 = "f(c(d(a b)) e)"; // Distance: 2 (main example used in the Zhang-Shasha paper) final String tree1Str3 = "a(b(c d) e(f g(i)))"; final String tree1Str4 = "a(b(c d) e(f g(h)))"; // Distance: 1 final String tree1Str5 = "d"; final String tree1Str6 = "g(h)"; // Distance: 2 final Tree tree1 = new Tree(tree1Str1); final Tree tree2 = new Tree(tree1Str2); final Tree tree3 = new Tree(tree1Str3); final Tree tree4 = new Tree(tree1Str4); final Tree tree5 = new Tree(tree1Str5); final Tree tree6 = new Tree(tree1Str6); final int distance1 = Tree.ZhangShasha(tree1, tree2); assertEquals(distance1, 2); final int distance2 = Tree.ZhangShasha(tree3, tree4); assertEquals(distance2, 1); final int distance3 = Tree.ZhangShasha(tree5, tree6); assertEquals(distance3, 2); } }
1,306
21.534483
62
java
Ludii
Ludii-master/Player/test/tensor/TestStateMoveTensors.java
package tensor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import game.Game; import compiler.Compiler; import main.FileHandling; import main.grammar.Description; import utils.LudiiGameWrapper; import utils.LudiiStateWrapper; /** * Unit test to ensure that for every game we can create a tensor for * the initial game state, and tensors for all legal moves in the initial * game state, without crashing. * * @author Dennis Soemers */ public class TestStateMoveTensors { @Test @SuppressWarnings("static-method") public void test() { final File startFolder = new File("../Common/res/lud/"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (path.equals("../Common/res/lud/plex")) continue; if (path.equals("../Common/res/lud/wip")) continue; if (path.equals("../Common/res/lud/wishlist")) continue; if (path.equals("../Common/res/lud/WishlistDLP")) continue; if (path.equals("../Common/res/lud/puzzle/deduction")) continue; // skip deduction puzzles for now if (path.equals("../Common/res/lud/bad")) continue; if (path.equals("../Common/res/lud/bad_playout")) continue; if (path.equals("../Common/res/lud/test")) continue; if (path.equals("../Common/res/lud/simulation")) continue; if (path.equals("../Common/res/lud/reconstruction")) continue; // We'll find files that we should be able to compile and run here gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String fileName = fileEntry.getPath(); System.out.println("File: " + fileName); // Load the string from file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(fileName); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); testTensors(game); } } } /** * Tries to instantiate tensors for given game, to test that that doesn't make us crash * @param game */ public static void testTensors(final Game game) { if (game.hasSubgames()) return; if (!game.isAlternatingMoveGame()) return; if (game.isStochasticGame()) return; if (game.hiddenInformation()) return; if (game.isGraphGame()) return; if (game.requiresBet()) return; if (game.isDeductionPuzzle()) return; // Create our wrappers final LudiiGameWrapper gameWrapper = new LudiiGameWrapper(game); final LudiiStateWrapper stateWrapper = new LudiiStateWrapper(gameWrapper); // Create tensors for initial game state and legal moves stateWrapper.toTensor(); stateWrapper.legalMovesTensors(); } }
3,590
22.019231
88
java
Ludii
Ludii-master/Player/test/tensor/TestYavalathTensors.java
package tensor; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import utils.LudiiGameWrapper; import utils.LudiiStateWrapper; /** * Unit test to test a bunch of things in Yavalath's tensors * * @author Dennis Soemers */ public class TestYavalathTensors { @SuppressWarnings("static-method") @Test public void test() { final LudiiGameWrapper game = LudiiGameWrapper.construct("Yavalath.lud"); final LudiiStateWrapper state = new LudiiStateWrapper(game); final int[] stateTensorsShape = game.stateTensorsShape(); final int[] moveTensorsShape = game.moveTensorsShape(); assertArrayEquals(stateTensorsShape, new int[]{10, 9, 17}); assertArrayEquals(moveTensorsShape, new int[]{3, 9, 17}); float[][][] stateTensor = state.toTensor(); // State tensor channels: // 0: Piece Type 1 (Ball1) // 1: Piece Type 2 (Ball2) // 2: Is Player 1 the current mover? // 3: Is Player 2 the current mover? // 4: Did Swap Occur? // 5: Does position exist in container 0 (Board)? // 6: Last move's from-position // 7: Last move's to-position // 8: Second-to-last move's from-position // 9: Second-to-last move's to-position // First two tensors must be all-zeros: no pieces on board yet assertAllZero(stateTensor[0]); assertAllZero(stateTensor[1]); // Third tensor must be all-ones: it's Player 1's turn assertAllOne(stateTensor[2]); // Fourth tensor must be all-zeros: it's not Player 2's turn assertAllZero(stateTensor[3]); // No swap occurred, so fifth tensor all 0s assertAllZero(stateTensor[4]); // Board has 61 cells, so must have 61 1s in sixth tensor assertEquals(countOnes(stateTensor[5]), 61); // First and last column have 5 cells, giving this pattern: 0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0 assertArrayEquals(stateTensor[5][0], new float[]{0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0}, 0.0001f); assertArrayEquals(stateTensor[5][8], new float[]{0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0}, 0.0001f); // Second and second-to-last column have 6 cells, giving this pattern: 0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0 assertArrayEquals(stateTensor[5][1], new float[]{0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0}, 0.0001f); assertArrayEquals(stateTensor[5][7], new float[]{0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0}, 0.0001f); // Third and third-to-last column have 7 cells, giving this pattern: 0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0 assertArrayEquals(stateTensor[5][2], new float[]{0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0}, 0.0001f); assertArrayEquals(stateTensor[5][6], new float[]{0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0}, 0.0001f); // Fourth and fourth-to-last column have 8 cells, giving this pattern: 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0 assertArrayEquals(stateTensor[5][3], new float[]{0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0}, 0.0001f); assertArrayEquals(stateTensor[5][5], new float[]{0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0}, 0.0001f); // Middle column has 9 cells, giving this pattern: 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 assertArrayEquals(stateTensor[5][4], new float[]{1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1}, 0.0001f); // All remaining channels should be all-zero, since no moves played assertAllZero(stateTensor[6]); assertAllZero(stateTensor[7]); assertAllZero(stateTensor[8]); assertAllZero(stateTensor[9]); // Should have 61 legal moves, game not over assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 61); // Player 1 will play move 30 (which also happens to be in Cell 30) state.applyNthMove(30); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 61); // Swap included! assertAllZero(state.toTensor()[2]); // Not Player 1's turn anymore assertAllOne(state.toTensor()[3]); // Player 2's turn now assertAllZero(state.toTensor()[4]); // No swap occurred // Player 2 plays move 60 (swap) state.applyNthMove(60); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 60); assertAllOne(state.toTensor()[2]); // Player 1's turn now assertAllZero(state.toTensor()[3]); // Not Player 2's turn anymore assertAllOne(state.toTensor()[4]); // Swap occurred // Black (previous Player 1, now Player 2) plays move 38 (= Cell 39) state.applyNthMove(38); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 59); assertAllZero(state.toTensor()[2]); // Not Player 1's turn anymore assertAllOne(state.toTensor()[3]); // Player 2's turn now assertAllOne(state.toTensor()[4]); // Swap occurred // White move 22 (= Cell 22) state.applyNthMove(22); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 58); assertAllOne(state.toTensor()[2]); // Player 1's turn now assertAllZero(state.toTensor()[3]); // Not Player 2's turn anymore assertAllOne(state.toTensor()[4]); // Swap occurred // Black move 29 (= Cell 31) state.applyNthMove(29); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 57); assertAllZero(state.toTensor()[2]); // Not Player 1's turn anymore assertAllOne(state.toTensor()[3]); // Player 2's turn now assertAllOne(state.toTensor()[4]); // Swap occurred // White move 9 (= Cell 9) state.applyNthMove(9); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 56); assertAllOne(state.toTensor()[2]); // Player 1's turn now assertAllZero(state.toTensor()[3]); // Not Player 2's turn anymore assertAllOne(state.toTensor()[4]); // Swap occurred // Black move 15 (= Cell 16) state.applyNthMove(15); assertFalse(state.isTerminal()); assertEquals(state.numLegalMoves(), 55); assertAllZero(state.toTensor()[2]); // Not Player 1's turn anymore assertAllOne(state.toTensor()[3]); // Player 2's turn now assertAllOne(state.toTensor()[4]); // Swap occurred // White move 14 (= Cell 15) state.applyNthMove(14); assertTrue(state.isTerminal()); // Get the new state tensor for this terminal state stateTensor = state.toTensor(); // In the final game state, there must be 4 pieces of type Ball1... assertEquals(countOnes(stateTensor[0]), 4); // ... in these four positions: assertEquals(stateTensor[0][7][11], 1.f, 0.0001f); assertEquals(stateTensor[0][6][10], 1.f, 0.0001f); assertEquals(stateTensor[0][5][9], 1.f, 0.0001f); assertEquals(stateTensor[0][4][8], 1.f, 0.0001f); // And 3 of type Ball2... assertEquals(countOnes(stateTensor[1]), 3); // ... in these three positions: assertEquals(stateTensor[1][6][12], 1.f, 0.0001f); assertEquals(stateTensor[1][4][10], 1.f, 0.0001f); assertEquals(stateTensor[1][3][9], 1.f, 0.0001f); // White won ("Player 1"), but that's the person who was originally Player 2 assertEquals(state.returns(0), -1.0, 0.0001); assertEquals(state.returns(1), 1.0, 0.0001); } /** * Asserts that given plane contains only 0s * @param plane */ private static void assertAllZero(final float[][] plane) { for (int x = 0; x < plane.length; ++x) { for (int y = 0; y < plane[x].length; ++y) { assertEquals(plane[x][y], 0.f, 0.f); } } } /** * Asserts that given plane contains only 1s * @param plane */ private static void assertAllOne(final float[][] plane) { for (int x = 0; x < plane.length; ++x) { for (int y = 0; y < plane[x].length; ++y) { assertEquals(plane[x][y], 1.f, 0.f); } } } /** * @param plane * @return Number of 1.f entries in given plane */ private static int countOnes(final float[][] plane) { int count = 0; for (int x = 0; x < plane.length; ++x) { for (int y = 0; y < plane[x].length; ++y) { if (plane[x][y] == 1.f) ++count; } } return count; } }
7,833
33.817778
106
java
Ludii
Ludii-master/Player/test/travis/TravisTest.java
package travis; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.Test; import ai.TestDefaultAIs; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import game.types.state.GameType; import games.TestCustomPlayouts; import games.TestTrialSerialization; import main.FileHandling; import main.StringRoutines; import main.collections.FastArrayList; import main.collections.ListUtils; import main.grammar.Description; import main.options.Option; import manager.utils.game_logs.MatchRecord; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import tensor.TestStateMoveTensors; import utils.AIUtils; /** * Unit Test for Travis uniting many other JUnit tests: * * - CompilationTest * - GameFileNameTest * - OnePlayoutPerGameTestWithOptions * - TestCustomPlayouts * - TestParallelPlayouts, * - TestStateMoveTensors * - TestTrialSerialization. * - TestTrialsIntegrity. * * @author Eric.Piette */ public class TravisTest { /** True if we want to run only some tests between the minimum day and the maximum hour of the day. */ private final static boolean USE_TIME = false; /** The minimum hour in the day to stop to run all the tests.*/ private final static int MIN_HOUR = 6; /** The maximum hour in the day to stop to run all the tests.*/ private final static int MAX_HOUR = 18; /** Number of parallel playouts we run. */ private static final int NUM_PARALLEL = 4; /** The current game compiled. */ private Game gameCompiled = null; /** The current path of the game compiled. */ private String pathGameCompiled = ""; //------------------------------------------------------------------------------- @Test public void runTests() { // Get the current hour in our time zone. final Date date = new Date(); final DateFormat df = new SimpleDateFormat("HH"); df.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); final int hour = Integer.parseInt(df.format(date)); // Load from memory final String[] choices = FileHandling.listGames(); for (final String filePath : choices) { final long startGameAt = System.nanoTime(); if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (filePath.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; // We exclude that game from the tests because the legal moves are // too slow to test. // if (!filePath.replaceAll(Pattern.quote("\\"), "/").contains("Tavli")) // continue; // Get game description from resource // System.out.println("Game: " + filePath); String path = filePath.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { e1.printStackTrace(); fail(); } // Parse and compile the game Game game = null; try { game = (Game)compiler.Compiler.compileTest(new Description(desc), false); pathGameCompiled = filePath; } catch (final Exception e) { System.err.println("** FAILED TO COMPILE: " + filePath + "."); e.printStackTrace(); fail(); } if (game != null) { System.out.println("Compiled " + game.name() + "."); this.gameCompiled = game; final int indexLastSlash = filePath.lastIndexOf('/'); final String fileName = filePath.substring(indexLastSlash + 1, filePath.length() - ".lud".length()); if (!fileName.equals(game.name())) { System.err.println("The fileName of " + fileName + ".lud is not equals to the name of the game which is " + game.name()); fail(); } } else { System.err.println("** FAILED TO COMPILE: " + filePath + "."); fail(); } // TO REMOVE WHEN MATCH WILL BE FIXED // if (game.hasSubgames()) // continue; if (game.hasMissingRequirement()) { System.err.println(game.name() + " has missing requirements."); fail(); } if (game.willCrash()) { System.err.println(game.name() + " is going to crash."); fail(); } try { testIntegrity(); } catch (final IOException e) { e.printStackTrace(); } final List<String> excludedCustomPlayouts = new ArrayList<String>(); excludedCustomPlayouts.add("Kriegsspiel"); excludedCustomPlayouts.add("Throngs "); excludedCustomPlayouts.add("Omny"); excludedCustomPlayouts.add("Lifeline"); excludedCustomPlayouts.add("Shisen-Sho"); excludedCustomPlayouts.add("Allemande"); excludedCustomPlayouts.add("Chains of Thought"); if (!containsPartOf(excludedCustomPlayouts, game.name())) testCustomPlayouts(); //------------------------------------------------------------------------- final List<String> excludedTensors = new ArrayList<String>(); excludedTensors.add("Kriegsspiel"); excludedTensors.add("Throngs"); excludedTensors.add("Omny"); excludedTensors.add("Lifeline"); excludedTensors.add("Shisen-Sho"); excludedTensors.add("Allemande"); excludedTensors.add("Chains of Thought"); if (!containsPartOf(excludedTensors, game.name())) testStateMoveTensors(); //------------------------------------------------------------------------- final List<String> excludedPlayoutPerOption = new ArrayList<String>(); excludedPlayoutPerOption.add("Kriegsspiel"); excludedPlayoutPerOption.add("Throngs"); excludedPlayoutPerOption.add("Mini Wars"); excludedPlayoutPerOption.add("Omny"); excludedPlayoutPerOption.add("Lifeline"); excludedPlayoutPerOption.add("Shisen-Sho"); excludedPlayoutPerOption.add("Allemande"); excludedPlayoutPerOption.add("Chains of Thought"); if (!containsPartOf(excludedPlayoutPerOption, game.name())) testPlayoutPerOption((USE_TIME) ? (hour < MIN_HOUR || hour > MAX_HOUR) : true); //------------------------------------------------------------------------- // testParallelPlayouts((USE_TIME) ? (hour < MIN_HOUR || hour > // MAX_HOUR) : true); final List<String> excludedParallelPlayouts = new ArrayList<String>(); excludedParallelPlayouts.add("Kriegsspiel"); excludedParallelPlayouts.add("Throngs"); excludedParallelPlayouts.add("Omny"); excludedParallelPlayouts.add("Lifeline"); excludedParallelPlayouts.add("Shisen-Sho"); excludedParallelPlayouts.add("Allemande"); excludedParallelPlayouts.add("Chains of Thought"); excludedParallelPlayouts.add("Nodal Chess"); if (!containsPartOf(excludedParallelPlayouts, game.name())) testParallelPlayouts(true); //------------------------------------------------------------------------- // testDefaultAIs((USE_TIME) ? (hour < MIN_HOUR || hour > // MAX_HOUR) // : true); final List<String> excludedDefaultAI = new ArrayList<String>(); if (!containsPartOf(excludedDefaultAI, game.name())) testDefaultAIs(true); //------------------------------------------------------------------------- /** * WARNING: the Trial Serialisation test must always be the LAST * test! It modifies the Game objects, which makes any tests that * run afterwards and re-use the same Game object invalid! */ final List<String> excludedSerialisation = new ArrayList<String>(); excludedSerialisation.add("Kriegsspiel"); excludedSerialisation.add("Throngs"); excludedSerialisation.add("Omny"); excludedSerialisation.add("Lifeline"); excludedSerialisation.add("Shisen-Sho"); excludedSerialisation.add("Allemande"); excludedSerialisation.add("Chains of Thought"); if (!containsPartOf(excludedSerialisation, game.name())) testTrialSerialisation(); final long stopGameAt = System.nanoTime(); final double Gamesecs = (stopGameAt - startGameAt) / 1000000000.0; System.out.println("All tests on this game done in " + Gamesecs + "s.\n"); } // Check if all the games using ADD_TO_EMPTY have been checked. // Make sure that we found all the games we expected to find if (!TestCustomPlayouts.ADD_TO_EMPTY_GAMES.isEmpty()) { System.err.println("Expected the following games to have AddToEmpty playouts:"); for (final String gameCustom : TestCustomPlayouts.ADD_TO_EMPTY_GAMES) { System.err.println(gameCustom); } fail(); } } //------------------------------------------------------------------------------------------- /** * The test of the tensors. */ public void testStateMoveTensors() { TestStateMoveTensors.testTensors(gameCompiled); } //------------------------------------------------------------------------------------------- /** * The test of the serialisation. */ public void testTrialSerialisation() { if (gameCompiled.isSimulationMoveGame()) return; TestTrialSerialization.testTrialSerialization(gameCompiled); // delete temp file if we succeeded unit test TestTrialSerialization.TEMP_TRIAL_FILE.delete(); } //------------------------------------------------------------------------------------------- /** * The test of the parallels playouts. */ public void testParallelPlayouts(final boolean toTest) { // To do that test only if we are on the right timeline. if (!toTest) return; if (gameCompiled.isDeductionPuzzle()) return; if (gameCompiled.isSimulationMoveGame()) return; // run parallel trials final Context[] contexts = new Context[NUM_PARALLEL]; final RandomProviderDefaultState[] gameStartRngStates = new RandomProviderDefaultState[NUM_PARALLEL]; for (int i = 0; i < NUM_PARALLEL; ++i) { contexts[i] = new Context(gameCompiled, new Trial(gameCompiled)); gameStartRngStates[i] = (RandomProviderDefaultState) contexts[i].rng().saveState(); } final ExecutorService executorService = Executors.newFixedThreadPool(NUM_PARALLEL); final List<Future<Context>> playedContexts = new ArrayList<Future<Context>>(NUM_PARALLEL); for (int i = 0; i < NUM_PARALLEL; ++i) { final Context context = contexts[i]; playedContexts.add(executorService.submit(() -> { gameCompiled.start(context); gameCompiled.playout(context, null, 1.0, null, 0, 30, ThreadLocalRandom.current()); return context; })); } // store outcomes of all parallel trials final Context[] endContexts = new Context[NUM_PARALLEL]; try { for (int i = 0; i < NUM_PARALLEL; ++i) { endContexts[i] = playedContexts.get(i).get(); } } catch (final InterruptedException | ExecutionException e) { System.err.println("Failing in game: " + gameCompiled.name()); e.printStackTrace(); fail(); } executorService.shutdown(); // check if we can still execute them all the same way in serial // mode for (int parallelPlayout = 0; parallelPlayout < NUM_PARALLEL; ++parallelPlayout) { final Context parallelContext = endContexts[parallelPlayout]; final Trial parallelTrial = parallelContext.trial(); final List<Move> loadedMoves = parallelTrial.generateCompleteMovesList(); final Trial trial = new Trial(gameCompiled); final Context context = new Context(gameCompiled, trial); context.rng().restoreState(gameStartRngStates[parallelPlayout]); gameCompiled.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { assert (loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. // in ByScore End condition) // so we just check if they're equal, without // applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context) .equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ("Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context)); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if(!loadedMoves.get(moveIdx).isDecision()) { System.err.println("A move is not a decision in the game: " + gameCompiled.name()); System.err.println("The move is " + loadedMoves.get(moveIdx)); fail(); } if (trial.over()) { System.err.println("Failing in game: " + gameCompiled.name()); System.err.println("Serial trial already over after moves:"); for (final Move move : trial.generateCompleteMovesList()) { System.err.println(move); } System.err.println("When run in parallel, trial only ended after moves:"); for (final Move move : parallelTrial.generateCompleteMovesList()) { System.err.println(move); } fail(); } final Moves legalMoves = gameCompiled.moves(context); final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); if (gameCompiled.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.err.println("Failing in game: " + gameCompiled.name()); System.err.println("No matching move found for: " + loadedMoveAllActions); for (final Move move : legalMoves.moves()) { System.err.println("legal move: " + move.getActionsWithConsequences(context)); } fail(); } // assert(matchingMove != null); assert ( matchingMove.fromNonDecision() == matchingMove.toNonDecision() || (context.currentInstanceContext().game().gameFlags() & GameType.UsesFromPositions) != 0L ); gameCompiled.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of // the possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = gameCompiled.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>( numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils .generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this // combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p] .get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.err.println("Failing in game: " + gameCompiled.name()); System.err.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } gameCompiled.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert (parallelTrial.status() == null); else assert (trial.status().winner() == parallelTrial.status().winner()); if (!Arrays.equals(context.trial().ranking(), parallelContext.trial().ranking())) { System.err.println("Failing in game: " + gameCompiled.name()); System.err.println( "Ranking when run in parallel: " + Arrays.toString(parallelContext.trial().ranking())); System.err.println("Ranking when run serially: " + Arrays.toString(context.trial().ranking())); fail(); } // we're done with this one, let's allow memory to be // cleared endContexts[parallelPlayout] = null; } } //------------------------------------------------------------------------------------------- /** * The test to run for the custom Playouts. */ public void testCustomPlayouts() { if (gameCompiled.hasSubgames()) return; if (gameCompiled.isDeductionPuzzle()) return; if (gameCompiled.isSimulationMoveGame()) return; if (!gameCompiled.hasCustomPlayouts()) return; // System.out.println(gameCompiled.name()); // Remember that we've hit this one TestCustomPlayouts.ADD_TO_EMPTY_GAMES.remove(gameCompiled.name()); TestCustomPlayouts.testCustomPlayout(gameCompiled); } //------------------------------------------------------------------------------------ /** * The test to run for the default AIs. */ public void testDefaultAIs(final boolean toTest) { // To do that test only if we are on the right timeline. if (!toTest) return; if (gameCompiled.isDeductionPuzzle()) return; if (gameCompiled.isSimulationMoveGame()) return; TestDefaultAIs.testDefaultAI(gameCompiled); } //------------------------------------------------------------------------------------ /** * To test each combination of options. */ public void testPlayoutPerOption(final boolean toTest) { // To do that test only if we are on the right timeline. if (!toTest) return; if (gameCompiled.isDeductionPuzzle()) return; if (gameCompiled.isSimulationMoveGame()) return; assert (gameCompiled != null); final List<List<String>> optionCategories = new ArrayList<List<String>>(); for (int o = 0; o < gameCompiled.description().gameOptions().numCategories(); o++) { final List<Option> options = gameCompiled.description().gameOptions().categories().get(o).options(); final List<String> optionCategory = new ArrayList<String>(); for (int j = 0; j < options.size(); j++) { final Option option = options.get(j); optionCategory.add(StringRoutines.join("/", option.menuHeadings().toArray(new String[0]))); } if (optionCategory.size() > 0) optionCategories.add(optionCategory); } List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories); // If no option (just the default game) we do not run the test. if (optionCombinations.size() <= 1) return; // System.out.println(game.name()); // We keep only the combinations of options with only one of these // option categories. optionCombinations = combinationsKept("Board Size/", optionCombinations); optionCombinations = combinationsKept("Rows/", optionCombinations); optionCombinations = combinationsKept("Columns/", optionCombinations); optionCombinations = combinationsKept("Safe Teleportations/", optionCombinations); optionCombinations = combinationsKept("Robots/", optionCombinations); optionCombinations = combinationsKept("Board/", optionCombinations); optionCombinations = combinationsKept("Dual/", optionCombinations); optionCombinations = combinationsKept("Players/", optionCombinations); optionCombinations = combinationsKept("Start Rules/", optionCombinations); optionCombinations = combinationsKept("Play Rules/", optionCombinations); optionCombinations = combinationsKept("End Rules/", optionCombinations); optionCombinations = combinationsKept("Version/", optionCombinations); optionCombinations = combinationsKept("Slide/", optionCombinations); optionCombinations = combinationsKept("Tiling/", optionCombinations); optionCombinations = combinationsKept("Track/", optionCombinations); optionCombinations = combinationsKept("Throw/", optionCombinations); optionCombinations = combinationsKept("Ruleset/", optionCombinations); optionCombinations = combinationsKept("Dice/", optionCombinations); optionCombinations = combinationsKept("Start Rules Tiger/", optionCombinations); optionCombinations = combinationsKept("Start Rules Goat/", optionCombinations); optionCombinations = combinationsKept("Capture/", optionCombinations); optionCombinations = combinationsKept("Is/", optionCombinations); optionCombinations = combinationsKept("Multi-", optionCombinations); optionCombinations = combinationsKept("Equi", optionCombinations); optionCombinations = combinationsKept("Discs", optionCombinations); optionCombinations = combinationsKept("Value", optionCombinations); optionCombinations = combinationsKept("Balance Rule", optionCombinations); optionCombinations = combinationsKept("Star Cells", optionCombinations); optionCombinations = combinationsKept("Board Shape", optionCombinations); for (final List<String> optionCombination : optionCombinations) { // System.out.println("Compiling and running playout with options: " // + optionCombination); try { final Game gameWithOptions = GameLoader.loadGameFromName(gameCompiled.name() + ".lud", optionCombination); if (gameWithOptions.hasMissingRequirement()) { System.err.println(gameWithOptions.name() + "with the option combination = " + optionCombination + " has missing requirements."); fail(); } if (gameWithOptions.willCrash()) { System.err.println(gameWithOptions.name() + "with the option combination = " + optionCombination + " is going to crash."); fail(); } final Trial trial = new Trial(gameWithOptions); final Context context = new Context(gameWithOptions, trial); gameWithOptions.start(context); gameWithOptions.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current()); } catch (final Exception e) { System.out.println("On the game " + gameCompiled.name()); System.out.println("The playout with these options: " + optionCombination + "failed."); e.printStackTrace(); fail(); } } } //------------------------------------------------------------------------------------ public void testIntegrity() throws FileNotFoundException, IOException { final SplitMix64 rng = new SplitMix64(); final File folder = new File("../Common/res" + pathGameCompiled); if (folder.getName().contains(".lud")) { if (gameCompiled.isDeductionPuzzle()) return; final String ludPath = folder.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); return; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); return; } if (gameCompiled.isSimulationMoveGame()) return; final File trialFile = trialFiles[rng.nextInt(trialFiles.length)]; final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, gameCompiled); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(gameCompiled); final Context context = new Context(gameCompiled, trial); context.rng().restoreState(loadedRecord.rngState()); gameCompiled.start(context); int moveIdx = 0; while (moveIdx < context.currentInstanceContext().trial().numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.moves().get(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); if (!loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Moves not equal."); System.out.println("init moveIdx: " + moveIdx); System.out.println("Move on the trial is = " + trial.getMove(moveIdx)); System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); System.out.println("All moves in trial = " + trial.generateCompleteMovesList()); fail("One of the init moves was different in stored trial!"); } ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in // ByScore End condition) // so we just check if they're equal, without applying // them again from loaded file if (!loadedMoves.get(moveIdx).getActionsWithConsequences(context) .equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Mismatch in actions."); System.out.println("Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context)); System.out.println("trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context)); fail("Mismatch in auto-applied actions."); } ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } final Moves legalMoves = gameCompiled.moves(context); // make sure that the number of legal moves is the same // as stored in file final int numInitPlacementMoves = context.currentInstanceContext().trial().numInitialPlacementMoves(); if (loadedTrial.auxilTrialData() != null) { if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - numInitPlacementMoves)) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - numInitPlacementMoves)); System.out.println("moveIdx = " + moveIdx); System.out.println("trial.numInitialPlacementMoves() = " + numInitPlacementMoves); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - numInitPlacementMoves)); System.out.println("legalMoves.moves() = " + legalMoves.moves()); fail("Incorrect number of legal moves"); } } final Move loadedMove = loadedMoves.get(moveIdx); final List<Action> loadedMoveAllActions = loadedMove.getActionsWithConsequences(context); if (gameCompiled.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.from() == loadedMove.from() && move.to() == loadedMove.to()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } } if (matchingMove == null) { if (loadedMove.isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMove; } if (matchingMove == null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + " from is " + loadedMoves.get(moveIdx).fromType() + " to is " + loadedMoves.get(moveIdx).toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } fail("Found no matching move"); } gameCompiled.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the // possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = gameCompiled.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>(numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils.generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this // combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p].get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println( "Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } gameCompiled.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) { if (loadedTrial.status() != null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Status doesn't match."); System.out.println("trial : " + trial.status()); System.out.println("loadedTrial: " + loadedTrial.status()); } assert (loadedTrial.status() == null); } else { if (trial.status().winner() != loadedTrial.status().winner()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Winners don't match."); System.out.println("trial : " + trial.status().winner()); System.out.println("loadedTrial: " + loadedTrial.status().winner()); } assert (trial.status().winner() == loadedTrial.status().winner()); } if (!Arrays.equals(trial.ranking(), loadedTrial.ranking())) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Rankings not equal."); System.out.println("trial : " + trial.ranking()); System.out.println("loadedTrial : " + loadedTrial.ranking()); } assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } //------------------------------------------------------------------------------------ /** * @param optionToCheck The option to check. * @param optionCombinations The original combinations of options. * * @return The list of combinations of option with only one option between * the specific option to check. */ public static List<List<String>> combinationsKept(final String optionToCheck, final List<List<String>> optionCombinations) { final SplitMix64 rng = new SplitMix64(); final List<List<String>> optionCombinationsKept = new ArrayList<List<String>>(); if (!optionCombinations.isEmpty()) { // We check if the option to check exist. final List<String> firstOptionCombination = optionCombinations.get(0); boolean optionExists = false; String optionToKeep = ""; for (final String option : firstOptionCombination) if (option.contains(optionToCheck)) { optionExists = true; break; } // We get a random option between the different possibilities of // that option. if (optionExists) { final int indexSizeSelected = rng.nextInt(optionCombinations.size()); final List<String> optionsSelected = optionCombinations.get(indexSizeSelected); for (final String option : optionsSelected) if (option.contains(optionToCheck)) { optionToKeep = option; // System.out.println("Only the combinations options // with " + option + " will be tested"); break; } } else // If that option is not found we return the original // combinations of options. return optionCombinations; // We keep only the option selected. if (optionExists) for (final List<String> optionCombination : optionCombinations) for (final String option : optionCombination) if (option.equals(optionToKeep)) { optionCombinationsKept.add(optionCombination); break; } } return optionCombinationsKept; } //------------------------------------------------------------------------------------ /** * @param list The list of string. * @param test The string to check. * @return True if the string to check is contains in any string in the * list. */ public static boolean containsPartOf(final List<String> list, final String test) { for (final String string : list) if (test.contains(string)) return true; return false; } }
37,900
31.814719
123
java
Ludii
Ludii-master/Player/test/travis/integrity/TestTrialsIntegrity.java
package travis.integrity; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.Test; import compiler.Compiler; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.FileHandling; import main.collections.FastArrayList; import main.collections.ListUtils; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIUtils; /** * A Unit Test to load Trials from the TravisTrials repository, and check if they * all still play out the same way in the current Ludii codebase. * * @author Dennis Soemers and cambolbro */ public class TestTrialsIntegrity { /** * The test to run * @throws FileNotFoundException * @throws IOException */ @Test @SuppressWarnings("static-method") public void test() throws FileNotFoundException, IOException { System.out.println( "\n=========================================\nIntegrity Test\n=========================================\n"); final long startAt = System.nanoTime(); final File startFolder = new File("../Common/res/lud"); final SplitMix64 rng = new SplitMix64(); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) { final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); if (fileEntryPath.equals("../Common/res/lud/plex")) continue; if (fileEntryPath.equals("../Common/res/lud/wip")) continue; if (fileEntryPath.equals("../Common/res/lud/wishlist")) continue; if (fileEntryPath.equals("../Common/res/lud/WishlistDLP")) continue; if (fileEntryPath.equals("../Common/res/lud/test")) continue; if (fileEntryPath.equals("../Common/res/lud/reconstruction")) continue; if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction")) continue; // skip puzzles for now if (fileEntryPath.equals("../Common/res/lud/bad")) continue; if (fileEntryPath.equals("../Common/res/lud/bad_playout")) continue; gameDirs.add(fileEntry); } else { entries.add(fileEntry); } } } int iterations = 0; for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game Game game = null; try { game = (Game)Compiler.compileTest(new Description(desc), false); } catch (final Exception e) { System.out.println("Fail(): Testing re-play of trial: " + ludPath); e.printStackTrace(); fail("COMPILATION FAILED for the file : " + ludPath); } if (game == null) { System.out.println("Fail(): Testing re-play of trial: " + ludPath); fail("COMPILATION FAILED for the file : " + ludPath); } if (game.isSimulationMoveGame()) continue; System.out.print("."); if (++iterations % 80 == 0) System.out.println(); final File trialFile = trialFiles[rng.nextInt(trialFiles.length)]; final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < context.currentInstanceContext().trial().numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.moves().get(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); if (!loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Moves not equal."); System.out.println("init moveIdx: " + moveIdx); System.out.println("Move on the trial is = " + trial.getMove(moveIdx)); System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); System.out.println("All moves in trial = " + trial.generateCompleteMovesList()); fail("One of the init moves was different in stored trial!"); } ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in // ByScore End condition) // so we just check if they're equal, without applying // them again from loaded file if (!loadedMoves.get(moveIdx).getActionsWithConsequences(context) .equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Mismatch in actions."); System.out.println( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context)); System.out.println("trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context)); fail("Mismatch in auto-applied actions."); } ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - context.currentInstanceContext().trial().numInitialPlacementMoves())); System.out.println("moveIdx = " + moveIdx); System.out.println("Trial was not supposed to be over, but it is!"); fail(); } final Moves legalMoves = game.moves(context); // make sure that the number of legal moves is the same // as stored in file final int numInitPlacementMoves = context.currentInstanceContext().trial() .numInitialPlacementMoves(); if (legalMoves.moves().size() != loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - numInitPlacementMoves)) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("corrected moveIdx = " + (moveIdx - numInitPlacementMoves)); System.out.println("moveIdx = " + moveIdx); System.out.println("trial.numInitialPlacementMoves() = " + numInitPlacementMoves); System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); System.out.println( "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " + loadedTrial.auxilTrialData().legalMovesHistorySizes() .getQuick(moveIdx - numInitPlacementMoves)); System.out.println("legalMoves.moves() = " + legalMoves.moves()); fail("Incorrect number of legal moves"); } final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + " from is " + loadedMoves.get(moveIdx).fromType() + " to is " + loadedMoves.get(moveIdx).toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } fail("Found no matching move"); } game.apply(context, matchingMove); } else { // simultaneous-move game // the full loaded move should be equal to one of the // possible large combined moves final FastArrayList<Move> legal = legalMoves.moves(); final int numPlayers = game.players().count(); @SuppressWarnings("unchecked") final FastArrayList<Move>[] legalPerPlayer = new FastArrayList[numPlayers + 1]; final List<List<Integer>> legalMoveIndicesPerPlayer = new ArrayList<List<Integer>>( numPlayers + 1); for (int p = 1; p <= numPlayers; ++p) { legalPerPlayer[p] = AIUtils.extractMovesForMover(legal, p); final List<Integer> legalMoveIndices = new ArrayList<Integer>(legalPerPlayer[p].size()); for (int i = 0; i < legalPerPlayer[p].size(); ++i) { legalMoveIndices.add(Integer.valueOf(i)); } legalMoveIndicesPerPlayer.add(legalMoveIndices); } final List<List<Integer>> combinedMoveIndices = ListUtils .generateTuples(legalMoveIndicesPerPlayer); boolean foundMatch = false; for (final List<Integer> submoveIndicesCombination : combinedMoveIndices) { // Combined all the per-player moves for this // combination of indices final List<Action> actions = new ArrayList<>(); final List<Moves> topLevelCons = new ArrayList<Moves>(); for (int p = 1; p <= numPlayers; ++p) { final Move move = legalPerPlayer[p] .get(submoveIndicesCombination.get(p - 1).intValue()); if (move != null) { final Move moveToAdd = new Move(move.actions()); actions.add(moveToAdd); if (move.then() != null) { for (int i = 0; i < move.then().size(); ++i) { if (move.then().get(i).applyAfterAllMoves()) topLevelCons.add(move.then().get(i)); else moveToAdd.then().add(move.then().get(i)); } } } } final Move combinedMove = new Move(actions); combinedMove.setMover(numPlayers + 1); combinedMove.then().addAll(topLevelCons); final List<Action> combinedMoveAllActions = combinedMove.getActionsWithConsequences(context); if (loadedMoveAllActions.equals(combinedMoveAllActions)) { foundMatch = true; break; } } if (!foundMatch) { System.out.println("Found no combination of submoves that generate loaded move: " + loadedMoveAllActions); fail(); } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) { if (loadedTrial.status() != null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Status doesn't match."); System.out.println("trial : " + trial.status()); System.out.println("loadedTrial: " + loadedTrial.status()); } assert (loadedTrial.status() == null); } else { if (trial.status().winner() != loadedTrial.status().winner()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Failed at trial file: " + trialFile); System.out.println("Winners don't match."); System.out.println("trial : " + trial.status().winner()); System.out.println("loadedTrial: " + loadedTrial.status().winner()); } assert (trial.status().winner() == loadedTrial.status().winner()); } if (!Arrays.equals(trial.ranking(), loadedTrial.ranking())) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Rankings not equal."); System.out.println("trial : " + trial.ranking()); System.out.println("loadedTrial : " + loadedTrial.ranking()); } assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); } }
14,517
32.146119
131
java
Ludii
Ludii-master/Player/test/travis/integrity/TestTrialsIntegrityPuzzle.java
package travis.integrity; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import compiler.Compiler; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.FileHandling; import main.grammar.Description; import manager.utils.game_logs.MatchRecord; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * For Puzzle: A Unit Test to load Trials from the TravisTrials repository, and * check if they all still play out the same way in the current Ludii codebase. * * @author Eric.Piette */ @SuppressWarnings("static-method") public class TestTrialsIntegrityPuzzle { /** * The test to run * * @throws FileNotFoundException * @throws IOException */ @Test public void test() throws FileNotFoundException, IOException { System.out.println( "\n=========================================\nIntegrity Deduction Puzzle Test\n=========================================\n"); final long startAt = System.nanoTime(); final File startFolder = new File("../Common/res/lud/puzzle/deduction"); final List<File> gameDirs = new ArrayList<File>(); gameDirs.add(startFolder); final List<File> entries = new ArrayList<File>(); for (int i = 0; i < gameDirs.size(); ++i) { final File gameDir = gameDirs.get(i); for (final File fileEntry : gameDir.listFiles()) { if (fileEntry.isDirectory()) gameDirs.add(fileEntry); else entries.add(fileEntry); } } for (final File fileEntry : entries) { if (fileEntry.getName().contains(".lud")) { final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/"); final String trialDirPath = ludPath .replaceFirst(Pattern.quote("/Common/res/"), Matcher.quoteReplacement("/../TravisTrials/")) .replaceFirst(Pattern.quote("/lud/"), Matcher.quoteReplacement("/random_trials/")) .replace(".lud", ""); final File trialsDir = new File(trialDirPath); if (!trialsDir.exists()) { System.err.println("WARNING: No directory of trials exists at: " + trialsDir.getAbsolutePath()); continue; } final File[] trialFiles = trialsDir.listFiles(); if (trialFiles.length == 0) { System.err.println("WARNING: No trial files exist in directory: " + trialsDir.getAbsolutePath()); continue; } // Load the string from lud file String desc = ""; try { desc = FileHandling.loadTextContentsFromFile(ludPath); } catch (final FileNotFoundException ex) { fail("Unable to open file '" + ludPath + "'"); } catch (final IOException ex) { fail("Error reading file '" + ludPath + "'"); } // Parse and compile the game final Game game = (Game)Compiler.compileTest(new Description(desc), false); if (game == null) fail("COMPILATION FAILED for the file : " + ludPath); if (game.hasSubgames()) continue; for (final File trialFile : trialFiles) { final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { // System.out.println("init moveIdx: " + moveIdx); // System.out.println("Move on the trial is = " + trial.moves().get(moveIdx)); // System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); if (!loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Moves not equal."); System.out.println("init moveIdx: " + moveIdx); System.out.println("Move on the trial is = " + trial.getMove(moveIdx)); System.out.println("loadedMoves.get(moveIdx) = " + loadedMoves.get(moveIdx)); fail("One of the init moves was different in stored trial!"); } assert (loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { // System.out.println("moveIdx after init: " + moveIdx); while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. // in ByScore End condition) // so we just check if they're equal, without // applying them again from loaded file if (!loadedMoves.get(moveIdx).getActionsWithConsequences(context) .equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Mismatch in actions."); System.out.println( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context)); System.out.println( "trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context)); fail("Mismatch in auto-applied actions."); } ++moveIdx; } if (moveIdx == loadedMoves.size()) break; if (trial.over()) fail("Trial over too early for " + ludPath); final Moves legalMoves = game.moves(context); // make sure that the number of legal moves is the same // as stored in file // if (legalMoves.moves().size() != loadedTrial.legalMovesHistorySizes() // .getQuick(moveIdx - trial.numInitPlace())) // { // System.out.println("moveIdx = " + (moveIdx - trial.numInitPlace())); // System.out.println("legalMoves.moves().size() = " + legalMoves.moves().size()); // System.out.println( // "loadedTrial.legalMovesHistorySizes().getQuick(moveIdx - trial.numInitPlace()) = " // + loadedTrial.legalMovesHistorySizes() // .getQuick(moveIdx - trial.numInitPlace())); // fail("Incorrect number of legal moves"); // } final List<Action> loadedMoveAllActions = loadedMoves.get(moveIdx).getActionsWithConsequences(context); if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (final Move move : legalMoves.moves()) { if (move.getActionsWithConsequences(context).equals(loadedMoveAllActions)) { matchingMove = move; break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("moveIdx = " + (moveIdx - trial.numInitialPlacementMoves())); System.out.println("Loaded move = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + " from is " + loadedMoves.get(moveIdx).fromType() + " to is " + loadedMoves.get(moveIdx).toType()); for (final Move move : legalMoves.moves()) { System.out.println("legal move = " + move.getActionsWithConsequences(context) + " move from is " + move.fromType() + " to " + move.toType()); } fail("Found no matching move"); } game.apply(context, matchingMove); } ++moveIdx; } if (trial.status() == null) { if (loadedTrial.status() != null) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Status doesn't match."); System.out.println("trial : " + trial.status()); System.out.println("loadedTrial: " + loadedTrial.status()); } assert (loadedTrial.status() == null); } else { if (trial.status().winner() != loadedTrial.status().winner()) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Winners don't match."); System.out.println("trial : " + trial.status().winner()); System.out.println("loadedTrial: " + loadedTrial.status().winner()); } assert (trial.status().winner() == loadedTrial.status().winner()); } if (!Arrays.equals(trial.ranking(), loadedTrial.ranking())) { System.out.println("Fail(): Testing re-play of trial: " + trialFile.getParent()); System.out.println("Rankings not equal."); System.out.println("trial : " + trial.ranking()); System.out.println("loadedTrial : " + loadedTrial.ranking()); } assert (Arrays.equals(trial.ranking(), loadedTrial.ranking())); } } } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); } }
9,328
31.505226
129
java
Ludii
Ludii-master/Player/test/travis/quickTests/AllDifferentIdConceptEnum.java
package travis.quickTests; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import gnu.trove.list.array.TIntArrayList; import other.concept.Concept; import other.concept.ConceptComputationType; import other.concept.ConceptDataType; import other.concept.ConceptKeyword; import other.concept.ConceptPurpose; import other.concept.ConceptType; /** * Check if all the ids are different for all the enum class related to the * concepts (for the db). * * @author Eric.Piette * */ @SuppressWarnings("static-method") public class AllDifferentIdConceptEnum { @Test public void Concept() { final TIntArrayList ids = new TIntArrayList(); for (final Concept concept : Concept.values()) { if (ids.contains(concept.id())) { System.err.println("The id " + concept.id() + " is used twice for the Concept enum class."); fail(); } else ids.add(concept.id()); } } @Test public void ConceptTaxo() { final List<String> taxos = new ArrayList<String>(); for (final Concept concept : Concept.values()) { if (taxos.contains(concept.taxonomy())) { System.err.println("The taxo " + concept.taxonomy() + " is used twice for the Concept enum class."); fail(); } else taxos.add(concept.taxonomy()); } } @Test public void ConceptDataType() { final TIntArrayList ids = new TIntArrayList(); for (final ConceptDataType conceptDataType : ConceptDataType.values()) { if (ids.contains(conceptDataType.id())) { System.err.println( "The id " + conceptDataType.id() + " is used twice for the ConceptDataType enum class."); fail(); } else ids.add(conceptDataType.id()); } } @Test public void ConceptKeyword() { final TIntArrayList ids = new TIntArrayList(); for (final ConceptKeyword conceptKeyword : ConceptKeyword.values()) { if (ids.contains(conceptKeyword.id())) { System.err .println("The id " + conceptKeyword.id() + " is used twice for the ConceptKeyword enum class."); fail(); } else ids.add(conceptKeyword.id()); } } @Test public void ConceptPurpose() { final TIntArrayList ids = new TIntArrayList(); for (final ConceptPurpose conceptPurpose : ConceptPurpose.values()) { if (ids.contains(conceptPurpose.id())) { System.err .println("The id " + conceptPurpose.id() + " is used twice for the ConceptPurpose enum class."); fail(); } else ids.add(conceptPurpose.id()); } } @Test public void ConceptType() { final TIntArrayList ids = new TIntArrayList(); for (final ConceptType conceptType : ConceptType.values()) { if (ids.contains(conceptType.id())) { System.err.println("The id " + conceptType.id() + " is used twice for the ConceptType enum class."); fail(); } else ids.add(conceptType.id()); } } @Test public void ConceptComputationType() { final TIntArrayList ids = new TIntArrayList(); for (final ConceptComputationType conceptComputationType : ConceptComputationType.values()) { if (ids.contains(conceptComputationType.id())) { System.err.println("The id " + conceptComputationType.id() + " is used twice for the ConceptComputationType enum class."); fail(); } else ids.add(conceptComputationType.id()); } } }
3,333
21.993103
126
java
Ludii
Ludii-master/Player/test/travis/quickTests/FVectorTests.java
package travis.quickTests; import static org.junit.Assert.assertEquals; import org.junit.Test; import main.collections.FVector; /** * Unit tests for FVector * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class FVectorTests { private static final float FLOAT_TOLERANCE = 0.0001f; @Test public void testLinspaceInclusive() { final FVector linspace = FVector.linspace(0.f, 1.f, 4, true); assertEquals(linspace.dim(), 4); assertEquals(linspace.get(0), 0.f / 3.f, FLOAT_TOLERANCE); assertEquals(linspace.get(1), 1.f / 3.f, FLOAT_TOLERANCE); assertEquals(linspace.get(2), 2.f / 3.f, FLOAT_TOLERANCE); assertEquals(linspace.get(3), 3.f / 3.f, FLOAT_TOLERANCE); } @Test public void testLinspaceExclusive() { final FVector linspace = FVector.linspace(0.f, 1.f, 4, false); assertEquals(linspace.dim(), 4); assertEquals(linspace.get(0), 0.f / 4.f, FLOAT_TOLERANCE); assertEquals(linspace.get(1), 1.f / 4.f, FLOAT_TOLERANCE); assertEquals(linspace.get(2), 2.f / 4.f, FLOAT_TOLERANCE); assertEquals(linspace.get(3), 3.f / 4.f, FLOAT_TOLERANCE); } }
1,111
24.860465
64
java
Ludii
Ludii-master/Player/test/travis/quickTests/HashTests.java
package travis.quickTests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import game.Game; import game.types.board.SiteType; import main.Constants; import other.GameLoader; import other.action.move.move.ActionMove; import other.action.state.ActionSetNextPlayer; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Unit Test to test efficiency for all the games on the lud folder * * @author mrraow */ @SuppressWarnings("static-method") public class HashTests { /** * Tests that score hashes are working correctly, including modulus */ @Test public void testScoreHashes() { final Game game = GameLoader.loadGameFromName("Chaturaji.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().fullHash(); context.setScore(1, 100); final long hash100 = context.state().fullHash(); Assert.assertNotEquals("Score has changed but hash has not.", startHash, hash100); context.setScore(1, 100 + Constants.MAX_SCORE); final long hash1100 = context.state().fullHash(); Assert.assertNotEquals("Score has changed but hash has not.", startHash, hash1100); Assert.assertNotEquals("Hash(core) should not be Hash(score+MaxScore).", hash100, hash1100); context.setScore(1, 100); final long hash100b = context.state().fullHash(); Assert.assertEquals("Same score should give same hash", hash100, hash100b); } /** * Tests that temp hashes are working correctly */ @Test public void testTempHashes() { final Game game = GameLoader.loadGameFromName("Chaturaji.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); final int temp = context.state().temp(); context.state().setTemp(temp+1); final long newHash = context.state().stateHash(); Assert.assertNotEquals("Temp has changed but hash has not.", startHash, newHash); context.state().setTemp(temp); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same temp value should give same hash", startHash, restoredHash); } /** * Tests that [players swapped] hash is working correctly */ @Test public void testPlayersSwappedHashes() { final Game game = GameLoader.loadGameFromName("Chaturaji.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); context.state().swapPlayerOrder(1, 2); final long newHash = context.state().stateHash(); Assert.assertNotEquals("Players swapped state has changed but hash has not.", startHash, newHash); context.state().swapPlayerOrder(1, 2); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same swap value should give same hash", startHash, restoredHash); assert(true); } /** * Tests that [consecutive turns] hash and [player turn switch] hash are working correctly */ @Ignore @Test public void testTurnHashes() { final Game game = GameLoader.loadGameFromName("Chaturaji.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().fullHash(); context.state().incrementNumTurnSamePlayer(); final long newHash = context.state().fullHash(); Assert.assertNotEquals("Consecutive turns has changed but hash has not.", startHash, newHash); context.state().reinitNumTurnSamePlayer(); final long restoredHash = context.state().fullHash(); Assert.assertNotEquals("Same consecutive turns should not give same hash (turn has switched)", startHash, restoredHash); } /** * Tests that [player team] hash is working correctly */ @Ignore @Test public void teamHashes() { final Game game = GameLoader.loadGameFromName("Pachisi.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); final int playerTeam = context.state().getTeam(1); context.state().setPlayerToTeam(1, playerTeam+1); final long newHash = context.state().stateHash(); Assert.assertNotEquals("Player team changed but hash has not.", startHash, newHash); context.state().setPlayerToTeam(1, playerTeam); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same team value should give same hash", startHash, restoredHash); } /** * Tests that [player phase] hash is working correctly */ @Ignore @Test public void testPhaseHashes() { final Game game = GameLoader.loadGameFromName("Lasca.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); final int startPhase = context.state().currentPhase(1); context.state().setPhase(1, startPhase+1); final long newHash = context.state().stateHash(); Assert.assertNotEquals("Player phase has changed but hash has not.", startHash, newHash); context.state().setPhase(1, startPhase); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same phase value should give same hash", startHash, restoredHash); } /** * Tests that [player amount] hash is working correctly */ @Ignore @Test public void testAmountHashes() { final Game game = GameLoader.loadGameFromName("testBet.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().fullHash(); final int startAmount = context.state().amount(1); context.state().setAmount(1, startAmount + 1); final long newHash = context.state().fullHash(); Assert.assertNotEquals("Player amount has changed but hash has not.", startHash, newHash); context.state().setAmount(1, startAmount); final long restoredHash = context.state().fullHash(); Assert.assertEquals("Same amount should give same hash", startHash, restoredHash); } /** * Tests that [visited] hash is working correctly */ @Ignore @Test public void visitedHashes() { final Game game = GameLoader.loadGameFromName("Castello.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); context.state().visit(1); final long newHash = context.state().stateHash(); Assert.assertNotEquals("Visits changed but hash has not.", startHash, newHash); context.state().reInitVisited(); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same visits should give same hash", startHash, restoredHash); } /** * Tests that [to remove] hash is working correctly */ @Ignore @Test public void toRemoveHashes() { final Game game = GameLoader.loadGameFromName("Fanorona.lud"); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final long startHash = context.state().stateHash(); // context.state().addPieceToRemove(1); // final long newHash = context.state().stateHash(); // Assert.assertNotEquals("Remove sites changed but hash has not.", startHash, newHash); context.state().reInitCapturedPiece(); final long restoredHash = context.state().stateHash(); Assert.assertEquals("Same removed sites value should give same hash", startHash, restoredHash); } /** * Plays same 4 chess moves in different order, verifies position is the same */ @Test public void testSameChess() { Game game = GameLoader.loadGameFromName("/Chess.lud"); Trial trial = new Trial(game); Context context = new Context(game, trial); game.start(context); step(context, game, 2, 12, 28); step(context, game, 1, 52, 36); step(context, game, 2, 11, 27); step(context, game, 1, 51, 35); final long stateHash = context.state().stateHash(); game = GameLoader.loadGameFromName("/Chess.lud"); trial = new Trial(game); context = new Context(game, trial); game.start(context); step(context, game, 2, 11, 27); step(context, game, 1, 51, 35); step(context, game, 2, 12, 28); step(context, game, 1, 52, 36); final long stateHash2 = context.state().stateHash(); assertEquals(stateHash, stateHash2); } /** * Plays different 2 chess moves, verifies position is different * Note that these are the same two moves used in testSame, so we break the symmetry then restore it */ @Test public void testDifferentChess() { Game game = GameLoader.loadGameFromName("/Chess.lud"); Trial trial = new Trial(game); Context context = new Context(game, trial); game.start(context); step(context, game, 2, 12, 28); step(context, game, 1, 52, 36); final long stateHash = context.state().stateHash(); game = GameLoader.loadGameFromName("/Chess.lud"); trial = new Trial(game); context = new Context(game, trial); game.start(context); step(context, game, 2, 11, 27); step(context, game, 1, 51, 35); final long stateHash2 = context.state().stateHash(); assertFalse(stateHash==stateHash2); } private static void step(final Context context, final Game game, final int nextPlayer, final int from, final int to) { game.apply(context, new Move(ActionMove.construct(SiteType.Cell, from, Constants.UNDEFINED, SiteType.Cell, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false).withDecision(true), new ActionSetNextPlayer(nextPlayer)).withFrom(from).withTo(to)); } }
9,787
30.371795
187
java
Ludii
Ludii-master/Player/test/travis/quickTests/TestDemos.java
package travis.quickTests; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import org.junit.Test; import game.Game; import game.rules.play.moves.Moves; import game.types.play.ModeType; import main.FileHandling; import manager.utils.game_logs.MatchRecord; import other.AI; import other.GameLoader; import other.action.Action; import other.context.Context; import other.move.Move; import other.trial.Trial; import utils.AIFactory; /** * Tests that all the games, AIs and trials specified in demos are still valid. * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestDemos { @Test public void testDemos() { final String[] allDemos = FileHandling.getResourceListing(TestDemos.class, "demos/", ".json"); for (String demo : allDemos) { if (!demo.endsWith(".json")) continue; demo = demo.replaceAll(Pattern.quote("\\"), "/"); if (demo.contains("/demos/")) demo = demo.substring(demo.indexOf("/demos/")); if (!demo.startsWith("/")) demo = "/" + demo; if (!demo.startsWith("/demos")) demo = "/demos" + demo; System.out.println("Testing demo: " + demo + "..."); try (final InputStream inputStream = TestDemos.class.getResourceAsStream(demo)) { final JSONObject json = new JSONObject(new JSONTokener(inputStream)); final JSONObject jsonDemo = json.getJSONObject("Demo"); final String gameName = jsonDemo.getString("Game"); final List<String> gameOptions = new ArrayList<>(); final JSONArray optionsArray = jsonDemo.optJSONArray("Options"); if (optionsArray != null) for (final Object object : optionsArray) gameOptions.add((String) object); // Make sure we can load the game final Game game = GameLoader.loadGameFromName(gameName, gameOptions); assert(game != null); for (int p = 1; p <= game.players().count(); ++p) { final JSONObject jsonPlayer = jsonDemo.optJSONObject("Player " + p); if (jsonPlayer != null) { if (jsonPlayer.has("AI")) { // Make sure we can load the AI and that it supports this game final AI ai = AIFactory.fromJson(jsonPlayer); assert (ai != null); assert (ai.supportsGame(game)); } } } if (jsonDemo.has("Trial")) { // Make sure that we can load and execute this trial final String trialFile = jsonDemo.getString("Trial").replaceAll(Pattern.quote("\\"), "/"); try ( final InputStreamReader reader = new InputStreamReader(TestDemos.class.getResourceAsStream(trialFile)); ) { final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromInputStream ( reader, game ); final Trial loadedTrial = loadedRecord.trial(); final List<Move> loadedMoves = loadedTrial.generateCompleteMovesList(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); context.rng().restoreState(loadedRecord.rngState()); game.start(context); int moveIdx = 0; while (moveIdx < trial.numInitialPlacementMoves()) { assert(loadedMoves.get(moveIdx).equals(trial.getMove(moveIdx))); ++moveIdx; } while (moveIdx < loadedMoves.size()) { while (moveIdx < trial.numMoves()) { // looks like some actions were auto-applied (e.g. in ByScore End condition) // so we just check if they're equal, without applying them again from loaded file assert (loadedMoves.get(moveIdx).getActionsWithConsequences(context).equals(trial.getMove(moveIdx).getActionsWithConsequences(context))) : ( "Loaded Move Actions = " + loadedMoves.get(moveIdx).getActionsWithConsequences(context) + ", trial actions = " + trial.getMove(moveIdx).getActionsWithConsequences(context) ); ++moveIdx; } if (moveIdx == loadedMoves.size()) break; assert(!trial.over()); final Moves legalMoves = game.moves(context); final List<List<Action>> legalMovesAllActions = new ArrayList<List<Action>>(); for (final Move legalMove : legalMoves.moves()) { legalMovesAllActions.add(legalMove.getActionsWithConsequences(context)); } if (game.mode().mode() == ModeType.Alternating) { Move matchingMove = null; for (int i = 0; i < legalMovesAllActions.size(); ++i) { if (legalMovesAllActions.get(i).equals(loadedMoves.get(moveIdx).getActionsWithConsequences(context))) { matchingMove = legalMoves.moves().get(i); break; } } if (matchingMove == null) { if (loadedMoves.get(moveIdx).isPass() && legalMoves.moves().isEmpty()) matchingMove = loadedMoves.get(moveIdx); } if (matchingMove == null) { for (int i = 0; i < legalMovesAllActions.size(); ++i) { System.out.println(legalMovesAllActions.get(i) + " does not match " + loadedMoves.get(moveIdx).getActionsWithConsequences(context)); } fail(); } game.apply(context, matchingMove); } else { // simultaneous-move game // we expect each of the actions of the loaded move to be contained // in at least one of the legal moves for (final Action subAction : loadedMoves.get(moveIdx).actions()) { boolean foundMatch = false; for (int i = 0; i < legalMovesAllActions.size(); ++i) if (legalMovesAllActions.get(i).contains(subAction)) { foundMatch = true; break; } if (!foundMatch) { System.out.println("Found no matching subAction!"); System.out.println("subAction = " + subAction); for (int i = 0; i < legalMovesAllActions.size(); ++i) System.out.println("Legal move = " + legalMovesAllActions.get(i)); fail(); } } game.apply(context, loadedMoves.get(moveIdx)); } ++moveIdx; } if (trial.status() == null) assert(loadedTrial.status() == null); else assert(trial.status().winner() == loadedTrial.status().winner()); assert(Arrays.equals(trial.ranking(), loadedTrial.ranking())); } catch (final IOException e) { e.printStackTrace(); } } } catch (final IOException e) { e.printStackTrace(); fail(); } } } }
6,978
28.323529
142
java
Ludii
Ludii-master/Player/test/travis/quickTests/TestJNIClasses.java
package travis.quickTests; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; /** * Unit test to make sure that the fully qualified names of classes that we * access by those exact names through JNI (for example in Polygames) don't * change. * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestJNIClasses { @Test public void testFullyQualifiedNames() { try { assertNotNull(Class.forName("utils.LudiiGameWrapper")); assertNotNull(Class.forName("utils.LudiiStateWrapper")); } catch (final ClassNotFoundException e) { fail(); } } }
651
18.176471
75
java
Ludii
Ludii-master/Player/test/travis/quickTests/TestPregenGraphFunction.java
package travis.quickTests; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import game.equipment.container.board.Board; import game.functions.dim.DimConstant; import game.functions.floats.FloatConstant; import game.functions.graph.GraphFunction; import game.functions.graph.generators.basis.hex.HexagonOnHex; import game.functions.graph.generators.basis.hex.StarOnHex; import game.functions.graph.generators.basis.square.RectangleOnSquare; import game.functions.graph.generators.basis.tiling.Tiling; import game.functions.graph.generators.basis.tiling.TilingType; import game.functions.graph.generators.basis.tri.TriangleOnTri; import game.functions.graph.operators.Merge; import game.functions.graph.operators.Shift; import game.functions.graph.operators.Union; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.graph.GraphElement; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import other.topology.TopologyElement; /** * Test checking the pregeneration with the graph functions. * * @author Eric.Piette and cambolbro */ public class TestPregenGraphFunction { /** The board to test. */ private Board board; /** To know if the test is ok */ private boolean testSucceed = true; // Expected Cells. private int[] cellsCorners; private int[] cellsOuter; private int[] cellsPerimeter; private int[] cellsInner; private int[] cellsCentre; private int[] cellsTop; private int[] cellsBottom; private int[] cellsLeft; private int[] cellsRight; // Expected Vertices. private int[] verticesCorners; private int[] verticesOuter; private int[] verticesPerimeter; private int[] verticesInner; private int[] verticesCentre; private int[] verticesTop; private int[] verticesBottom; private int[] verticesLeft; private int[] verticesRight; // Expected Edges. private int[] edgesCorners; private int[] edgesOuter; private int[] edgesPerimeter; private int[] edgesInner; private int[] edgesCentre; private int[] edgesTop; private int[] edgesBottom; private int[] edgesLeft; private int[] edgesRight; // --------------------------------------------------------------------- @Test public void testSquareTilingSquare() { makeTheBoard(new RectangleOnSquare(new DimConstant(3), null, null, null), SiteType.Cell); final String nameTest = "Square tiling by Square"; // Cells cellsCorners = new int[] { 0, 2, 6, 8 }; cellsOuter = new int[] { 0, 1, 2, 3, 5, 6, 7, 8 }; cellsPerimeter = new int[] { 0, 1, 2, 3, 5, 6, 7, 8 }; cellsInner = new int[] { 4 }; cellsCentre = new int[] { 4 }; cellsTop = new int[] { 6, 7, 8 }; cellsBottom = new int[] { 0, 1, 2 }; cellsLeft = new int[] { 0, 3, 6 }; cellsRight = new int[] { 2, 5, 8 }; // Vertices verticesCorners = new int[] { 0, 3, 12, 15 }; verticesOuter = new int[] { 0, 1, 2, 3, 4, 7, 8, 11, 12, 13, 14, 15 }; verticesPerimeter = new int[] { 0, 1, 2, 3, 4, 7, 8, 11, 12, 13, 14, 15 }; verticesInner = new int[] { 5, 6, 9, 10 }; verticesCentre = new int[] { 5, 6, 9, 10 }; verticesTop = new int[] { 12, 13, 14, 15 }; verticesBottom = new int[] { 0, 1, 2, 3 }; verticesLeft = new int[] { 0, 4, 8, 12 }; verticesRight = new int[] { 3, 7, 11, 15 }; // Edges edgesCorners = new int[] {0, 2, 3, 6, 17, 20, 21, 23}; edgesOuter = new int[] {0, 1, 2, 3, 6, 10, 13, 17, 20, 21, 22, 23}; edgesPerimeter = new int[] {0, 1, 2, 3, 6, 10, 13, 17, 20, 21, 22, 23}; edgesInner = new int[] {4, 5, 7, 8, 9, 11, 12, 14, 15, 16, 18, 19}; edgesCentre = new int[] {8, 11, 12, 15}; edgesTop = new int[] { 21, 22, 23 }; edgesBottom = new int[] {0, 1, 2}; edgesLeft = new int[] {3, 10, 17}; edgesRight = new int[] { 6, 13, 20 }; runAllTests(nameTest); // For the square Tiling we also test some radials. final int[][] allRadials = new int[8][2]; allRadials[0] = new int[] {4, 7}; allRadials[1] = new int[] {4, 8}; allRadials[2] = new int[] {4, 5}; allRadials[3] = new int[] {4, 2}; allRadials[4] = new int[] {4, 1}; allRadials[5] = new int[] {4, 0}; allRadials[6] = new int[] {4, 3}; allRadials[7] = new int[] {4, 6}; final int[][] orthogonalRadials = new int[4][2]; orthogonalRadials[0] = new int[] {4, 7}; orthogonalRadials[1] = new int[] {4, 5}; orthogonalRadials[2] = new int[] {4, 1}; orthogonalRadials[3] = new int[] {4, 3}; final int[][] diagonalRadials = new int[4][2]; diagonalRadials[0] = new int[] {4, 8}; diagonalRadials[1] = new int[] {4, 2}; diagonalRadials[2] = new int[] {4, 0}; diagonalRadials[3] = new int[] {4, 6}; final int[][] northRadials = new int[1][3]; northRadials[0] = new int[] {1,4,7}; testRadials(AbsoluteDirection.All, SiteType.Cell, 4, allRadials); testRadials(AbsoluteDirection.Orthogonal, SiteType.Cell, 4, orthogonalRadials); testRadials(AbsoluteDirection.Diagonal, SiteType.Cell, 4, diagonalRadials); testRadials(AbsoluteDirection.N, SiteType.Cell, 1, northRadials); if(!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- @Test public void testHexTilingHex() { makeTheBoard(new HexagonOnHex(new DimConstant(5)), SiteType.Cell); final String nameTest = "Hex tiling by Hex"; // Cells cellsCorners = new int[] {0, 4, 26, 34, 56, 60}; cellsOuter = new int[] {0, 1, 2, 3, 4, 5, 10, 11, 17, 18, 25, 26, 34, 35, 42, 43, 49, 50, 55, 56, 57, 58, 59, 60}; cellsPerimeter = new int[] {0, 1, 2, 3, 4, 5, 10, 11, 17, 18, 25, 26, 34, 35, 42, 43, 49, 50, 55, 56, 57, 58, 59, 60}; cellsInner = new int[] {6, 7, 8, 9, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 44, 45, 46, 47, 48, 51, 52, 53, 54}; cellsCentre = new int[] { 30 }; cellsTop = new int[] { 56,57,58,59,60 }; cellsBottom = new int[] {0, 1, 2, 3, 4}; cellsLeft = new int[] { 26 }; cellsRight = new int[] { 34 }; // Vertices // verticesCorners = new int[] { }; // NOT SURE ??? verticesOuter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 23, 24, 30, 31, 38, 39, 46, 47, 55, 56, 64, 65, 74, 75, 84, 85, 93, 94, 102, 103, 110, 111, 118, 119, 125, 126, 132, 133, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149}; verticesPerimeter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 23, 24, 30, 31, 38, 39, 46, 47, 55, 56, 64, 65, 74, 75, 84, 85, 93, 94, 102, 103, 110, 111, 118, 119, 125, 126, 132, 133, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149}; final TIntArrayList outer = new TIntArrayList(verticesOuter); final TIntArrayList inner = new TIntArrayList(); for (int i = 0; i < 149; i++) if (!outer.contains(i)) inner.add(i); verticesInner = inner.toArray(); verticesCentre = new int[] {60, 69, 70, 79, 80, 89}; verticesTop = new int[] {145, 146, 147, 148, 149}; verticesBottom = new int[] {0, 1, 2, 3, 4}; verticesLeft = new int[] {65, 75}; verticesRight = new int[] {74, 84}; // TODO the edges. runAllTests(nameTest); if(!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- @Test public void testTriangleTilingTriangle() { makeTheBoard(new TriangleOnTri(new DimConstant(4)), SiteType.Cell); final String nameTest = "Triangle tiling by Triangle"; // Cells cellsCorners = new int[] { 0, 3, 15 }; cellsOuter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15}; cellsPerimeter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15}; cellsInner = new int[] { 8 }; cellsCentre = new int[] { 8 }; cellsTop = new int[] { 15 }; cellsBottom = new int[] { 0, 1, 2, 3 }; cellsLeft = new int[] { 0 }; cellsRight = new int[] { 3 }; // Vertices verticesCorners = new int[] { 0, 4, 14 }; verticesOuter = new int[] { 0,1,2,3,4,5,8,9,11,12,13,14 }; verticesPerimeter = new int[] { 0,1,2,3,4,5,8,9,11,12,13,14 }; verticesInner = new int[] { 6, 7, 10 }; verticesCentre = new int[] { 6, 7, 10 }; verticesTop = new int[] { 14 }; verticesBottom = new int[] { 0,1,2,3,4 }; verticesLeft = new int[] { 0 }; verticesRight = new int[] { 4 }; // Edges edgesCorners = new int[] { 0, 4, 3, 11, 28, 29 }; edgesOuter = new int[] {0, 1, 2, 3, 4, 11, 15, 20, 23, 26, 28, 29}; edgesPerimeter = new int[] {0, 1, 2, 3, 4, 11, 15, 20, 23, 26, 28, 29}; edgesInner = new int[] {5, 6, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18, 19, 21, 22, 24, 25, 27}; edgesCentre = new int[] { 13, 17, 18}; edgesTop = new int[] { 28, 29 }; edgesBottom = new int[] { 0, 1, 2, 3 }; edgesLeft = new int[] { 4 }; edgesRight = new int[] { 11 }; runAllTests(nameTest); if(!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- @Test public void testTiling3464() { makeTheBoard(Tiling.construct(TilingType.T3464, new DimConstant(2), null), SiteType.Cell); final String nameTest = "Tiling3464"; // Cells cellsCorners = new int[] { 1, 7, 9, 12, 15, 27, 33, 45, 48, 51, 53, 59 }; cellsOuter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 15, 16, 22, 23, 26, 27, 33, 34, 37, 38, 44, 45, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60}; cellsPerimeter = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 15, 16, 22, 23, 26, 27, 33, 34, 37, 38, 44, 45, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60}; final TIntArrayList outer = new TIntArrayList(cellsOuter); final TIntArrayList inner = new TIntArrayList(); for (int i = 0; i < 60; i++) if (!outer.contains(i)) inner.add(i); cellsInner = inner.toArray(); cellsCentre = new int[] { 30 }; cellsTop = new int[] { 58,59,60 }; cellsBottom = new int[] { 0,1,2}; cellsLeft = new int[] { 16,38 }; cellsRight = new int[] { 22,44 }; // TODO the vertices. // TODO the edges. runAllTests(nameTest); if(!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- @Test public void testCross() { makeTheBoard(new Merge(new GraphFunction[] { new Shift(new FloatConstant((float) 3.0), new FloatConstant((float) 0.0), null, new RectangleOnSquare(new DimConstant(12), new DimConstant(2), null, null)), new Shift(new FloatConstant((float) 0.0), new FloatConstant((float) 7.0), null, new RectangleOnSquare(new DimConstant(2), new DimConstant(8), null, null)) }, Boolean.valueOf(false)), SiteType.Cell ); final String nameTest = "Cross tiling by Square"; // Cells cellsCorners = new int[] { 0, 1, 14, 16, 18, 20, 26, 27, 28, 31, 32, 35 }; cellsOuter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35}; cellsPerimeter = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35}; cellsInner = new int[] { }; cellsCentre = new int[] { 12,13 }; cellsTop = new int[] { 26,27 }; cellsBottom = new int[] { 0,1 }; cellsLeft = new int[] { 28,32 }; cellsRight = new int[] { 31,35 }; // TODO the vertices. // TODO the edges. runAllTests(nameTest); if(!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- @Test public void testHexStar() { makeTheBoard(new Merge(new GraphFunction[] { new StarOnHex(new DimConstant(2)) }, Boolean.valueOf(false)), SiteType.Cell); final String nameTest = "Star tiling by Hex"; // Cells cellsCorners = new int[] {0, 3, 5, 7, 9, 16, 20, 27, 29, 31, 33, 36}; cellsOuter = new int[] {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 15, 16, 20, 21, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36}; cellsPerimeter = new int[] {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 15, 16, 20, 21, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36}; cellsInner = new int[] {6, 11, 12, 13, 14, 17, 18, 19, 22, 23, 24, 25, 30}; cellsCentre = new int[] { 18 }; cellsTop = new int[] { 36 }; cellsBottom = new int[] { 0 }; cellsLeft = new int[] {3, 27}; cellsRight = new int[] {9, 33}; // TODO the vertices. // TODO the edges. runAllTests(nameTest); if (!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- // @Test // public void testMorris() // { // makeTheBoard(new Morris(new DimConstant(3), BooleanConstant.construct(true)), SiteType.Cell); // final String nameTest = "Morris Tiling with Join Corners"; // // // Vertices // verticesCorners = new int[] { 0,2,21,23 }; // verticesOuter = new int[] { 0,1,2,9,14,23,22,21 }; // verticesPerimeter = new int[] { 0,1,2,9,14,23,22,21 }; // verticesInner = new int[] { 3,4,5,6,7,8,10,11,12,13,15,16,17,18,19,20 }; // verticesCentre = new int[] { 7, 11, 12, 16}; // verticesTop = new int[] { 21,22,23 }; // verticesBottom = new int[] { 0,1,2 }; // verticesLeft = new int[] { 0,9,21 }; // verticesRight = new int[] { 2,14,23 }; // // // TODO the cells. // // TODO the edges. // // runAllTests(nameTest); // // if (!testSucceed) // fail("Pregeneration for " + nameTest + " is failing"); // } // --------------------------------------------------------------------- @Test public void testUnion() { makeTheBoard(new Union(new GraphFunction[] { new RectangleOnSquare(new DimConstant(6), new DimConstant(2), null, null), new Shift(new FloatConstant((float) 2.0), new FloatConstant((float) 2.0), null, new RectangleOnSquare(new DimConstant(3), null, null, null)), new RectangleOnSquare(new DimConstant(2), new DimConstant(6), null, null) }, Boolean.valueOf(false)), SiteType.Vertex); final String nameTest = "Union of two boards tiling by square"; // Cells cellsCorners = new int[] { 0,13,4,5,6,7,8,9}; cellsOuter = new int[] { 0,1,2,3,4,5,6,7,8,9,10,11,12,13 }; cellsPerimeter = new int[] { 0,1,2,3,4,5,6,7,8,9,10,11,12,13 }; cellsInner = new int[] { }; //cellsCentre = new int[] { }; // Not sure? cellsTop = new int[] { 4 }; cellsBottom = new int[] { 0, 10, 11, 12, 13, 9 }; cellsLeft = new int[] {0,1,2,3,4,9 }; cellsRight = new int[] { 13 }; // TODO the vertices. // TODO the edges. runAllTests(nameTest); if (!testSucceed) fail("Pregeneration for " + nameTest + " is failing"); } // --------------------------------------------------------------------- // --------------------------Helper methods----------------------------- // --------------------------------------------------------------------- /** * Run all the tests. * * @param nameTest The name of the test. */ public void runAllTests(final String nameTest) { testCorners(SiteType.Cell, cellsCorners, nameTest); testOuter(SiteType.Cell, cellsOuter, nameTest); testPerimeter(SiteType.Cell, cellsPerimeter, nameTest); testInner(SiteType.Cell, cellsInner, nameTest); testCentre(SiteType.Cell, cellsCentre, nameTest); testTop(SiteType.Cell, cellsTop, nameTest); testBottom(SiteType.Cell, cellsBottom, nameTest); testLeft(SiteType.Cell, cellsLeft, nameTest); testRight(SiteType.Cell, cellsRight, nameTest); testCorners(SiteType.Vertex, verticesCorners, nameTest); testOuter(SiteType.Vertex, verticesOuter, nameTest); testPerimeter(SiteType.Vertex, verticesPerimeter, nameTest); testInner(SiteType.Vertex, verticesInner, nameTest); testCentre(SiteType.Vertex, verticesCentre, nameTest); testTop(SiteType.Vertex, verticesTop, nameTest); testBottom(SiteType.Vertex, verticesBottom, nameTest); testLeft(SiteType.Vertex, verticesLeft, nameTest); testRight(SiteType.Vertex, verticesRight, nameTest); testCorners(SiteType.Edge, edgesCorners, nameTest); testOuter(SiteType.Edge, edgesOuter, nameTest); testPerimeter(SiteType.Edge, edgesPerimeter, nameTest); testInner(SiteType.Edge, edgesInner, nameTest); testCentre(SiteType.Edge, edgesCentre, nameTest); testTop(SiteType.Edge, edgesTop, nameTest); testBottom(SiteType.Edge, edgesBottom, nameTest); testLeft(SiteType.Edge, edgesLeft, nameTest); testRight(SiteType.Edge, edgesRight, nameTest); } /** * Run the test for the centre sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testCentre(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().centre(type), "Centre"); } /** * Run the test for the right sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testRight(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().right(type), "Right"); } /** * Run the test for the left sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testLeft(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().left(type), "Left"); } /** * Run the test for the bottom sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testBottom(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().bottom(type), "Bottom"); } /** * Run the test for the top sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testTop(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().top(type), "Top"); } /** * Run the test for the perimeter sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testPerimeter(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().perimeter(type), "Perimeter"); } /** * Run the test for the inner sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testInner(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().inner(type), "Inner"); } /** * Run the test for the outer sites. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testOuter(final SiteType type, final int[] correctSites, final String nameTest) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().outer(type), "Outer"); } /** * Run the test for the corners. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. */ public void testCorners ( final SiteType type, final int[] correctSites, final String nameTest ) { if(correctSites != null) runTest(type, correctSites, nameTest, board.topology().corners(type), "Corners"); } /** * Run the test. * * @param type The type of site to test. * @param correctSites The expected sites. * @param nameTest The name of the current test. * @param pregenElements The list of the elements generated. * @param pregenTest The type of pregeneration to test. */ public void runTest ( final SiteType type, final int[] correctSites, final String nameTest, final List<TopologyElement> pregenElements, final String pregenTest ) { final TIntArrayList expectedSites = new TIntArrayList(correctSites); if (!check(transformList(pregenElements), expectedSites)) { System.out.println(nameTest + ": "); System.out.println(type.toString() + " " + pregenTest + " are: " + transformList(pregenElements)); System.out.println("They should be: " + expectedSites + " \n"); this.testSucceed = false; } } /** * Init the test. */ public void init() { this.testSucceed = true; // Cells cellsCorners = null; cellsOuter = null; cellsPerimeter = null; cellsInner = null; cellsCentre = null; cellsTop = null; cellsBottom = null; cellsLeft = null; cellsRight = null; // Vertices verticesCorners = null; verticesOuter = null; verticesPerimeter = null; verticesInner = null; verticesCentre = null; verticesTop = null; verticesBottom = null; verticesLeft = null; verticesRight = null; // Edges edgesCorners = null; edgesOuter = null; edgesPerimeter = null; edgesInner = null; edgesCentre = null; edgesTop = null; edgesBottom = null; edgesLeft = null; edgesRight = null; } /** * Compute the board. * * @param function The graphFunction to test. */ public void makeTheBoard(final GraphFunction function, final SiteType useType) { init(); board = new Board(function, null, null, null, null, useType, Boolean.FALSE); board.createTopology(0, 0); for (final SiteType type : SiteType.values()) for (final TopologyElement element : board.topology().getGraphElements(type)) board.topology().convertPropertiesToList(type, element); } /** * @param graphElements * * @return A list with all the indices of a list of graph element. */ public static TIntArrayList transformList(final List<? extends TopologyElement> graphElements) { final TIntArrayList result = new TIntArrayList(); for (final TopologyElement element : graphElements) result.add(element.index()); return result; } /** * @param indices * @param expectedIndices * @return True if the list has the same indices on it and the same size. */ public static boolean check(final TIntArrayList indices, final TIntArrayList expectedIndices) { if (indices.size() != expectedIndices.size()) return false; for (int i = 0; i < indices.size(); i++) { final int index = indices.get(i); boolean found = false; for (int j = 0; j < expectedIndices.size(); j++) { final int value = expectedIndices.get(j); if (value == index) { found = true; break; } } if (!found) return false; } return true; } /** * To test the radials from a specific graph element with a specific * absolute direction. * * @param absoluteDirection The absolute direction. * @param type The type of the graph element. * @param origin The index of the origin of the radials. * @param expectedRadials Th expected radials. */ public void testRadials(final AbsoluteDirection absoluteDirection, final SiteType type, final int origin, final int[][] expectedRadials) { final List<Radial> radials = board.topology().trajectories().radials(type, origin, absoluteDirection); for (int i = 0; i < radials.size(); i++) { final Radial radial = radials.get(i); final List<TopologyElement> elementInRadial = new ArrayList<TopologyElement>(); for (final GraphElement graphElement : radial.steps()) elementInRadial.add(board.topology().getGraphElement(type, graphElement.id())); if (!check(transformList(elementInRadial), new TIntArrayList(expectedRadials[i]))) { System.out.println( "Square tiling by Square: The radials in absolute direction " + absoluteDirection.toString() + " from the " + type.toString() + " " + origin + " are wrong. They should be (in this order):"); for (int j = 0; j < expectedRadials.length; j++) System.out.println("- " + new TIntArrayList(expectedRadials[j])); System.out.println("But these radials are: "); for (int k = 0; k < radials.size(); k++) { final Radial wrongRadial = radials.get(k); final List<TopologyElement> elementInWrongRadial = new ArrayList<TopologyElement>(); for (final GraphElement graphElement : wrongRadial.steps()) elementInWrongRadial.add(board.topology().getGraphElement(type, graphElement.id())); System.out.println("- " + transformList(elementInWrongRadial)); } System.out.println(); testSucceed = false; break; } } } }
25,007
32.658143
261
java
Ludii
Ludii-master/Player/test/travis/quickTests/ai/TestPrioritizedExperienceReplay.java
package travis.quickTests.ai; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.junit.Test; import main.collections.FVector; import training.expert_iteration.ExItExperience; import utils.data_structures.experience_buffers.PrioritizedReplayBuffer; /** * Unit tests for Prioritized Experience Replay implementation. * * Using similar unit tests (where applicable) as in Dopamine: * https://github.com/google/dopamine/blob/master/tests/dopamine/replay_memory/prioritized_replay_buffer_test.py * * @author Dennis Soemers */ @SuppressWarnings("static-method") public class TestPrioritizedExperienceReplay { /** Capacity of replay buffers in unit tests */ private static final int REPLAY_CAPACITY = 100; /** * @return A default buffer for testing purposes */ private static PrioritizedReplayBuffer createDefaultMemory() { return new PrioritizedReplayBuffer(REPLAY_CAPACITY); } /** * @param memory Replay buffer to add blank experience to * @return Index at which the new experience should be in the buffer */ private static int addBlank(final PrioritizedReplayBuffer memory) { return addBlank(memory, 1.f); } /** * @param memory Replay buffer to add blank experience to * @param priority Priority with which to add new sample * @return Index at which the new experience should be in the buffer */ private static int addBlank(final PrioritizedReplayBuffer memory, final float priority) { memory.add(new ExItExperience(null, null, null, null, null, 1.f), priority); return (memory.cursor() - 1) % REPLAY_CAPACITY; } @Test public void testAdd() { System.out.println("Running testAdd()"); final PrioritizedReplayBuffer memory = createDefaultMemory(); assertEquals(memory.cursor(), 0); addBlank(memory); assertEquals(memory.cursor(), 1); assertEquals(memory.addCount(), 1L); System.out.println("Finished testAdd()"); } @Test public void testSetAndGetPriority() { System.out.println("Running testSetAndGetPriority()"); final PrioritizedReplayBuffer memory = createDefaultMemory(); final int batchSize = 7; final int[] indices = new int[batchSize]; for (int index = 0; index < batchSize; ++index) { indices[index] = addBlank(memory); } final float[] priorities = new float[batchSize]; for (int i = 0; i < batchSize; ++i) { priorities[i] = i; } memory.setPriorities(indices, priorities); // We send the indices in reverse order and verify // that the priorities come back in that same order final int[] reversedIndices = new int[batchSize]; for (int i = 0; i < batchSize; ++i) { reversedIndices[i] = indices[batchSize - i - 1]; } final float[] fetchedPriorities = memory.getPriorities(reversedIndices); for (int i = 0; i < batchSize; ++i) { assertEquals((float) Math.pow(priorities[i], memory.alpha()), fetchedPriorities[batchSize - 1 - i], 0.0001f); } System.out.println("Finished testSetAndGetPriority()"); } @Test public void testLowPriorityElementNotFrequentlySampled() { System.out.println("Running testLowPriorityElementNotFrequentlySampled()"); final PrioritizedReplayBuffer memory = createDefaultMemory(); // add 0-priority sample addBlank(memory, 0.f); // add more items with default priority (of 1) for (int i = 0; i < 3; ++i) { memory.add(new ExItExperience(null, null, null, null, new FVector(0), 1.f), 1.f); } // this test should always pass for (int i = 0; i < 100; ++i) { final List<ExItExperience> batch = memory.sampleExperienceBatch(2); for (final ExItExperience sample : batch) { assertNotNull(sample.expertValueEstimates()); } } System.out.println("Finished testLowPriorityElementNotFrequentlySampled()"); } public void testNoIdxOutOfBounds() { System.out.println("Running testNoIdxOutOfBounds()"); for (int rep = 0; rep < 100; ++rep) { // random capacity in [100, 4500] final int capacity = (int) (4400 * Math.random() + 100); // create buffer final PrioritizedReplayBuffer buffer = new PrioritizedReplayBuffer(capacity); // fill up replay buffer with random priorities for (int i = 0; i < capacity; ++i) { addBlank(buffer, (float) Math.random()); } // sample indices, make sure we never exceed capacity final int[] indices = buffer.sampleIndexBatch(Math.min(500, capacity)); for (final int idx : indices) { assert (idx >= 0); assert (idx < capacity); } } System.out.println("Finished testNoIdxOutOfBounds()"); } }
4,614
26.470238
112
java
Ludii
Ludii-master/Player/test/travis/recons/ReconstructionTest.java
package travis.recons; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import completer.Completion; import main.FileHandling; import other.GameLoader; import reconstruction.completer.CompleterWithPrepro; /** * Unit Test to compile all the reconstruction games on the lud/reconstruction folder * * @author Eric.Piette */ public class ReconstructionTest { @SuppressWarnings("static-method") @Test public void testCompilingLudFromMemory() { System.out.println("\n=========================================\nTest: Compile all .lud corresponding to reconstruction:\n"); final List<String> failedGames = new ArrayList<String>(); boolean failure = false; final long startAt = System.nanoTime(); // Load from memory final String[] choices = FileHandling.listGames(); CompleterWithPrepro completer = new CompleterWithPrepro(0.5, 0.5, 0.0, 0.0, -1); final int idRulesetToRecons = -1; for (final String fileName : choices) { //if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/eric/recons/")) if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/pending/")) //if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/board/war/leaping/lines/Manipur Capturing Game")) continue; // Get game description from resource //System.out.println("Game: " + fileName); String path = fileName.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); String desc = ""; String line; try ( final InputStream in = GameLoader.class.getResourceAsStream(path); final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); ) { while ((line = rdr.readLine()) != null) { desc += line + "\n"; // System.out.println("line: " + line); } } catch (final IOException e1) { failure = true; e1.printStackTrace(); } // Parse and reconstruct one instance of a game which is respected the expected concepts. Completion completion = null; try { completion = completer.completeSampled(desc, idRulesetToRecons); } catch (final Exception e) { failure = true; e.printStackTrace(); } if (completion != null) { System.out.println("Reconstruction(s) of " + fileName); // for (int n = 0; n < completions.size(); n++) // { // final Completion completion = completions.get(n); //System.out.println(completion.raw()); // Check if the concepts expected are present. //boolean expectedConcepts = Concept.isExpectedConcepts(completion.raw()); //System.out.println("RECONS HAS THE EXPECTED CONCEPTS? " + expectedConcepts); // } //System.out.println(); } else { failure = true; failedGames.add(fileName); System.err.println("** FAILED TO COMPILE: " + fileName); } } final long stopAt = System.nanoTime(); final double secs = (stopAt - startAt) / 1000000000.0; System.out.println("\nDone in " + secs + "s."); if (!failedGames.isEmpty()) { System.out.println("\nUncompiled games:"); for (final String name : failedGames) System.out.println(name); } if (failure) fail(); } }
3,433
25.828125
135
java
Ludii
Ludii-master/PlayerDesktop/src/app/DesktopApp.java
package app; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import org.json.JSONObject; import org.json.JSONTokener; import app.display.MainWindowDesktop; import app.display.dialogs.AboutDialog; import app.display.dialogs.SettingsDialog; import app.display.dialogs.MoveDialog.PossibleMovesDialog; import app.display.dialogs.MoveDialog.PuzzleDialog; import app.display.util.DesktopGUIUtil; import app.display.views.tabs.TabView; import app.loading.FileLoading; import app.loading.GameLoading; import app.loading.TrialLoading; import app.menu.MainMenu; import app.menu.MainMenuFunctions; import app.util.SettingsDesktop; import app.util.UserPreferences; import app.utils.GameSetup; import app.utils.SettingsExhibition; import app.utils.Sound; import app.views.View; import game.Game; import game.rules.phase.Phase; import main.Constants; import main.StringRoutines; import main.collections.FastArrayList; import main.options.GameOptions; import manager.ai.AIDetails; import manager.ai.AIUtil; import other.context.Context; import other.location.Location; import other.move.Move; import tournament.Tournament; import utils.AIFactory; //----------------------------------------------------------------------------- /** * The main player object. * * @author Matthew.Stephenson and cambolbro and Eric.Piette */ public class DesktopApp extends PlayerApp { /** App name. */ public static final String AppName = "Ludii Player"; /** Set me to false if we are making a release jar. * NOTE. In reality this is final, but keeping it non final prevents dead-code warnings. */ public static boolean devJar = false; /** Main frame. */ protected static JFrameListener frame; /** Main view. */ protected static MainWindowDesktop view; /** Current Graphics Device (screen) that is displaying the frame. */ private static GraphicsDevice currentGraphicsDevice = null; /** Minimum resolution of the application. */ private static final int minimumViewWidth = 400; private static final int minimumViewHeight = 400; //------------------------------------------------------------------------- /** * Reference to file chooser we use for selecting JSON files (containing AI configurations) */ private static JFileChooser jsonFileChooser; /** * Reference to file chooser we use for selecting JAR files (containing third-party AIs) */ private static JFileChooser jarFileChooser; /** * Reference to file chooser we use for selecting AI.DEF files (containing AI configurations) */ private static JFileChooser aiDefFileChooser; /** * Reference to file chooser we use for selecting LUD files */ private static JFileChooser gameFileChooser; //------------------------------------------------------------------------- /** Whether the trial should be loaded from a saved file (based on file validity checks). */ private static boolean shouldLoadTrial = false; //------------------------------------------------------------------------- /** Reference to file chooser we use for saving games we have just played */ private static JFileChooser saveGameFileChooser; /** File chooser for loading games. */ protected static JFileChooser loadGameFileChooser; /** File chooser for loading games. */ private static JFileChooser loadTrialFileChooser; /** File chooser for loading games. */ private static JFileChooser loadTournamentFileChooser; /** Last selected filepath for JSON file chooser (loaded from preferences) */ private static String lastSelectedJsonPath; /** Last selected filepath for JSON file chooser (loaded from preferences) */ private static String lastSelectedJarPath; /** Last selected filepath for AI.DEF file chooser (loaded from preferences) */ private static String lastSelectedAiDefPath; /** Last selected filepath for Game file chooser (loaded from preferences) */ private static String lastSelectedGamePath; /** Last selected filepath for JSON file chooser (loaded from preferences) */ private static String lastSelectedSaveGamePath; /** Last selected filepath for JSON file chooser (loaded from preferences) */ private static String lastSelectedLoadTrialPath; /** Last selected filepath for JSON file chooser (loaded from preferences) */ private static String lastSelectedLoadTournamentPath; //------------------------------------------------------------------------- /** * Constructor. */ public DesktopApp() { // Do nothing. } //------------------------------------------------------------------------- /** * Create the main Desktop application. */ public void createDesktopApp() { // Invoke UI in the correct thread, otherwise menu may not draw SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < Constants.MAX_PLAYERS + 1; i++) // one extra for the shared player { final JSONObject json = new JSONObject() .put("AI", new JSONObject() .put("algorithm", "Human") ); manager().aiSelected()[i] = new AIDetails(manager(), json, i, "Human"); } try { createFrame(); } catch (final SQLException e) { e.printStackTrace(); } } }); } //------------------------------------------------------------------------- /** * Gets the full frame title for displaying at the top of the application. */ public String getFrameTitle(final Context context) { final Game game = context.game(); String frameTitle = AppName + " - " + game.name(); GameOptions gameOptions = game.description().gameOptions(); if (manager().settingsManager().userSelections().ruleset() != Constants.UNDEFINED && !SettingsExhibition.exhibitionVersion) { final String rulesetName = game.description().rulesets().get(manager().settingsManager().userSelections().ruleset()).heading(); frameTitle += " (" + rulesetName + ")"; } else if (gameOptions.numCategories() > 0) { final List<String> optionHeadings = gameOptions.allOptionStrings(manager().settingsManager().userSelections().selectedOptionStrings()); final boolean defaultOptionsLoaded = optionHeadings.equals(gameOptions.allOptionStrings(new ArrayList<String>())); if (optionHeadings.size() > 0 && !defaultOptionsLoaded) { final String appendOptions = " (" + StringRoutines.join(", ", optionHeadings) + ")"; frameTitle += appendOptions; } } if (context.isAMatch()) { final Context instanceContext = context.currentInstanceContext(); frameTitle += " - " + instanceContext.game().name(); gameOptions = game.description().gameOptions(); if (gameOptions != null && gameOptions.numCategories() > 0) { String appendOptions = " ("; int found = 0; for (int cat = 0; cat < gameOptions.numCategories(); cat++) { try { if (gameOptions.categories().get(cat).options().size() > 0) { final List<String> optionHeadings = gameOptions.categories().get(cat).options().get(0).menuHeadings(); String optionSelected = optionHeadings.get(0); optionSelected = optionSelected.substring(optionSelected.indexOf('/')+1); if (found > 0) appendOptions += ", "; appendOptions += optionSelected; found++; } } catch (final Exception e) { e.printStackTrace(); //break; } } appendOptions += ")"; if (found > 0) frameTitle += appendOptions; } frameTitle += " - game #" + (manager().ref().context().completedTrials().size() + 1); } if (manager().settingsNetwork().getActiveGameId() > 0 && manager().settingsNetwork().getTournamentId() > 0) frameTitle += " (game " + manager().settingsNetwork().getActiveGameId() + " in tournament " + manager().settingsNetwork().getTournamentId() + ")"; else if (manager().settingsNetwork().getActiveGameId() > 0) frameTitle += " (game " + manager().settingsNetwork().getActiveGameId() + ")"; if (settingsPlayer().showPhaseInTitle() && !context.game().hasSubgames()) { final int mover = context.state().mover(); final int indexPhase = context.state().currentPhase(mover); final Phase phase = context.game().rules().phases()[indexPhase]; frameTitle += " (phase " + phase.name() + ")"; } return frameTitle; } //------------------------------------------------------------------------- /** * Display an error message on the status panel. */ @Override public void reportError(final String text) { if (view != null) { if (frame != null) { frame.setContentPane(view); frame.repaint(); frame.revalidate(); } } EventQueue.invokeLater(() -> { addTextToStatusPanel(text + "\n"); }); } //------------------------------------------------------------------------- @Override public void actionPerformed(final ActionEvent e) { MainMenuFunctions.checkActionsPerformed(this, e); } @Override public void itemStateChanged(final ItemEvent e) { MainMenuFunctions.checkItemStateChanges(this, e); } //--------------------------------------------------------------------------- /** Tasks that are performed when the application is closed. */ public void appClosedTasks() { if (SettingsExhibition.exhibitionVersion) return; manager().settingsNetwork().restoreAiPlayers(manager()); // Close all AI objects for (final AIDetails ai : manager().aiSelected()) if (ai.ai() != null) ai.ai().closeAI(); if (manager().ref().context().game().equipmentWithStochastic()) manager().ref().context().trial().reset(manager().ref().context().game()); // Save the current trial final File file = new File("." + File.separator + "ludii.trl"); TrialLoading.saveTrial(this, file); // Save the rest of the preferences UserPreferences.savePreferences(this); } //------------------------------------------------------------------------- /** * Launch the frame. */ void createFrame() throws SQLException { try { UserPreferences.loadPreferences(this); } catch (final Exception e) { System.out.println("Failed to create preferences file."); e.printStackTrace(); } try { frame = new JFrameListener(AppName, this); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Logo try { final URL resource = this.getClass().getResource("/ludii-logo-100x100.png"); final BufferedImage image = ImageIO.read(resource); frame.setIconImage(image); } catch (final IOException e) { e.printStackTrace(); } view = new MainWindowDesktop(this); frame.setContentPane(view); frame.setSize(SettingsDesktop.defaultWidth, SettingsDesktop.defaultHeight); if (SettingsExhibition.exhibitionVersion) { frame.setUndecorated(true); frame.setResizable(false); frame.setSize(SettingsExhibition.exhibitionDisplayWidth, SettingsExhibition.exhibitionDisplayHeight); } try { if (settingsPlayer().defaultX() == -1 || settingsPlayer().defaultY() == -1) frame.setLocationRelativeTo(null); else frame.setLocation(settingsPlayer().defaultX(), settingsPlayer().defaultY()); if (settingsPlayer().frameMaximised()) frame.setExtendedState(frame.getExtendedState() | Frame.MAXIMIZED_BOTH); } catch (final Exception e) { frame.setLocationRelativeTo(null); } frame.setVisible(true); frame.setMinimumSize(new Dimension(minimumViewWidth, minimumViewHeight)); FileLoading.createFileChoosers(); setCurrentGraphicsDevice(frame.getGraphicsConfiguration().getDevice()); // gets called when the app is closed (save preferences and trial) Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { appClosedTasks(); } }); loadInitialGame(true); } catch (final Exception e) { System.out.println("Failed to create application frame."); e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Loads the initial game. * Either the default game of the previously loaded game when the application was last closed. */ protected void loadInitialGame(final boolean firstTry) { try { if (SettingsExhibition.exhibitionVersion) { GameLoading.loadGameFromMemory(this, SettingsExhibition.exhibitionGamePath, false); if (SettingsExhibition.againstAI) { final JSONObject json = new JSONObject().put("AI", new JSONObject() .put("algorithm", "UCT") ); AIUtil.updateSelectedAI(manager(), json, 2, "UCT"); manager().aiSelected()[2].setThinkTime(SettingsExhibition.thinkingTime); } bridge().settingsVC().setShowPossibleMoves(true); return; } if (firstTry) TrialLoading.loadStartTrial(this); if (manager().ref().context() == null) { if (firstTry) GameLoading.loadGameFromMemory(this, Constants.DEFAULT_GAME_PATH, false); else { settingsPlayer().setLoadedFromMemory(true); GameSetup.compileAndShowGame(this, Constants.FAIL_SAFE_GAME_DESCRIPTION, false); EventQueue.invokeLater(() -> { setTemporaryMessage("Failed to start game. Loading default game (Tic-Tac-Toe)."); }); } } frame.setJMenuBar(new MainMenu(this)); for (int i = 1; i <= manager().ref().context().game().players().count(); i++) if (aiSelected()[i] != null) AIUtil.updateSelectedAI(manager(), manager().aiSelected()[i].object(), i, manager().aiSelected()[i].menuItemName()); } catch (final Exception e) { e.printStackTrace(); if (firstTry) { // Try and load the default game. manager().setSavedLudName(null); settingsPlayer().setLoadedFromMemory(true); setLoadTrial(false); loadInitialGame(false); } if (manager().savedLudName() != null) addTextToStatusPanel("Failed to start game: " + manager().savedLudName() + "\n"); else if (manager().ref().context().game().name() != null) addTextToStatusPanel("Failed to start external game description.\n"); } } //------------------------------------------------------------------------- @Override public Tournament tournament() { return manager().getTournament(); } @Override public void setTournament(final Tournament tournament) { manager().setTournament(tournament); } public static GraphicsDevice currentGraphicsDevice() { return currentGraphicsDevice; } public static void setCurrentGraphicsDevice(final GraphicsDevice currentGraphicsDevice) { DesktopApp.currentGraphicsDevice = currentGraphicsDevice; } public AIDetails[] aiSelected() { return manager().aiSelected(); } public static JFileChooser jsonFileChooser() { return jsonFileChooser; } public static void setJsonFileChooser(final JFileChooser jsonFileChooser) { DesktopApp.jsonFileChooser = jsonFileChooser; } public static JFileChooser jarFileChooser() { return jarFileChooser; } public static JFileChooser gameFileChooser() { return gameFileChooser; } public static void setJarFileChooser(final JFileChooser jarFileChooser) { DesktopApp.jarFileChooser = jarFileChooser; } public static void setGameFileChooser(final JFileChooser gameFileChooser) { DesktopApp.gameFileChooser = gameFileChooser; } public static JFileChooser saveGameFileChooser() { return saveGameFileChooser; } public static void setSaveGameFileChooser(final JFileChooser saveGameFileChooser) { DesktopApp.saveGameFileChooser = saveGameFileChooser; } public static JFileChooser loadTrialFileChooser() { return loadTrialFileChooser; } public static void setLoadTrialFileChooser(final JFileChooser loadTrialFileChooser) { DesktopApp.loadTrialFileChooser = loadTrialFileChooser; } public static JFileChooser loadTournamentFileChooser() { return loadTournamentFileChooser; } public static void setLoadTournamentFileChooser(final JFileChooser loadTournamentFileChooser) { DesktopApp.loadTournamentFileChooser = loadTournamentFileChooser; } public static void setLoadTrial(final boolean shouldLoadTrial) { DesktopApp.shouldLoadTrial = shouldLoadTrial; } public static boolean shouldLoadTrial() { return shouldLoadTrial; } public static String lastSelectedSaveGamePath() { return lastSelectedSaveGamePath; } public static void setLastSelectedSaveGamePath(final String lastSelectedSaveGamePath) { DesktopApp.lastSelectedSaveGamePath = lastSelectedSaveGamePath; } public static String lastSelectedJsonPath() { return lastSelectedJsonPath; } public static void setLastSelectedJsonPath(final String lastSelectedJsonPath) { DesktopApp.lastSelectedJsonPath = lastSelectedJsonPath; } public static String lastSelectedJarPath() { return lastSelectedJarPath; } public static String lastSelectedGamePath() { return lastSelectedGamePath; } public static void setLastSelectedJarPath(final String lastSelectedJarPath) { DesktopApp.lastSelectedJarPath = lastSelectedJarPath; } public static void setLastSelectedGamePath(final String lastSelectedGamePath) { DesktopApp.lastSelectedGamePath = lastSelectedGamePath; } public static String lastSelectedLoadTrialPath() { return lastSelectedLoadTrialPath; } public static void setLastSelectedLoadTrialPath(final String lastSelectedLoadTrialPath) { DesktopApp.lastSelectedLoadTrialPath = lastSelectedLoadTrialPath; } public static String lastSelectedLoadTournamentPath() { return lastSelectedLoadTournamentPath; } public static void setLastSelectedLoadTournamentPath(final String lastSelectedLoadTournamentPath) { DesktopApp.lastSelectedLoadTournamentPath = lastSelectedLoadTournamentPath; } /** * @return Main view. */ public static MainWindowDesktop view() { return view; } /** * @return Main frame. */ public static JFrameListener frame() { return frame; } @Override public void updateFrameTitle(final boolean alsoUpdateMenu) { frame().setTitle(getFrameTitle(manager().ref().context())); if (alsoUpdateMenu) { frame().setJMenuBar(new MainMenu(this)); view().createPanels(); } } //------------------------------------------------------------------------- @Override public void refreshNetworkDialog() { remoteDialogFunctionsPublic().refreshNetworkDialog(); } //------------------------------------------------------------------------- @Override public void loadGameFromName(final String name, final List<String> options, final boolean debug) { GameLoading.loadGameFromName(this, name, options, debug); } @Override public JSONObject getNameFromJar() { // we'll have to go through file chooser final JFileChooser fileChooser = DesktopApp.jarFileChooser(); fileChooser.setDialogTitle("Select JAR file containing AI."); final int jarReturnVal = fileChooser.showOpenDialog(DesktopApp.frame()); final File jarFile; if (jarReturnVal == JFileChooser.APPROVE_OPTION) jarFile = fileChooser.getSelectedFile(); else jarFile = null; if (jarFile != null && jarFile.exists()) { final List<Class<?>> classes = AIFactory.loadThirdPartyAIClasses(jarFile); if (classes.size() > 0) { // show dialog with options final URL logoURL = this.getClass().getResource("/ludii-logo-64x64.png"); final ImageIcon icon = new ImageIcon(logoURL); final String[] choices = new String[classes.size()]; for (int i = 0; i < choices.length; ++i) { choices[i] = classes.get(i).getName(); } final String choice = (String) JOptionPane.showInputDialog(DesktopApp.frame(), "AI Classes", "Choose an AI class to load", JOptionPane.QUESTION_MESSAGE, icon, choices, choices[0]); if (choice == null) { System.err.println("No AI class selected."); return null; } else { return new JSONObject().put("AI", new JSONObject() .put("algorithm", "From JAR") .put("JAR File", jarFile.getAbsolutePath()) .put("Class Name", choice) ); } } else { System.err.println("Could not find any AI classes."); return null; } } else { System.err.println("Could not find JAR file."); return null; } } @Override public JSONObject getNameFromJson() { // we'll have to go through file chooser final JFileChooser fileChooser = DesktopApp.jsonFileChooser(); fileChooser.setDialogTitle("Select JSON file containing AI."); final int jsonReturnVal = fileChooser.showOpenDialog(DesktopApp.frame()); final File jsonFile; if (jsonReturnVal == JFileChooser.APPROVE_OPTION) jsonFile = fileChooser.getSelectedFile(); else jsonFile = null; if (jsonFile != null && jsonFile.exists()) { try (final InputStream inputStream = new FileInputStream(jsonFile)) { return new JSONObject(new JSONTokener(inputStream)); } catch (final IOException e) { e.printStackTrace(); } } else { System.err.println("Could not find JSON file."); } return null; } @Override public JSONObject getNameFromAiDef() { // we'll have to go through file chooser final JFileChooser fileChooser = DesktopApp.aiDefFileChooser(); fileChooser.setDialogTitle("Select AI.DEF file containing AI."); final int aiDefReturnVal = fileChooser.showOpenDialog(DesktopApp.frame()); final File aiDefFile; if (aiDefReturnVal == JFileChooser.APPROVE_OPTION) aiDefFile = fileChooser.getSelectedFile(); else aiDefFile = null; if (aiDefFile != null && aiDefFile.exists()) { return new JSONObject().put ( "AI", new JSONObject() .put("algorithm", "From AI.DEF") .put("AI.DEF File", aiDefFile.getAbsolutePath()) ); } else { System.err.println("Could not find AI.DEF file."); } return null; } @Override public void addTextToStatusPanel(final String text) { EventQueue.invokeLater(() -> { view.tabPanel().page(TabView.PanelStatus).addText(text); }); } @Override public void addTextToAnalysisPanel(final String text) { EventQueue.invokeLater(() -> { view.tabPanel().page(TabView.PanelAnalysis).addText(text); }); } @Override public void setTemporaryMessage(final String text) { view.setTemporaryMessage(text); } @Override public void setVolatileMessage(final String text) { MainWindowDesktop.setVolatileMessage(this, text); } @Override public void showPuzzleDialog(final int site) { PuzzleDialog.createAndShowGUI(this, manager().ref().context(), site); } @Override public void showPossibleMovesDialog(final Context context, final FastArrayList<Move> possibleMoves) { PossibleMovesDialog.createAndShowGUI(this, context, possibleMoves, false); } @Override public void selectAnalysisTab() { view.tabPanel().select((TabView.PanelAnalysis)); } @Override public void repaint() { view.isPainting = true; view.repaint(); view.revalidate(); } @Override public void reportDrawAgreed() { //final String lastLine = view.tabPanel().page(TabView.PanelStatus).text().split("\n")[view.tabPanel().page(TabView.PanelStatus).text().split("\n").length-1]; final String message = "All players have agreed to a draw, for Game " + manager().settingsNetwork().getActiveGameId() + ".\nThe Game is Over.\n"; if (!view.tabPanel().page(TabView.PanelStatus).text().contains(message)) addTextToStatusPanel(message); } @Override public void reportForfeit(final int playerForfeitNumber) { final String message = "Player " + playerForfeitNumber + " has resigned Game " + manager().settingsNetwork().getActiveGameId() + ".\nThe Game is Over.\n"; if (!view.tabPanel().page(TabView.PanelStatus).text().contains(message)) addTextToStatusPanel(message); } @Override public void reportTimeout(final int playerForfeitNumber) { final String message = "Player " + playerForfeitNumber + " has timed out for Game " + manager().settingsNetwork().getActiveGameId() + ".\nThe Game is Over.\n"; if (!view.tabPanel().page(TabView.PanelStatus).text().contains(message)) addTextToStatusPanel(message); } @Override public void updateTabs(final Context context) { EventQueue.invokeLater(() -> { view.tabPanel().updateTabs(context); }); } @Override public void playSound(final String soundName) { if (settingsPlayer().isMoveSoundEffect()) Sound.playSound(soundName); } @Override public void saveTrial() { final File file = new File("." + File.separator + "ludii.trl"); TrialLoading.saveTrial(this, file); } //------------------------------------------------------------------------- @Override public void repaintTimerForPlayer(final int playerId) { if (view.playerNameList[playerId] != null) view.repaint(DesktopApp.view.playerNameList[playerId]); } @Override public void repaintComponentBetweenPoints(final Context context, final Location moveFrom, final Point startPoint, final Point endPoint) { DesktopGUIUtil.repaintComponentBetweenPoints(this, context, moveFrom, startPoint, endPoint); } @Override public void writeTextToFile(final String fileName, final String log) { FileLoading.writeTextToFile(fileName, log); } @Override public void resetMenuGUI() { DesktopApp.frame().setJMenuBar(new MainMenu(this)); } @Override public void showSettingsDialog() { if (!SettingsExhibition.exhibitionVersion) { SettingsDialog.createAndShowGUI(this); } } @Override public void showOtherDialog(final FastArrayList<Move> otherPossibleMoves) { PossibleMovesDialog.createAndShowGUI(this, contextSnapshot().getContext(this), otherPossibleMoves, true); } @Override public void showInfoDialog() { AboutDialog.showAboutDialog(this); } //------------------------------------------------------------------------- @Override public int width() { return view.width(); } @Override public int height() { return view.height(); } @Override public Rectangle[] playerSwatchList() { return view.playerSwatchList; } @Override public Rectangle[] playerNameList() { return view.playerNameList; } @Override public boolean[] playerSwatchHover() { return view.playerSwatchHover; } @Override public boolean[] playerNameHover() { return view.playerNameHover; } @Override public List<View> getPanels() { return view.getPanels(); } @Override public void repaint(final Rectangle rect) { view.repaint(rect); } public static JFileChooser aiDefFileChooser() { return aiDefFileChooser; } public static void setAiDefFileChooser(final JFileChooser aiDefFileChooser) { DesktopApp.aiDefFileChooser = aiDefFileChooser; } public static String lastSelectedAiDefPath() { return lastSelectedAiDefPath; } public static void setLastSelectedAiDefPath(final String lastSelectedAiDefPath) { DesktopApp.lastSelectedAiDefPath = lastSelectedAiDefPath; } }
27,457
24.903774
161
java
Ludii
Ludii-master/PlayerDesktop/src/app/JFrameListener.java
package app; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import app.move.MoveHandler; import game.util.directions.AbsoluteDirection; /** * JFrame for listening to keyboard button presses. * @author Matthew.Stephenson * */ public class JFrameListener extends JFrame implements KeyListener { private static final long serialVersionUID = 1L; public PlayerApp app; JFrameListener(final String appName, final PlayerApp app) { super(appName); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); this.app = app; } @Override public void keyPressed(final KeyEvent e) { // Rotate large pieces. if (e.getKeyCode() == KeyEvent.VK_R) { app.settingsPlayer().setCurrentWalkExtra(app.settingsPlayer().currentWalkExtra()+1); app.repaint(); } else if (e.getKeyCode() == KeyEvent.VK_TAB) { int nextTabIndex = app.settingsPlayer().tabSelected() + 1; if (nextTabIndex >= DesktopApp.view().tabPanel().pages().size()) nextTabIndex = 0; DesktopApp.view().tabPanel().select(nextTabIndex); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD8) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.N); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD4) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.W); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD2) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.S); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD6) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.E); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD1) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.SW); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD3) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.SE); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD7) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.NW); } else if (e.getKeyCode() == KeyEvent.VK_NUMPAD9) { MoveHandler.applyDirectionMove(app, AbsoluteDirection.NE); } } @Override public void keyReleased(final KeyEvent arg0) { // do nothing } @Override public void keyTyped(final KeyEvent arg0) { // do nothing } }
2,223
22.913978
87
java
Ludii
Ludii-master/PlayerDesktop/src/app/PlayerCLI.java
package app; import java.util.Arrays; import gameDistance.CompareAllDistanceMetrics; import kilothon.Kilothon; import ludemeplexDetection.LudemeplexDetection; import main.CommandLineArgParse; import main.CommandLineArgParse.ArgOption; import main.CommandLineArgParse.OptionTypes; import skillTraceAnalysis.SkillTraceAnalysis; import supplementary.experiments.debugging.FindCrashingTrial; import supplementary.experiments.eval.EvalAgents; import supplementary.experiments.eval.EvalGames; import supplementary.experiments.eval.EvalGate; import supplementary.experiments.feature_importance.IdentifyTopFeatures; import supplementary.experiments.optim.EvolOptimHeuristics; import supplementary.experiments.scripts.GenerateBiasedMCTSEvalScripts; import supplementary.experiments.scripts.GenerateFeatureEvalScripts; import supplementary.experiments.scripts.GenerateGatingScripts; import supplementary.experiments.speed.PlayoutsPerSec; import test.instructionGeneration.TestInstructionGeneration; import training.expert_iteration.ExpertIteration; import utils.concepts.db.ExportDbCsvConcepts; import utils.features.ExportFeaturesDB; import utils.trials.GenerateTrialsCluster; import utils.trials.GenerateTrialsClusterParallel; /** * Class with helper method to delegate to various other main methods * based on command-line arguments. * * @author Dennis Soemers */ public class PlayerCLI { /** * @param args The first argument is expected to be a command * to run, with all subsequent arguments being passed onto * the called command. */ public static void runCommand(final String[] args) { final String[] commandArg = new String[]{args[0]}; final CommandLineArgParse argParse = new CommandLineArgParse ( true, "Run one of Ludii's command-line options, followed by the command's arguments.\n" + "Enter a command's name followed by \"-h\" or \"--help\" for " + "more information on the arguments for that particular command." ); argParse.addOption(new ArgOption() .help("Command to run. For more help, enter a command followed by \" --help\"") .setRequired() .withLegalVals ( "--time-playouts", "--expert-iteration", "--eval-agents", "--find-crashing-trial", "--eval-gate", "--eval-games", "--evol-optim-heuristics", "--ludeme-detection", "--generate-gating-scripts", "--export-features-db", "--export-moveconcept-db", "--generate-trials", "--generate-trials-parallel", "--tutorial-generation", "--game-distance", "--generate-feature-eval-scripts", // "--eval-ubfm", // "--learning-with-descent", "--generate-biased-mcts-eval-scripts", "--kilothon", "--identify-top-features", "--skill-trace-analysis" ) .withNumVals(1) .withType(OptionTypes.String)); // parse the args if (!argParse.parseArguments(commandArg)) return; final String command = argParse.getValueString(0); final String[] passArgs = Arrays.copyOfRange(args, 1, args.length); if (command.equalsIgnoreCase("--time-playouts")) PlayoutsPerSec.main(passArgs); else if (command.equalsIgnoreCase("--expert-iteration")) ExpertIteration.main(passArgs); else if (command.equalsIgnoreCase("--eval-agents")) EvalAgents.main(passArgs); else if (command.equalsIgnoreCase("--find-crashing-trial")) FindCrashingTrial.main(passArgs); else if (command.equalsIgnoreCase("--eval-gate")) EvalGate.main(passArgs); else if (command.equalsIgnoreCase("--eval-games")) EvalGames.main(passArgs); else if (command.equalsIgnoreCase("--evol-optim-heuristics")) EvolOptimHeuristics.main(passArgs); else if (command.equalsIgnoreCase("--ludeme-detection")) LudemeplexDetection.main(passArgs); else if (command.equalsIgnoreCase("--generate-gating-scripts")) GenerateGatingScripts.main(passArgs); else if (command.equalsIgnoreCase("--export-features-db")) ExportFeaturesDB.main(passArgs); else if (command.equalsIgnoreCase("--export-moveconcept-db")) ExportDbCsvConcepts.main(passArgs); else if (command.equalsIgnoreCase("--generate-trials")) GenerateTrialsCluster.main(passArgs); else if (command.equalsIgnoreCase("--generate-trials-parallel")) GenerateTrialsClusterParallel.main(passArgs); else if (command.equalsIgnoreCase("--tutorial-generation")) TestInstructionGeneration.main(passArgs); else if (command.equalsIgnoreCase("--game-distance")) CompareAllDistanceMetrics.main(passArgs); else if (command.equalsIgnoreCase("--generate-feature-eval-scripts")) GenerateFeatureEvalScripts.main(passArgs); else if (command.equalsIgnoreCase("--generate-biased-mcts-eval-scripts")) GenerateBiasedMCTSEvalScripts.main(passArgs); else if (command.equalsIgnoreCase("--kilothon")) Kilothon.main(passArgs); else if (command.equalsIgnoreCase("--identify-top-features")) IdentifyTopFeatures.main(passArgs); else if (command.equalsIgnoreCase("--skill-trace-analysis")) SkillTraceAnalysis.main(passArgs); // else if (command.equalsIgnoreCase("--eval-ubfm")) // EvaluateAllUBFMs.main(passArgs); // else if (command.equalsIgnoreCase("--learning-with-descent")) // { // HeuristicsTraining.main(passArgs); // EvaluateAllUBFMs.main(new String[] {passArgs[0], "eval heuristics"}); // } else System.err.println("ERROR: command not yet implemented: " + command); } }
5,404
36.020548
86
java
Ludii
Ludii-master/PlayerDesktop/src/app/StartDesktopApp.java
package app; /** * Main point of Entry for running the Ludii application. * * @author Matthew.Stephenson and Dennis Soemers */ public class StartDesktopApp { private static DesktopApp desktopApp = null; public static void main(final String[] args) { // The actual launching if (args.length == 0) { desktopApp = new DesktopApp(); desktopApp.createDesktopApp(); } else { PlayerCLI.runCommand(args); } } // Used in case any agents need DesktopApp functions. public static DesktopApp desktopApp() { return desktopApp; } }
559
17.064516
57
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/MainWindowDesktop.java
package app.display; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.JPanel; import javax.swing.Timer; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.MoveDialog.SandboxDialog; import app.display.util.DevTooltip; import app.display.util.ZoomBox; import app.display.views.OverlayView; import app.display.views.tabs.TabView; import app.loading.FileLoading; import app.move.MouseHandler; import app.utils.AnimationVisualsType; import app.utils.GUIUtil; import app.utils.MVCSetup; import app.utils.SettingsExhibition; import app.utils.sandbox.SandboxValueType; import app.views.BoardView; import app.views.View; import app.views.players.PlayerView; import app.views.tools.ToolView; import game.equipment.container.Container; import main.Constants; import other.context.Context; import other.location.Location; import other.topology.Cell; import other.topology.Edge; import other.topology.Vertex; import util.LocationUtil; //----------------------------------------------------------------------------- /** * Main Window for displaying the application * * @author Matthew.Stephenson and cambolbro and Eric.Piette */ public class MainWindowDesktop extends JPanel implements MouseListener, MouseMotionListener { final DesktopApp app; private static final long serialVersionUID = 1L; /** List of view panels, including all sub-panels of the main five. */ protected List<View> panels = new CopyOnWriteArrayList<>(); // The main five views that are always present in the window. /** View that covers the entire window. */ protected OverlayView overlayPanel; /** View that covers the left half of the window, where the board is drawn. */ protected BoardView boardPanel; /** View that covers the top right area of the window, where the player views are drawn. */ protected PlayerView playerPanel; /** View that covers the bottom right area of the window, where the tool buttons are drawn. */ protected ToolView toolPanel; /** View that covers the middle right area of the window, where the tab pages are drawn. */ protected TabView tabPanel; /** Width of the MainView. */ protected int width; /** Height of the MainView. */ protected int height; /** array of bounding rectangles for each player's swatch. */ public Rectangle[] playerSwatchList = new Rectangle[Constants.MAX_PLAYERS+1]; /** array of bounding rectangles for each player's name. */ public Rectangle[] playerNameList = new Rectangle[Constants.MAX_PLAYERS+1]; /** array of booleans for representing if the mouse cursor is over any player's swatch. */ public boolean[] playerSwatchHover = new boolean[Constants.MAX_PLAYERS+1]; /** array of booleans for representing if the mouse cursor is over any player's name. */ public boolean[] playerNameHover = new boolean[Constants.MAX_PLAYERS+1]; public static final int MIN_UI_FONT_SIZE = 12; public static final int MAX_UI_FONT_SIZE = 24; /** Temporary message to be printed at the bottom of the Window. */ private String temporaryMessage = ""; static String volatileMessage = ""; /** ZoomBox (magnifying glass) pane. */ public ZoomBox zoomBox; /** If we are currently painting the desktop frame. */ public boolean isPainting = false; // View page for MYOG app protected int page = 0; //------------------------------------------------------------------------- /** * Constructor. */ public MainWindowDesktop(final DesktopApp app) { addMouseListener(this); addMouseMotionListener(this); this.app = app; zoomBox = new ZoomBox(app, this); } //------------------------------------------------------------------------- /** * Create UI panels. */ public void createPanels() { MVCSetup.setMVC(app); panels.clear(); removeAll(); final boolean portraitMode = width < height; // Create board panel boardPanel = new BoardView(app, false); panels.add(boardPanel); // create the player panel playerPanel = new PlayerView(app, portraitMode, false); panels.add(playerPanel); // Create tool panel toolPanel = new ToolView(app, portraitMode); panels.add(toolPanel); // Create tab panel if (!app.settingsPlayer().isPerformingTutorialVisualisation()) { tabPanel = new TabView(app, portraitMode); panels.add(tabPanel); } // Create overlay panel overlayPanel = new OverlayView(app); panels.add(overlayPanel()); if (SettingsExhibition.exhibitionVersion) app.settingsPlayer().setAnimationType(AnimationVisualsType.Single); } //------------------------------------------------------------------------- @Override public void paintComponent(final Graphics g) { try { final Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (!app.bridge().settingsVC().thisFrameIsAnimated()) app.contextSnapshot().setContext(app); setDisplayFont(app); app.graphicsCache().allDrawnComponents().clear(); if (panels.isEmpty() || width != getWidth() || height != getHeight()) { width = getWidth(); height = getHeight(); createPanels(); } app.updateTabs(app.contextSnapshot().getContext(app)); // Set application background colour. if (app.settingsPlayer().usingMYOGApp()) g2d.setColor(Color.black); else if (SettingsExhibition.exhibitionVersion) g2d.setColor(Color.black); else g2d.setColor(Color.white); g2d.fillRect(0, 0, getWidth(), getHeight()); // Paint each panel for (final View panel : panels) if (g.getClipBounds().intersects(panel.placement())) panel.paint(g2d); // Report any errors that occurred. reportErrors(); // Delayed and invoked later to be sure the painting is complete. new java.util.Timer().schedule ( new java.util.TimerTask() { @Override public void run() { EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> { isPainting = false; }); }); } }, 500 ); } catch (final Exception e) { e.printStackTrace(); EventQueue.invokeLater(() -> { setTemporaryMessage("Error painting components."); FileLoading.writeErrorFile("error_report.txt", e); }); } } //------------------------------------------------------------------------- /** * Report any errors that occurred. */ private void reportErrors() { if (app.bridge().settingsVC().errorReport() != "") { app.addTextToStatusPanel(app.bridge().settingsVC().errorReport()); app.bridge().settingsVC().setErrorReport(""); } final metadata.graphics.Graphics graphics = app.contextSnapshot().getContext(app).game().metadata().graphics(); if (graphics.getErrorReport() != "") { app.addTextToStatusPanel(graphics.getErrorReport()); graphics.setErrorReport(""); } } //------------------------------------------------------------------------- /** * Check if the point pressed overlaps any "buttons" * (e.g. pass or swap buttons, player swatches or names, tool/tab views) * If activateButton is True, then the overlapped button is also pressed. */ protected boolean checkPointOverlapsButton(final MouseEvent e, final boolean pressButton) { if (GUIUtil.pointOverlapsRectangles(e.getPoint(), playerSwatchList)) { if (pressButton) app.showSettingsDialog(); return true; } else if (GUIUtil.pointOverlapsRectangles(e.getPoint(), playerNameList)) { if (pressButton) app.showSettingsDialog(); return true; } else if (tabPanel.placement().contains(e.getPoint())) { if (pressButton) tabPanel.clickAt(e.getPoint()); return true; } else if (toolPanel.placement().contains(e.getPoint())) { if (pressButton) toolPanel.clickAt(e.getPoint()); return true; } return false; } //------------------------------------------------------------------------- @Override public void mousePressed(final MouseEvent e) { if (!checkPointOverlapsButton(e, false)) MouseHandler.mousePressedCode(app, e.getPoint()); } //------------------------------------------------------------------------- @Override public void mouseReleased(final MouseEvent e) { // Important that this is delayed slightly, to take place after the mouseClicked function. EventQueue.invokeLater(() -> { if (!checkPointOverlapsButton(e, false)) MouseHandler.mouseReleasedCode(app, e.getPoint()); }); } //------------------------------------------------------------------------- @Override public void mouseClicked(final MouseEvent e) { checkPointOverlapsButton(e, true); if (app.settingsPlayer().sandboxMode()) { final Context context = app.contextSnapshot().getContext(app); final Location location = LocationUtil.calculateNearestLocation(context, app.bridge(), e.getPoint(), LocationUtil.getAllLocations(context, app.bridge())); SandboxDialog.createAndShowGUI(app, location, SandboxValueType.Component); } MouseHandler.mouseClickedCode(app, e.getPoint()); } //------------------------------------------------------------------------- @Override public void mouseDragged(final MouseEvent e) { MouseHandler.mouseDraggedCode(app, e.getPoint()); } //------------------------------------------------------------------------- @Override public void mouseMoved(final MouseEvent e) { for (final View view : panels) view.mouseOverAt(e.getPoint()); DevTooltip.displayToolTipMessage(app, e.getPoint()); } //------------------------------------------------------------------------- @Override public void mouseEntered(final MouseEvent e) { app.repaint(); } //------------------------------------------------------------------------- @Override public void mouseExited(final MouseEvent e) { app.repaint(); } //------------------------------------------------------------------------- /** * Set the display font based on the size of the graph elements across all containers. */ protected static void setDisplayFont(final PlayerApp app) { int maxDisplayNumber = 0; int minCellSize = 9999999; int maxCoordDigitLength = 0; for (final Container container : app.contextSnapshot().getContext(app).equipment().containers()) { final int maxVertices = container.topology().cells().size(); final int maxEdges = container.topology().edges().size(); final int maxFaces = container.topology().vertices().size(); maxDisplayNumber = Math.max(maxDisplayNumber, Math.max(maxVertices, Math.max(maxEdges, maxFaces))); minCellSize = Math.min(minCellSize, app.bridge().getContainerStyle(container.index()).cellRadiusPixels()); for (final Vertex vertex : container.topology().vertices()) if (vertex.label().length() > maxCoordDigitLength) maxCoordDigitLength = vertex.label().length(); for (final Edge edge : container.topology().edges()) if (edge.label().length() > maxCoordDigitLength) maxCoordDigitLength = edge.label().length(); for (final Cell cell : container.topology().cells()) if (cell.label().length() > maxCoordDigitLength) maxCoordDigitLength = cell.label().length(); } final int maxStringLength = Math.max(maxCoordDigitLength, Integer.toString(maxDisplayNumber).length()); int fontSize = (int)(minCellSize * (1.0 - maxStringLength * 0.1)); if (fontSize < MIN_UI_FONT_SIZE) fontSize = MIN_UI_FONT_SIZE; else if (fontSize > MAX_UI_FONT_SIZE) fontSize = MAX_UI_FONT_SIZE; app.bridge().settingsVC().setDisplayFont(new Font("Arial", Font.BOLD, fontSize)); } //------------------------------------------------------------------------- public BoardView getBoardPanel() { return boardPanel; } public PlayerView getPlayerPanel() { return playerPanel; } public List<View> getPanels() { return panels; } public TabView tabPanel() { return tabPanel; } public ToolView toolPanel() { return toolPanel; } public String temporaryMessage() { return temporaryMessage; } public static String volatileMessage() { return volatileMessage; } public void setTemporaryMessage(final String s) { if (s.length()==0) { temporaryMessage = ""; volatileMessage = ""; } else if (!temporaryMessage.contains(s)) { temporaryMessage += " " + s; } } public static void setVolatileMessage(final PlayerApp app, final String s) { volatileMessage = s; final Timer timer = new Timer(3000, new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { volatileMessage = ""; app.repaint(); } }); timer.setRepeats(false); timer.start(); } public OverlayView overlayPanel() { return overlayPanel; } //------------------------------------------------------------------------- public int width() { return width; } public int height() { return height; } public Rectangle[] playerSwatchList() { return playerSwatchList; } public Rectangle[] playerNameList() { return playerNameList; } public boolean[] playerSwatchHover() { return playerSwatchHover; } public boolean[] playerNameHover() { return playerNameHover; } }
14,197
26.25144
157
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/SVGWindow.java
package app.display; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; import main.Constants; //----------------------------------------------------------------------------- /** * SVG viewer. * * @author cambolbro */ public class SVGWindow extends JPanel { private static final long serialVersionUID = 1L; private final BufferedImage[] images = new BufferedImage[Constants.MAX_PLAYERS+1]; //------------------------------------------------------------------------- public void setImages(final BufferedImage img1, final BufferedImage img2) { images[1] = img1; images[2] = img2; } //------------------------------------------------------------------------- @Override public void paint(final Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); if (images[1] != null && images[2] != null) { g.drawImage(images[1], 10, 10, null); g.drawImage(images[2], 10 + images[1].getWidth() + 10, 10, null); } } //------------------------------------------------------------------------- }
1,128
21.58
83
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/AboutDialog.java
package app.display.dialogs; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import app.DesktopApp; import app.PlayerApp; import game.equipment.component.Component; import game.equipment.container.Container; import main.Constants; /** * Dialog for showing various information about Ludii and the current game. * * @author Matthew.Stephenson */ public class AboutDialog { //------------------------------------------------------------------------- /** * Show the About dialog. */ public static void showAboutDialog(final PlayerApp app) { final URL iconURL = DesktopApp.class.getResource("/all-logos-64.png"); final ImageIcon icon = new ImageIcon(iconURL); // Description final StringBuilder sbDescription = new StringBuilder(); sbDescription.append("Ludii General Game System"); // Version final StringBuilder sbVersion = new StringBuilder(); sbVersion.append(", version " + Constants.LUDEME_VERSION + " (" + Constants.DATE + ").\n\n"); // Legal final StringBuilder sbLegal = new StringBuilder(); //sbLegal.append("Cameron Browne (c) 2017-21.\n\n"); sbLegal.append("Ludii is an initiative by Cameron Browne 2017-2022.\n\n"); // Team final StringBuilder sbTeam = new StringBuilder(); sbTeam.append("Code: Cameron Browne, Eric Piette, Matthew Stephenson, \n" + "Dennis Soemers, Stephen Tavener, Markus Niebisch, \n" + "Tahmina Begum, Coen Hacking and Lianne Hufkens.\n\n"); sbTeam.append("Testing: Wijnand Engelkes\n\n"); sbTeam.append("Historical Advice: Walter Crist\n\n"); // Admin final StringBuilder sbAdmin = new StringBuilder(); sbAdmin.append("Developed as part of the Digital Ludeme Project \n" + "funded by ERC Consolidator Grant #771292 led by \n" + "Cameron Browne at Maastricht University.\n\n"); sbAdmin.append("The Ludii JAR is freely available for non-commercial use.\n\n"); final StringBuilder sbURLs = new StringBuilder(); sbURLs.append("http://ludii.games\n" + "http://ludeme.eu\n\n"); sbURLs.append("Ludii source code available at: https://github.com/Ludeme/Ludii\n\n"); // Credits final StringBuilder sbCredits = new StringBuilder(); final Map<Integer, String> creditMap = new HashMap<Integer, String>(); // Component credits for (final Component component : app.manager().ref().context().game().equipment().components()) if (component != null && component.credit() != null) { final Integer key = Integer.valueOf(component.getNameWithoutNumber().hashCode()); if (creditMap.get(key) == null) { sbCredits.append(component.credit() + "\n"); creditMap.put(key, "Found"); } } // Container credits for (final Container container : app.manager().ref().context().game().equipment().containers()) if (container != null && container.credit() != null) { final Integer key = Integer.valueOf(container.name().hashCode()); if (creditMap.get(key) == null) { sbCredits.append(container.credit() + "\n"); creditMap.put(key, "Found"); } } // Audio credits sbCredits.append("Pling audio file by KevanGC from http://soundbible.com/1645-Pling.html.\n"); JOptionPane.showMessageDialog ( DesktopApp.frame(), sbDescription.toString() + sbVersion.toString() + sbLegal.toString() + sbTeam.toString() + sbAdmin.toString() + sbURLs.toString() + sbCredits.toString(), DesktopApp.AppName, JOptionPane.PLAIN_MESSAGE, icon ); } }
3,525
30.20354
97
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/DeveloperDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.display.dialogs.util.JComboCheckBox; import game.types.board.SiteType; import game.util.directions.DirectionFacing; import gnu.trove.iterator.TIntIterator; import main.Constants; import other.topology.Topology; import other.topology.TopologyElement; /** * Dialog that is used to display various Developer options. * * @author Matthew.Stephenson and Eric.Piette */ public class DeveloperDialog extends JDialog { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** X coordinate of the cell column. */ private final int CELL_X = 27; /** X coordinate of the vertex column. */ private final int VERTEX_X = 228; /** X coordinate of the edge column. */ private final int EDGE_X = 440; /** Gap between two check boxes. */ private final int GAP = 26; /** The init of Y coordinate for the check boxes. */ private final int INIT_Y = 60; /** The size of the combo boxes. */ private final int SIZE_COMBO_BOXES = 100; /** The indices of the pregeneration boxes according to its name. */ private final Map<String, Integer> indexPregen = new HashMap<String, Integer>(); //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void showDialog(final PlayerApp app) { try { final DeveloperDialog dialog = new DeveloperDialog(app); DialogUtil.initialiseSingletonDialog(dialog, "Developer Settings", null); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Init the map of the indices of the pregen. */ public void initMapIndexPregen() { indexPregen.put("Inner", Integer.valueOf(0)); indexPregen.put("Outer", Integer.valueOf(1)); indexPregen.put("Perimeter", Integer.valueOf(2)); indexPregen.put("Center", Integer.valueOf(3)); indexPregen.put("Major", Integer.valueOf(4)); indexPregen.put("Minor", Integer.valueOf(5)); indexPregen.put("Corners", Integer.valueOf(7)); indexPregen.put("Corners Concave", Integer.valueOf(8)); indexPregen.put("Corners Convex", Integer.valueOf(9)); indexPregen.put("Top", Integer.valueOf(11)); indexPregen.put("Bottom", Integer.valueOf(12)); indexPregen.put("Left", Integer.valueOf(13)); indexPregen.put("Right", Integer.valueOf(14)); indexPregen.put("Phases", Integer.valueOf(16)); indexPregen.put("Side", Integer.valueOf(18)); indexPregen.put("Col", Integer.valueOf(20)); indexPregen.put("Row", Integer.valueOf(21)); indexPregen.put("Neighbours", Integer.valueOf(23)); indexPregen.put("Radials", Integer.valueOf(24)); indexPregen.put("Distance", Integer.valueOf(25)); indexPregen.put("Axial", Integer.valueOf(20)); indexPregen.put("Horizontal", Integer.valueOf(21)); indexPregen.put("Vertical", Integer.valueOf(22)); indexPregen.put("Angled", Integer.valueOf(23)); indexPregen.put("Slash", Integer.valueOf(24)); indexPregen.put("Slosh", Integer.valueOf(25)); } //------------------------------------------------------------------------------------------------------ /** * Create the dialog. */ public DeveloperDialog(final PlayerApp app) { initMapIndexPregen(); setBounds(100, 100, 1200, indexPregen.values().size() * (int) (GAP * 1.2)); getContentPane().setLayout(new BorderLayout()); final JPanel contentPanel = new JPanel(); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); final JLabel lblNewLabel = new JLabel("Pregeneration visuals"); lblNewLabel.setBounds(27, 11, 331, 15); contentPanel.add(lblNewLabel); final Topology topology = app.contextSnapshot().getContext(app).board().topology(); makeColumnCell(app, contentPanel, topology); makeColumnVertex(app, contentPanel, topology); makeColumnEdge(app, contentPanel, topology); makeColumnOther(app, contentPanel, topology); } //----------------------------------------------------------------------------------------- /** * Make the column of the cells. */ public void makeColumnCell(final PlayerApp app, final JPanel contentPanel, final Topology topology) { final JLabel label = new JLabel("Cells"); label.setBounds(37, 37, 104, 15); contentPanel.add(label); final JCheckBox checkBox_Corners = checkBox(contentPanel, CELL_X, INIT_Y, "Corners", app.bridge().settingsVC().drawCornerCells()); checkBox_Corners.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerCells(checkBox_Corners.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Concave = checkBox(contentPanel, CELL_X, INIT_Y, "Corners Concave", app.bridge().settingsVC().drawCornerConcaveCells()); checkBox_Corners_Concave.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConcaveCells(checkBox_Corners_Concave.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Convex = checkBox(contentPanel, CELL_X, INIT_Y, "Corners Convex", app.bridge().settingsVC().drawCornerConvexCells()); checkBox_Corners_Convex.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConvexCells(checkBox_Corners_Convex.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Major = checkBox(contentPanel, CELL_X, INIT_Y, "Major", app.bridge().settingsVC().drawMajorCells()); checkBox_Major.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMajorCells(checkBox_Major.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Minor = checkBox(contentPanel, CELL_X, INIT_Y, "Minor", app.bridge().settingsVC().drawMinorCells()); checkBox_Minor.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMinorCells(checkBox_Minor.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Perimeter = checkBox(contentPanel, CELL_X, INIT_Y, "Perimeter", app.bridge().settingsVC().drawPerimeterCells()); checkBox_Perimeter.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPerimeterCells(checkBox_Perimeter.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Outer = checkBox(contentPanel, CELL_X, INIT_Y, "Outer", app.bridge().settingsVC().drawOuterCells()); checkBox_Outer.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawOuterCells(checkBox_Outer.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Inner = checkBox(contentPanel, CELL_X, INIT_Y, "Inner", app.bridge().settingsVC().drawInnerCells()); checkBox_Inner.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawInnerCells(checkBox_Inner.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Top = checkBox(contentPanel, CELL_X, INIT_Y, "Top", app.bridge().settingsVC().drawTopCells()); checkBox_Top.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawTopCells(checkBox_Top.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Bottom = checkBox(contentPanel, CELL_X, INIT_Y, "Bottom", app.bridge().settingsVC().drawBottomCells()); checkBox_Bottom.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawBottomCells(checkBox_Bottom.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Left = checkBox(contentPanel, CELL_X, INIT_Y, "Left", app.bridge().settingsVC().drawLeftCells()); checkBox_Left.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawLeftCells(checkBox_Left.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Right = checkBox(contentPanel, CELL_X, INIT_Y, "Right", app.bridge().settingsVC().drawRightCells()); checkBox_Right.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawRightCells(checkBox_Right.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Center = checkBox(contentPanel, CELL_X, INIT_Y, "Center", app.bridge().settingsVC().drawCenterCells()); checkBox_Center.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCenterCells(checkBox_Center.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Phases = checkBox(contentPanel, CELL_X, INIT_Y, "Phases", app.bridge().settingsVC().drawPhasesCells()); checkBox_Phases.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPhasesCells(checkBox_Phases.isSelected()); app.repaint(); } }); final JComboCheckBox comboCheckBox_Column = comboCheckBox(contentPanel, CELL_X, INIT_Y, "Col", app.bridge().settingsVC().drawColumnsCells(), topology.columns(SiteType.Cell)); if (comboCheckBox_Column != null) { comboCheckBox_Column.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < comboCheckBox_Column.getItemCount(); i++) { app.bridge().settingsVC().drawColumnsCells().set(i, Boolean.valueOf(((JCheckBox) comboCheckBox_Column.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); } final JComboCheckBox comboCheckBox_Row = comboCheckBox(contentPanel, CELL_X, INIT_Y, "Row", app.bridge().settingsVC().drawRowsCells(), topology.rows(SiteType.Cell)); if (comboCheckBox_Row != null) { comboCheckBox_Row.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < comboCheckBox_Row.getItemCount(); i++) { app.bridge().settingsVC().drawRowsCells().set(i, Boolean.valueOf(((JCheckBox) comboCheckBox_Row.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); } if (topology.sides(SiteType.Cell).size() > 0) { final Vector<JCheckBox> v = new Vector<JCheckBox>(); for (final DirectionFacing d : topology.sides(SiteType.Cell).keySet()) { app.bridge().settingsVC().drawSideCells().put(d.uniqueName().toString(), Boolean.valueOf(false)); final JCheckBox tempCheckBox = new JCheckBox(d.uniqueName().toString(), false); tempCheckBox.setSelected(app.bridge().settingsVC().drawSideCells().get(d.uniqueName().toString()).booleanValue()); v.add(tempCheckBox); } final JComboCheckBox directionLimitOptions = new JComboCheckBox(v); directionLimitOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < directionLimitOptions.getItemCount(); i++) { app.bridge().settingsVC().drawSideCells().put(((JCheckBox) directionLimitOptions.getItemAt(i)).getText(), Boolean.valueOf(((JCheckBox) directionLimitOptions.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); directionLimitOptions.setBounds(CELL_X, INIT_Y + GAP * indexPregen.get("Side").intValue(), SIZE_COMBO_BOXES, 23); contentPanel.add(directionLimitOptions); } final JCheckBox checkBox_Neighbours = checkBox(contentPanel, CELL_X, INIT_Y, "Neighbours", app.bridge().settingsVC().drawNeighboursCells()); checkBox_Neighbours.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawNeighboursCells(checkBox_Neighbours.isSelected()); } }); final JCheckBox checkBox_Radials = checkBox(contentPanel, CELL_X, INIT_Y, "Radials", app.bridge().settingsVC().drawRadialsCells()); checkBox_Radials.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawRadialsCells(checkBox_Radials.isSelected()); } }); final JCheckBox checkBox_Distance = checkBox(contentPanel, CELL_X, INIT_Y, "Distance", app.bridge().settingsVC().drawDistanceCells()); checkBox_Distance.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawDistanceCells(checkBox_Distance.isSelected()); } }); } //----------------------------------------------------------------------------------------- /** * Make the column of the vertices. */ public void makeColumnVertex(final PlayerApp app, final JPanel contentPanel, final Topology topology) { final JLabel label = new JLabel("Vertices"); label.setBounds(249, 37, 104, 15); contentPanel.add(label); final JCheckBox checkBox_Corners = checkBox(contentPanel, VERTEX_X, INIT_Y, "Corners", app.bridge().settingsVC().drawCornerVertices()); checkBox_Corners.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerVertices(checkBox_Corners.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Concave = checkBox(contentPanel, VERTEX_X, INIT_Y, "Corners Concave", app.bridge().settingsVC().drawCornerConcaveVertices()); checkBox_Corners_Concave.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConcaveVertices(checkBox_Corners_Concave.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Convex = checkBox(contentPanel, VERTEX_X, INIT_Y, "Corners Convex", app.bridge().settingsVC().drawCornerConvexVertices()); checkBox_Corners_Convex.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConvexVertices(checkBox_Corners_Convex.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Major = checkBox(contentPanel, VERTEX_X, INIT_Y, "Major", app.bridge().settingsVC().drawMajorVertices()); checkBox_Major.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMajorVertices(checkBox_Major.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Minor = checkBox(contentPanel, VERTEX_X, INIT_Y, "Minor", app.bridge().settingsVC().drawMinorVertices()); checkBox_Minor.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMinorVertices(checkBox_Minor.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Perimeter = checkBox(contentPanel, VERTEX_X, INIT_Y, "Perimeter", app.bridge().settingsVC().drawPerimeterVertices()); checkBox_Perimeter.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPerimeterVertices(checkBox_Perimeter.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Outer = checkBox(contentPanel, VERTEX_X, INIT_Y, "Outer", app.bridge().settingsVC().drawOuterVertices()); checkBox_Outer.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawOuterVertices(checkBox_Outer.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Inner = checkBox(contentPanel, VERTEX_X, INIT_Y, "Inner", app.bridge().settingsVC().drawInnerVertices()); checkBox_Inner.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawInnerVertices(checkBox_Inner.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Top = checkBox(contentPanel, VERTEX_X, INIT_Y, "Top", app.bridge().settingsVC().drawTopVertices()); checkBox_Top.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawTopVertices(checkBox_Top.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Bottom = checkBox(contentPanel, VERTEX_X, INIT_Y, "Bottom", app.bridge().settingsVC().drawBottomVertices()); checkBox_Bottom.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawBottomVertices(checkBox_Bottom.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Left = checkBox(contentPanel, VERTEX_X, INIT_Y, "Left", app.bridge().settingsVC().drawLeftVertices()); checkBox_Left.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawLeftVertices(checkBox_Left.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Right = checkBox(contentPanel, VERTEX_X, INIT_Y, "Right", app.bridge().settingsVC().drawRightVertices()); checkBox_Right.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawRightVertices(checkBox_Right.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Center = checkBox(contentPanel, VERTEX_X, INIT_Y, "Center", app.bridge().settingsVC().drawCenterVertices()); checkBox_Center.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCenterVertices( checkBox_Center.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Phases = checkBox(contentPanel, VERTEX_X, INIT_Y, "Phases", app.bridge().settingsVC().drawPhasesVertices()); checkBox_Phases.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPhasesVertices(checkBox_Phases.isSelected()); app.repaint(); } }); final JComboCheckBox comboCheckBox_Column = comboCheckBox(contentPanel, VERTEX_X, INIT_Y, "Col", app.bridge().settingsVC().drawColumnsVertices(), topology.columns(SiteType.Vertex)); if (comboCheckBox_Column != null) { comboCheckBox_Column.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < comboCheckBox_Column.getItemCount(); i++) { app.bridge().settingsVC().drawColumnsVertices().set(i, Boolean.valueOf(((JCheckBox) comboCheckBox_Column.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); } final JComboCheckBox comboCheckBox_Row = comboCheckBox(contentPanel, VERTEX_X, INIT_Y, "Row", app.bridge().settingsVC().drawRowsVertices(), topology.rows(SiteType.Vertex)); if (comboCheckBox_Row != null) { comboCheckBox_Row.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < comboCheckBox_Row.getItemCount(); i++) { app.bridge().settingsVC().drawRowsVertices().set(i, Boolean.valueOf(((JCheckBox) comboCheckBox_Row.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); } if (topology.sides(SiteType.Vertex).size() > 0) { final Vector<JCheckBox> v = new Vector<JCheckBox>(); for (final DirectionFacing d : topology.sides(SiteType.Vertex).keySet()) { app.bridge().settingsVC().drawSideVertices().put(d.uniqueName().toString(), Boolean.valueOf(false)); final JCheckBox tempCheckBox = new JCheckBox(d.uniqueName().toString(), false); tempCheckBox.setSelected( app.bridge().settingsVC().drawSideVertices().get(d.uniqueName().toString()).booleanValue()); v.add(tempCheckBox); } final JComboCheckBox directionLimitOptions = new JComboCheckBox(v); directionLimitOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < directionLimitOptions.getItemCount(); i++) { app.bridge().settingsVC().drawSideVertices().put( ((JCheckBox) directionLimitOptions.getItemAt(i)).getText(), Boolean.valueOf(((JCheckBox) directionLimitOptions.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); directionLimitOptions.setBounds(VERTEX_X, INIT_Y + GAP * indexPregen.get("Side").intValue(), SIZE_COMBO_BOXES, 23); contentPanel.add(directionLimitOptions); } final JCheckBox checkBox_Neighbours = checkBox(contentPanel, VERTEX_X, INIT_Y, "Neighbours", app.bridge().settingsVC().drawNeighboursVertices()); checkBox_Neighbours.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawNeighboursVertices(checkBox_Neighbours.isSelected()); } }); final JCheckBox checkBox_Radials = checkBox(contentPanel, VERTEX_X, INIT_Y, "Radials", app.bridge().settingsVC().drawRadialsVertices()); checkBox_Radials.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawRadialsVertices(checkBox_Radials.isSelected()); } }); final JCheckBox checkBox_Distance = checkBox(contentPanel, VERTEX_X, INIT_Y, "Distance", app.bridge().settingsVC().drawDistanceVertices()); checkBox_Distance.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawDistanceVertices(checkBox_Distance.isSelected()); } }); } //----------------------------------------------------------------------------------------- /** * Make the column of the edges. */ public void makeColumnEdge(final PlayerApp app, final JPanel contentPanel, final Topology topology) { final JLabel label = new JLabel("Edges"); label.setBounds(461, 37, 104, 15); contentPanel.add(label); final JCheckBox checkBox_Corners = checkBox(contentPanel, EDGE_X, INIT_Y, "Corners", app.bridge().settingsVC().drawCornerEdges()); checkBox_Corners.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerEdges(checkBox_Corners.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Concave = checkBox(contentPanel, EDGE_X, INIT_Y, "Corners Concave", app.bridge().settingsVC().drawCornerConcaveEdges()); checkBox_Corners_Concave.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConcaveEdges(checkBox_Corners_Concave.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Corners_Convex = checkBox(contentPanel, EDGE_X, INIT_Y, "Corners Convex", app.bridge().settingsVC().drawCornerConvexEdges()); checkBox_Corners_Convex.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCornerConvexEdges(checkBox_Corners_Convex.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Major = checkBox(contentPanel, EDGE_X, INIT_Y, "Major", app.bridge().settingsVC().drawMajorEdges()); checkBox_Major.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMajorEdges(checkBox_Major.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Minor = checkBox(contentPanel, EDGE_X, INIT_Y, "Minor", app.bridge().settingsVC().drawMinorEdges()); checkBox_Minor.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawMinorEdges(checkBox_Minor.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Perimeter = checkBox(contentPanel, EDGE_X, INIT_Y, "Perimeter", app.bridge().settingsVC().drawPerimeterEdges()); checkBox_Perimeter.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPerimeterEdges(checkBox_Perimeter.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Outer = checkBox(contentPanel, EDGE_X, INIT_Y, "Outer", app.bridge().settingsVC().drawOuterEdges()); checkBox_Outer.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawOuterEdges(checkBox_Outer.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Inner = checkBox(contentPanel, EDGE_X, INIT_Y, "Inner", app.bridge().settingsVC().drawInnerEdges()); checkBox_Inner.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawInnerEdges(checkBox_Inner.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Top = checkBox(contentPanel, EDGE_X, INIT_Y, "Top", app.bridge().settingsVC().drawTopEdges()); checkBox_Top.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawTopEdges(checkBox_Top.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Bottom = checkBox(contentPanel, EDGE_X, INIT_Y, "Bottom", app.bridge().settingsVC().drawBottomEdges()); checkBox_Bottom.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawBottomEdges(checkBox_Bottom.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Left = checkBox(contentPanel, EDGE_X, INIT_Y, "Left", app.bridge().settingsVC().drawLeftEdges()); checkBox_Left.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawLeftEdges(checkBox_Left.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Right = checkBox(contentPanel, EDGE_X, INIT_Y, "Right", app.bridge().settingsVC().drawRightEdges()); checkBox_Right.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawRightEdges(checkBox_Right.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Center = checkBox(contentPanel, EDGE_X, INIT_Y, "Center", app.bridge().settingsVC().drawCentreEdges()); checkBox_Center.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawCentreEdges(checkBox_Center.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Phases = checkBox(contentPanel, EDGE_X, INIT_Y, "Phases", app.bridge().settingsVC().drawPhasesEdges()); checkBox_Phases.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawPhasesEdges(checkBox_Phases.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Axial = checkBox(contentPanel, EDGE_X, INIT_Y, "Axial", app.bridge().settingsVC().drawAxialEdges()); checkBox_Axial.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawAxialEdges(checkBox_Axial.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Horizontal = checkBox(contentPanel, EDGE_X, INIT_Y, "Horizontal", app.bridge().settingsVC().drawHorizontalEdges()); checkBox_Horizontal.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawHorizontalEdges(checkBox_Horizontal.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Vertical = checkBox(contentPanel, EDGE_X, INIT_Y, "Vertical", app.bridge().settingsVC().drawVerticalEdges()); checkBox_Vertical.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawVerticalEdges(checkBox_Vertical.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Angled = checkBox(contentPanel, EDGE_X, INIT_Y, "Angled", app.bridge().settingsVC().drawAngledEdges()); checkBox_Angled.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawAngledEdges(checkBox_Angled.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Slash = checkBox(contentPanel, EDGE_X, INIT_Y, "Slash", app.bridge().settingsVC().drawSlashEdges()); checkBox_Slash.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawSlashEdges(checkBox_Slash.isSelected()); app.repaint(); } }); final JCheckBox checkBox_Slosh = checkBox(contentPanel, EDGE_X, INIT_Y, "Slosh", app.bridge().settingsVC().drawSloshEdges()); checkBox_Slosh.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawSloshEdges(checkBox_Slosh.isSelected()); app.repaint(); } }); if (topology.sides(SiteType.Edge).size() > 0) { final Vector<JCheckBox> v = new Vector<JCheckBox>(); for (final DirectionFacing d : topology.sides(SiteType.Edge).keySet()) { app.bridge().settingsVC().drawSideEdges().put(d.uniqueName().toString(), Boolean.valueOf(false)); final JCheckBox tempCheckBox = new JCheckBox(d.uniqueName().toString(), false); tempCheckBox .setSelected(app.bridge().settingsVC().drawSideEdges().get(d.uniqueName().toString()).booleanValue()); v.add(tempCheckBox); } final JComboCheckBox directionLimitOptions = new JComboCheckBox(v); directionLimitOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { for (int i = 0; i < directionLimitOptions.getItemCount(); i++) { app.bridge().settingsVC().drawSideEdges().put( ((JCheckBox) directionLimitOptions.getItemAt(i)).getText(), Boolean.valueOf(((JCheckBox) directionLimitOptions.getItemAt(i)).isSelected())); } app.repaint(); } }); } }); directionLimitOptions.setBounds(EDGE_X, INIT_Y + GAP * indexPregen.get("Side").intValue(), SIZE_COMBO_BOXES, 23); contentPanel.add(directionLimitOptions); } } //------------------------------------------------------------------------------------------------------- /** * Make the column to the right in the panel. TO REWRITE, NOT DONE FOR NOW. * * @param contentPanel * @param topology */ private static void makeColumnOther(final PlayerApp app, final JPanel contentPanel, final Topology topology) { final JTextField textFieldMaximumNumberOfTurns = new JTextField(); textFieldMaximumNumberOfTurns.setColumns(10); textFieldMaximumNumberOfTurns.setBounds(970, 495, 86, 20); contentPanel.add(textFieldMaximumNumberOfTurns); textFieldMaximumNumberOfTurns.setText("" + app.contextSnapshot().getContext(app).game().getMaxMoveLimit()); final JLabel lblNewLabel_1 = new JLabel("Maximum number of moves"); lblNewLabel_1.setBounds(719, 498, 241, 14); contentPanel.add(lblNewLabel_1); final DocumentListener documentListenerMaxTurns = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void insertUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void removeUpdate(final DocumentEvent documentEvent) { update(documentEvent); } private void update(final DocumentEvent documentEvent) { try { app.contextSnapshot().getContext(app).game() .setMaxMoveLimit(Integer.parseInt(textFieldMaximumNumberOfTurns.getText())); } catch (final Exception e) { // not an integer; app.contextSnapshot().getContext(app).game().setMaxMoveLimit(Constants.DEFAULT_MOVES_LIMIT); } app.repaint(); } }; textFieldMaximumNumberOfTurns.getDocument().addDocumentListener(documentListenerMaxTurns); final JCheckBox chckbxFacesofvertex = new JCheckBox("Faces of Vertices"); chckbxFacesofvertex.setSelected(app.bridge().settingsVC().drawFacesOfVertices()); chckbxFacesofvertex.setBounds(707, 60, 199, 23); contentPanel.add(chckbxFacesofvertex); chckbxFacesofvertex.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawFacesOfVertices(chckbxFacesofvertex.isSelected()); app.repaint(); } }); final JCheckBox chckbxEdgesOfVertices = new JCheckBox("Edges of Vertices"); chckbxEdgesOfVertices.setSelected(app.bridge().settingsVC().drawEdgesOfVertices()); chckbxEdgesOfVertices.setBounds(707, 86, 199, 23); contentPanel.add(chckbxEdgesOfVertices); chckbxEdgesOfVertices.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawEdgesOfVertices(chckbxEdgesOfVertices.isSelected()); app.repaint(); } }); final JCheckBox chckbxVerticesOfFaces = new JCheckBox("Vertices of Faces"); chckbxVerticesOfFaces.setSelected(app.bridge().settingsVC().drawVerticesOfFaces()); chckbxVerticesOfFaces.setBounds(707, 112, 199, 23); contentPanel.add(chckbxVerticesOfFaces); chckbxVerticesOfFaces.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawVerticesOfFaces(chckbxVerticesOfFaces.isSelected()); app.repaint(); } }); final JCheckBox chckbxEdgesOfFaces = new JCheckBox("Edges of Faces"); chckbxEdgesOfFaces.setSelected(app.bridge().settingsVC().drawEdgesOfFaces()); chckbxEdgesOfFaces.setBounds(707, 138, 199, 23); contentPanel.add(chckbxEdgesOfFaces); chckbxEdgesOfFaces.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawEdgesOfFaces(chckbxEdgesOfFaces.isSelected()); app.repaint(); } }); final JCheckBox chckbxVerticesOfEdges = new JCheckBox("Vertices of Edges"); chckbxVerticesOfEdges.setSelected(app.bridge().settingsVC().drawVerticesOfEdges()); chckbxVerticesOfEdges.setBounds(707, 165, 199, 23); contentPanel.add(chckbxVerticesOfEdges); chckbxVerticesOfEdges.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawVerticesOfEdges(chckbxVerticesOfEdges.isSelected()); app.repaint(); } }); final JCheckBox chckbxFacesOfEdges = new JCheckBox("Faces of Edges"); chckbxFacesOfEdges.setSelected(app.bridge().settingsVC().drawFacesOfEdges()); chckbxFacesOfEdges.setBounds(707, 191, 199, 23); contentPanel.add(chckbxFacesOfEdges); chckbxFacesOfEdges.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setDrawFacesOfEdges(chckbxFacesOfEdges.isSelected()); app.repaint(); } }); final JLabel lblPendingValue = new JLabel(); lblPendingValue.setBounds(719, 546, 241, 15); contentPanel.add(lblPendingValue); String allPendingValues = ""; if (app.manager().ref().context().state().pendingValues() != null) { final TIntIterator it = app.manager().ref().context().state().pendingValues().iterator(); while (it.hasNext()) { allPendingValues += Integer.valueOf(it.next()) + ", "; } } lblPendingValue.setText("Pending Values: " + allPendingValues); final JLabel lblCounterValue = new JLabel(); lblCounterValue.setBounds(719, 584, 241, 15); contentPanel.add(lblCounterValue); lblCounterValue.setText("Counter Value: " + app.manager().ref().context().state().counter()); final JLabel lblRememberValue = new JLabel(); lblRememberValue.setBounds(719, 624, 241, 15); contentPanel.add(lblRememberValue); lblRememberValue.setText("Remember Values: " + app.manager().ref().context().state().rememberingValues()); final JLabel lblTempValue = new JLabel(); lblTempValue.setBounds(719, 664, 241, 15); contentPanel.add(lblTempValue); lblTempValue.setText("Temp Value: " + app.manager().ref().context().state().temp()); } //------------------------------------------------------------------------------------------------------ /** * @return A check box on the correct position. */ public JCheckBox checkBox ( final JPanel contentPanel, final int x, final int init_y, final String namePregen, final boolean settingSelected ) { final JCheckBox checkBox = new JCheckBox(namePregen); checkBox.setBounds(x, init_y + indexPregen.get(namePregen).intValue() * GAP, 199, 23); contentPanel.add(checkBox); checkBox.setSelected(settingSelected); return checkBox; } /** * @return A combo check box on the correct position. */ public JComboCheckBox comboCheckBox ( final JPanel contentPanel, final int x, final int init_y, final String namePregen, final ArrayList<Boolean> settingSelected, final List<List<TopologyElement>> graphElements ) { JComboCheckBox comboCheckBox = null; if (graphElements.size() > 0) { final Vector<JCheckBox> v = new Vector<JCheckBox>(); for (int i = 0; i < graphElements.size(); i++) { if (settingSelected.size() <= i) { settingSelected.add(Boolean.valueOf(false)); } final JCheckBox tempCheckBox = new JCheckBox(namePregen + " " + i, false); tempCheckBox.setSelected(settingSelected.get(i).booleanValue()); v.add(tempCheckBox); } comboCheckBox = new JComboCheckBox(v); comboCheckBox.setBounds(x, init_y + GAP * indexPregen.get(namePregen).intValue(), SIZE_COMBO_BOXES, 23); contentPanel.add(comboCheckBox); } return comboCheckBox; } }
41,039
31.188235
194
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/EvaluationDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import analysis.Complexity; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.display.util.DesktopGUIUtil; import app.display.views.tabs.TabView; import app.loading.FileLoading; import app.utils.AIPlayer; import app.utils.ReportMessengerGUI; import gnu.trove.map.hash.TObjectDoubleHashMap; import main.grammar.Report; import metrics.Evaluation; import metrics.Metric; import metrics.designer.IdealDuration; import metrics.designer.SkillTrace; /** * Dialog that is used to display various game evaluation options * * @author Matthew.Stephenson */ public class EvaluationDialog extends JDialog { private static final long serialVersionUID = 1L; final JTextField textFieldThinkTime; final JTextField textFieldMinIdealTurns; final JTextField textFieldMaxIdealTurns; final JTextField textFieldNumMatches; final JTextField textFieldNumTrialsPerMatch; final JTextField textFieldHardTimeLimit; final JTextField txtcommonresoutput; //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void showDialog(final PlayerApp app) { try { final EvaluationDialog dialog = new EvaluationDialog(app); DialogUtil.initialiseSingletonDialog(dialog, "Game Evaluation", null); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ @SuppressWarnings("serial") public EvaluationDialog(final PlayerApp app) { final List<Metric> metrics = new Evaluation().dialogMetrics(); final ArrayList<Double> weights = new ArrayList<>(); final JButton okButton; setBounds(100, 100, 780, DesktopApp.frame().getHeight()); getContentPane().setLayout(new BorderLayout()); final JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(new BorderLayout(0, 0)); final JPanel LeftPanel = new JPanel(); panel.add(LeftPanel, BorderLayout.WEST); LeftPanel.setPreferredSize(new Dimension(460,500)); //LeftPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); LeftPanel.setLayout(null); final JLabel lblNewLabel = new JLabel("Number of Trials"); lblNewLabel.setBounds(26, 41, 145, 15); LeftPanel.add(lblNewLabel); final JTextField textFieldNumberTrials = new JTextField(); textFieldNumberTrials.setBounds(280, 39, 102, 19); textFieldNumberTrials.setText("10"); LeftPanel.add(textFieldNumberTrials); textFieldNumberTrials.setColumns(10); final JLabel lblAiModes = new JLabel("AI Agents"); lblAiModes.setBounds(26, 169, 91, 15); LeftPanel.add(lblAiModes); final JComboBox<String> comboBoxAIAgents = new JComboBox<String>(); comboBoxAIAgents.addItem("Random"); comboBoxAIAgents.addItem("Very weak AI"); comboBoxAIAgents.addItem("Weak AI"); comboBoxAIAgents.addItem("Strong AI"); comboBoxAIAgents.addItem("Very strong AI"); comboBoxAIAgents.addItem("Custom"); comboBoxAIAgents.setBounds(220, 164, 162, 24); comboBoxAIAgents.setEnabled(true); LeftPanel.add(comboBoxAIAgents); final JLabel labelMaxTurns = new JLabel("Maximum # Turns (per player)"); labelMaxTurns.setBounds(26, 72, 175, 15); LeftPanel.add(labelMaxTurns); final JTextField textFieldMaxTurns = new JTextField(); textFieldMaxTurns.setBounds(280, 70, 102, 19); textFieldMaxTurns.setText("50"); textFieldMaxTurns.setColumns(10); LeftPanel.add(textFieldMaxTurns); final JSeparator separator = new JSeparator(); separator.setOrientation(SwingConstants.VERTICAL); separator.setBounds(430, 0, 8, 4500); LeftPanel.add(separator); final JLabel labelThinkTime = new JLabel("Agent Think Time"); labelThinkTime.setBounds(26, 252, 175, 15); LeftPanel.add(labelThinkTime); textFieldThinkTime = new JTextField(); textFieldThinkTime.setEnabled(false); textFieldThinkTime.setText("0.5"); textFieldThinkTime.setColumns(10); textFieldThinkTime.setBounds(220, 250, 162, 19); LeftPanel.add(textFieldThinkTime); final JLabel lblAiAlgorithm = new JLabel("AI Algorithm"); lblAiAlgorithm.setBounds(26, 212, 91, 15); LeftPanel.add(lblAiAlgorithm); final String[] comboBoxContents = DesktopGUIUtil.getAIDropdownStrings(app, false).toArray(new String[DesktopGUIUtil.getAIDropdownStrings(app, false).size()]); final JComboBox<String> comboBoxAlgorithm = new JComboBox<String>(comboBoxContents); //comboBoxContents comboBoxAlgorithm.setEnabled(false); comboBoxAlgorithm.setBounds(220, 207, 162, 24); LeftPanel.add(comboBoxAlgorithm); final JLabel lblIdealTurnNumber = new JLabel("Ideal Turn Range"); lblIdealTurnNumber.setBounds(26, 331, 175, 15); LeftPanel.add(lblIdealTurnNumber); final JLabel lblMinimum = new JLabel("Minimum"); lblMinimum.setBounds(26, 357, 175, 15); LeftPanel.add(lblMinimum); final JLabel lblMaximum = new JLabel("Maximum"); lblMaximum.setBounds(26, 383, 175, 15); LeftPanel.add(lblMaximum); textFieldMinIdealTurns = new JTextField(); textFieldMinIdealTurns.setText("0"); textFieldMinIdealTurns.setColumns(10); textFieldMinIdealTurns.setBounds(220, 354, 162, 19); LeftPanel.add(textFieldMinIdealTurns); textFieldMaxIdealTurns = new JTextField(); textFieldMaxIdealTurns.setText("1000"); textFieldMaxIdealTurns.setColumns(10); textFieldMaxIdealTurns.setBounds(220, 380, 162, 19); LeftPanel.add(textFieldMaxIdealTurns); final JLabel lblSkillTrace = new JLabel("Skill Trace"); lblSkillTrace.setBounds(26, 435, 175, 15); LeftPanel.add(lblSkillTrace); final JLabel lblDirectory = new JLabel("Output Folder"); lblDirectory.setBounds(26, 461, 175, 15); LeftPanel.add(lblDirectory); final JLabel lblNumMatches = new JLabel("Maximum Levels"); lblNumMatches.setBounds(26, 487, 175, 15); LeftPanel.add(lblNumMatches); final JLabel lblTrailsPerMatch = new JLabel("Trials Per Level"); lblTrailsPerMatch.setBounds(26, 513, 175, 15); LeftPanel.add(lblTrailsPerMatch); final JLabel lblHardTimeLimit = new JLabel("Maximum Time(s)"); lblHardTimeLimit.setBounds(26, 539, 175, 15); LeftPanel.add(lblHardTimeLimit); final JButton skillTraceButton = new JButton("Run Skill Trace Only"); skillTraceButton.setBounds(180, 565, 202, 23); LeftPanel.add(skillTraceButton); textFieldNumMatches = new JTextField(); textFieldNumMatches.setText("8"); textFieldNumMatches.setColumns(10); textFieldNumMatches.setBounds(220, 484, 162, 19); LeftPanel.add(textFieldNumMatches); textFieldNumTrialsPerMatch = new JTextField(); textFieldNumTrialsPerMatch.setText("100"); textFieldNumTrialsPerMatch.setColumns(10); textFieldNumTrialsPerMatch.setBounds(220, 510, 162, 19); LeftPanel.add(textFieldNumTrialsPerMatch); textFieldHardTimeLimit = new JTextField(); textFieldHardTimeLimit.setText("60"); textFieldHardTimeLimit.setColumns(10); textFieldHardTimeLimit.setBounds(220, 536, 162, 19); LeftPanel.add(textFieldHardTimeLimit); String tempFilePath = DesktopApp.lastSelectedJsonPath(); if (tempFilePath == null) tempFilePath = System.getProperty("user.dir"); final String defaultFilePath = tempFilePath; txtcommonresoutput = new JTextField(); txtcommonresoutput.setText(defaultFilePath); txtcommonresoutput.setBounds(140, 460, 180, 19); LeftPanel.add(txtcommonresoutput); txtcommonresoutput.setColumns(10); final JButton buttonSelectDir = new JButton("Select"); buttonSelectDir.setFont(new Font("Arial", Font.PLAIN, 7)); buttonSelectDir.setBounds(324, 460, 55, 18); final ActionListener buttonListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final JFileChooser fileChooser = FileLoading.createFileChooser(defaultFilePath, ".txt", "TXT files (.txt)"); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Select output directory."); final int jsonReturnVal = fileChooser.showOpenDialog(DesktopApp.frame()); final File directory; if (jsonReturnVal == JFileChooser.APPROVE_OPTION) directory = fileChooser.getSelectedFile(); else directory = null; if (directory != null && directory.exists()) { txtcommonresoutput.setText(directory.getPath()); } else { txtcommonresoutput.setText(defaultFilePath); } } }; buttonSelectDir.addActionListener(buttonListener); LeftPanel.add(buttonSelectDir); final JButton btnCalculateTurnRange = new JButton("Calculate"); btnCalculateTurnRange.setBounds(220, 323, 162, 23); LeftPanel.add(btnCalculateTurnRange); final JCheckBox useDatabaseTrialsCheckBox = new JCheckBox("Use Database Trials (when available)"); useDatabaseTrialsCheckBox.setBounds(26, 97, 323, 23); useDatabaseTrialsCheckBox.setSelected(true); LeftPanel.add(useDatabaseTrialsCheckBox); // If the user has selected Custom agent, then other options are available. comboBoxAIAgents.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (comboBoxAIAgents.getSelectedItem().toString().equals("Custom")) { comboBoxAlgorithm.setEnabled(true); textFieldThinkTime.setEnabled(true); } else { comboBoxAlgorithm.setEnabled(false); textFieldThinkTime.setEnabled(false); } } }); // Calculate the automatic min/max turn numbers btnCalculateTurnRange.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.setVolatileMessage("Please Wait a few seconds."); app.repaint(); EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> { final double brachingFactor = estimateBranchingFactor(app, 5); if (brachingFactor != 0) { textFieldMinIdealTurns.setText(String.valueOf(brachingFactor)); textFieldMaxIdealTurns.setText(String.valueOf(brachingFactor*2)); } else { app.addTextToAnalysisPanel("Failed to calculate branching factor"); } }); }); } }); final JPanel RightPanel = new JPanel(); panel.add(RightPanel); RightPanel.setLayout(null); { final JPanel buttonPane = new JPanel(); buttonPane.setBorder(new LineBorder(new Color(0, 0, 0))); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { okButton = new JButton("Evaluate"); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } } final List<JSlider> allMetricSliders = new ArrayList<>(); final List<JTextField> allMetricTextFields = new ArrayList<>(); JTextField textField_1 = new JTextField(); // Ok button for starting the evaluation. okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (Double.valueOf(textFieldThinkTime.getText().toString()).doubleValue() <= 0) { app.addTextToAnalysisPanel("Invalid think time, setting to 0.05"); textFieldThinkTime.setText("0.05"); } try { if (Integer.valueOf(textFieldMaxTurns.getText().toString()).intValue() <= 0) { app.addTextToAnalysisPanel("Invalid maximum number of turns, setting to 50"); textFieldMaxTurns.setText("50"); } } catch (final NumberFormatException exception) { app.addTextToAnalysisPanel("Invalid maximum number of turns, setting to 50"); textFieldMaxTurns.setText("50"); } try { if (Integer.valueOf(textFieldNumberTrials.getText().toString()).intValue() <= 0) { app.addTextToAnalysisPanel("Invalid number of trials, setting to 10"); textFieldNumberTrials.setText("10"); } } catch (final NumberFormatException exception) { app.addTextToAnalysisPanel("Invalid number of trials, setting to 10"); textFieldNumberTrials.setText("10"); } try { if (Double.valueOf(textFieldMinIdealTurns.getText().toString()).doubleValue() < 0) { app.addTextToAnalysisPanel("Invalid minimum number of ideal turns, setting to 0"); textFieldMinIdealTurns.setText("0"); } } catch (final NumberFormatException exception) { app.addTextToAnalysisPanel("Invalid minimum number of ideal turns, setting to 0"); textFieldMinIdealTurns.setText("0"); } try { if (Double.valueOf(textFieldMaxIdealTurns.getText().toString()).doubleValue() <= 0) { app.addTextToAnalysisPanel("Invalid maximum number of ideal turns, setting to 1000"); textFieldMaxIdealTurns.setText("1000"); } } catch (final NumberFormatException exception) { app.addTextToAnalysisPanel("Invalid maximum number of ideal turns, setting to 1000"); textFieldMaxIdealTurns.setText("1000"); } final int maxTurns = Integer.valueOf(textFieldMaxTurns.getText().toString()).intValue(); final int numberIterations = Integer.valueOf(textFieldNumberTrials.getText().toString()).intValue(); double thinkTime = 0.5; String AIName = null; switch(comboBoxAIAgents.getSelectedItem().toString()) { case "Random": AIName = "Random"; break; case "Very weak AI": AIName = "Ludii AI"; thinkTime = 0.1; break; case "Weak AI": AIName = "Ludii AI"; thinkTime = 0.5; break; case "Strong AI": AIName = "Ludii AI"; thinkTime = 2.0; break; case "Very strong AI": AIName = "Ludii AI"; thinkTime = 5.0; break; case "Custom": AIName = comboBoxAlgorithm.getSelectedItem().toString(); thinkTime = Double.valueOf(textFieldThinkTime.getText()).doubleValue(); break; } for (final Metric m : metrics) { if (m instanceof IdealDuration) { ((IdealDuration)m).setMinTurn(Double.valueOf(textFieldMinIdealTurns.getText()).doubleValue()); ((IdealDuration)m).setMaxTurn(Double.valueOf(textFieldMaxIdealTurns.getText()).doubleValue()); } if (m instanceof SkillTrace) { ((SkillTrace)m).setNumMatches(Integer.valueOf(textFieldNumMatches.getText()).intValue()); ((SkillTrace)m).setNumTrialsPerMatch(Integer.valueOf(textFieldNumTrialsPerMatch.getText()).intValue()); ((SkillTrace)m).setHardTimeLimit(Integer.valueOf(textFieldHardTimeLimit.getText()).intValue()); ((SkillTrace)m).setOutputPath(txtcommonresoutput.getText() + File.separatorChar); } } final Report report = new Report(); report.setReportMessageFunctions(new ReportMessengerGUI(app)); // Make a deepcopy of the weights to be used. final ArrayList<Double> weightsCopy = new ArrayList<>(); for (final Double d : weights) weightsCopy.add(new Double(d.doubleValue())); AIPlayer.AIEvalution(app, report, numberIterations, maxTurns, thinkTime, AIName, metrics, weightsCopy, useDatabaseTrialsCheckBox.isSelected()); DesktopApp.view().tabPanel().select(TabView.PanelAnalysis); } }); // Skill trace only button for starting the evaluation. skillTraceButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { for (int i = 0; i < weights.size(); i++) { double value = 0.0; if (metrics.get(i).name().equals("Skill trace")) value = 1.0; weights.set(i, Double.valueOf(value)); } for(final ActionListener a: okButton.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) { // Nothing needs go here. }); } // Reset weights back afterwards for (int i = 0; i < allMetricSliders.size(); i++) weights.set(i, Double.valueOf(allMetricTextFields.get(i).getText())); } }); // Set the branching factor (quickly) when the dialog is loaded. final double brachingFactor = estimateBranchingFactor(app, 1); if (brachingFactor != 0) { textFieldMinIdealTurns.setText(String.valueOf(brachingFactor)); textFieldMaxIdealTurns.setText(String.valueOf(brachingFactor*2)); } int currentYDistance = 60; int currentXDistance = 0; // Each Metric has a slider to represent its weight value; for (int i = 0; i < metrics.size(); i++) { final int metricIndex = i; final Metric m = metrics.get(metricIndex); final JLabel metricNameLabel = new JLabel(m.name()); metricNameLabel.setBounds(currentXDistance+110, currentYDistance-30, 200, 19); RightPanel.add(metricNameLabel); final String metricInfo = m.notes(); metricNameLabel.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(final MouseEvent evt) { metricNameLabel.setToolTipText(metricInfo); } }); final JSlider slider = new JSlider(); slider.setMinorTickSpacing(1); slider.setMajorTickSpacing(10); slider.setValue(100); slider.setMinimum(-100); slider.setBounds(currentXDistance+110, currentYDistance+30, 162, 16); RightPanel.add(slider); textField_1 = new JTextField(); textField_1.setEditable(false); textField_1.setBounds(currentXDistance+110, currentYDistance, 162, 19); RightPanel.add(textField_1); textField_1.setColumns(10); final JButton zeroButton = new JButton(); zeroButton.setBounds(currentXDistance+20, currentYDistance, 70, 19); zeroButton.setText("Zero"); RightPanel.add(zeroButton); // Zero button sets slider value to 0 zeroButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { slider.setValue(0); } }); currentYDistance = currentYDistance + 100; final double initialWeightValue = slider.getValue() / 100.0; if (currentYDistance > getHeight() - 150) { currentXDistance += 300; currentYDistance = 60; this.setSize(getWidth()+300, getHeight()); } allMetricTextFields.add(textField_1); allMetricSliders.add(slider); weights.add(Double.valueOf(initialWeightValue)); allMetricTextFields.get(metricIndex).setText(Double.toString(initialWeightValue)); allMetricSliders.get(metricIndex).addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent arg0) { allMetricTextFields.get(metricIndex).setText(Double.toString(allMetricSliders.get(metricIndex).getValue() / 100.0)); weights.set(metricIndex, Double.valueOf(allMetricTextFields.get(metricIndex).getText())); } }); } } //------------------------------------------------------------------------- public static double estimateBranchingFactor(final PlayerApp app, final int numSecs) { if (!app.manager().ref().context().game().isDeductionPuzzle()) { final TObjectDoubleHashMap<String> results = Complexity.estimateBranchingFactor ( app.manager().savedLudName(), app.manager().settingsManager().userSelections(), numSecs ); return results.get("Avg Trial Branching Factor"); } return 0; } }
20,001
31.952224
160
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/GameLoaderDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import app.DesktopApp; import main.AliasesData; import main.FileHandling; /** * Class for showing a dialog to choose a game to load. * * @author Dennis Soemers, Matthew Stephenson */ public class GameLoaderDialog { static String lastKeyPressed = ""; static String oldSearchString = ""; //------------------------------------------------------------------------- /** * Shows a Game Loader dialog. * * @param frame * @param choices * @param initialChoice * @return Chosen game, or null if no choice made */ public static String showDialog ( final JFrame frame, final String[] choices, final String initialChoice ) { final JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); lastKeyPressed = ""; // reset this since it's static, shared between dialogs // convert our list of games into a tree final List<GameLoaderNode> leafNodes = new ArrayList<GameLoaderNode>(); final Map<String, GameLoaderNode> nodesMap = new HashMap<String, GameLoaderNode>(); final GameLoaderNode root = new GameLoaderNode("Games", "/lud/"); for (final String choice : choices) { if (!DesktopApp.devJar && FileHandling.shouldIgnoreLudRelease(choice)) continue; String str = choice.replaceAll(Pattern.quote("\\"), "/"); if (str.startsWith("/")) str = str.substring(1); final String[] parts = str.split("/"); if (!parts[0].equals("lud")) System.err.println("top level is not lud: " + parts[0]); String runningFullName = "/lud/"; GameLoaderNode internalNode = root; for (int i = 1; i < parts.length - 1; ++i) { final GameLoaderNode nextInternal; runningFullName += parts[i] + "/"; if (!nodesMap.containsKey(runningFullName)) { nextInternal = new GameLoaderNode(parts[i], runningFullName); nodesMap.put(runningFullName, nextInternal); int childIdx = 0; while (childIdx < internalNode.getChildCount()) { final GameLoaderNode existingChild = (GameLoaderNode) internalNode.getChildAt(childIdx); final String name = (String) existingChild.getUserObject(); if (existingChild.fullName.endsWith(".lud")) { // Our internal node should always go before .lud files break; } else if (parts[i].compareToIgnoreCase(name) < 0) { // Alphabetical ordering means we should go before this node break; } ++childIdx; } internalNode.insert(nextInternal, childIdx); } else { nextInternal = nodesMap.get(runningFullName); } internalNode = nextInternal; } final GameLoaderNode leafNode = new GameLoaderNode(parts[parts.length - 1].substring(0, parts[parts.length - 1].length()-4), choice); nodesMap.put(choice, leafNode); leafNodes.add(leafNode); internalNode.add(leafNode); } final GameLoaderTree tree = new GameLoaderTree(root); // only allow selecting a single leaf, not multiple leaves tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // select initial choice try { tree.setSelectionPath(new TreePath(nodesMap.get(initialChoice).getPath())); } catch (final Exception e) { // user probably has a puzzle or other non-online game loaded } // create our text field for filtering final JTextField filterField = new JTextField(); filterField.setFont(new Font("Arial", Font.PLAIN, 20)); final Font gainFont = new Font("Arial", Font.PLAIN, 20); final Font lostFont = new Font("Arial", Font.PLAIN, 20); final String hint = "Search Game"; filterField.setText(hint); filterField.setFont(lostFont); filterField.setForeground(Color.GRAY); tree.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if (lastKeyPressed == "UP") { tree.setSelectionRow(tree.getLeadSelectionRow()-1); lastKeyPressed = ""; } if (lastKeyPressed == "DOWN") { tree.setSelectionRow(tree.getLeadSelectionRow()+1); lastKeyPressed = ""; } } }); filterField.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if (filterField.getText().equals(hint)) { filterField.setText(""); filterField.setFont(gainFont); } else { filterField.setText(filterField.getText()); filterField.setFont(gainFont); } EventQueue.invokeLater(new Runnable() { @Override public void run() { final String currentSearchString = filterField.getText(); if (oldSearchString.equals(currentSearchString) || (oldSearchString.equals("Search Game") && currentSearchString.equals(""))) { if (!lastKeyPressed.equals("")) { filterField.setText(filterField.getText() + lastKeyPressed); lastKeyPressed = ""; } } } }); setTextColour(); } @Override public void focusLost(final FocusEvent e) { if (filterField.getText().equals(hint) || filterField.getText().length() == 0) { filterField.setText(hint); } setTextColour(); } public void setTextColour() { if (filterField.getText().equals(hint)) { filterField.setFont(lostFont); filterField.setForeground(Color.GRAY); } else { filterField.setFont(gainFont); filterField.setForeground(Color.BLACK); } } }); filterField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(final DocumentEvent e) { handleEvent(e); } @Override public void removeUpdate(final DocumentEvent e) { handleEvent(e); } @Override public void changedUpdate(final DocumentEvent e) { handleEvent(e); } /** * Handle any kind of change in text * @param e */ public void handleEvent(final DocumentEvent e) { tree.updateTreeFilter(filterField); tree.revalidate(); } }); final JScrollPane treeView = new JScrollPane(tree); contentPane.add(treeView, BorderLayout.CENTER); contentPane.add(filterField, BorderLayout.SOUTH); contentPane.setPreferredSize(new Dimension(650, 700)); // try to make our dialog resizable contentPane.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(final HierarchyEvent e) { final Window window = SwingUtilities.getWindowAncestor(contentPane); if (window instanceof Dialog) { final Dialog dialog = (Dialog) window; if (!dialog.isResizable()) dialog.setResizable(true); dialog.setLocationRelativeTo(DesktopApp.frame()); tree.requestFocus(); } } }); // give focus to our tree after the "Ok" button steals it tree.addFocusListener ( new FocusListener() { /** Should only steal back once */ private boolean isFirstTime = true; @Override public void focusGained(final FocusEvent e) { // Do nothing } @Override public void focusLost(final FocusEvent e) { if (isFirstTime) { tree.requestFocus(); isFirstTime = false; } } } ); // finally we can create our dialog final URL iconURL = DesktopApp.class.getResource("/ludii-logo-100x100.png"); BufferedImage image = null; try { image = ImageIO.read(iconURL); } catch (final IOException e) { e.printStackTrace(); } final JOptionPane pane = new JOptionPane ( contentPane, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null, null ); final JDialog dialog = pane.createDialog("Choose a Game to Load"); dialog.setIconImage(image); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setModal(true); final KeyEventDispatcher keyDispatcher = new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(final KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { pane.setValue(Integer.valueOf(JOptionPane.OK_OPTION)); dialog.dispose(); } else if (e.getKeyCode() == KeyEvent.VK_UP) { if (!tree.hasFocus()) { lastKeyPressed = "UP"; tree.requestFocus(); } } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (!tree.hasFocus()) { lastKeyPressed = "DOWN"; tree.requestFocus(); } } else if ( e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_RIGHT && KeyEvent.getKeyText(e.getKeyCode()).length() == 1 ) { if (!filterField.hasFocus()) { oldSearchString = filterField.getText(); lastKeyPressed = Character.toString(e.getKeyChar()); filterField.requestFocus(); return true; } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher); // Create mouse listener to allow double-click selection of games tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (e.getClickCount() == 2) { final TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path != null) { final GameLoaderNode node = (GameLoaderNode) path.getLastPathComponent(); if (node.fullName.endsWith(".lud")) { pane.setValue(Integer.valueOf(JOptionPane.OK_OPTION)); dialog.dispose(); } } } } }); // expand all nodes that have at least one non-leaf child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) bfsEnumeration.nextElement(); final Enumeration<?> children = node.children(); while (children.hasMoreElements()) { final GameLoaderNode child = (GameLoaderNode) children.nextElement(); if (!child.isLeaf()) { tree.expandPath(new TreePath(node.getPath())); break; } } } // show the dialog dialog.setVisible(true); final Object selectedValue = pane.getValue(); // get rid of our key event dispatcher again KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keyDispatcher); final int result; if (selectedValue == null) { result = JOptionPane.CLOSED_OPTION; } else { if (selectedValue instanceof Integer) result = ((Integer)selectedValue).intValue(); else result = JOptionPane.CLOSED_OPTION; } if (result == JOptionPane.OK_OPTION) { final TreePath treePath = tree.getSelectionPath(); if (treePath != null) { final GameLoaderNode selectedLeaf = (GameLoaderNode) treePath.getLastPathComponent(); if (!selectedLeaf.isLeaf()) return null; return selectedLeaf.fullName; } } return null; } //------------------------------------------------------------------------- /** * Custom class for the nodes in our tree * * Filtering code based on: http://www.java2s.com/Code/Java/Swing-Components/InvisibleNodeTreeExample.htm * * @author Dennis Soemers */ private static class GameLoaderNode extends DefaultMutableTreeNode { /** */ private static final long serialVersionUID = 1L; /** Full name */ public final String fullName; /** Aliases that we want to be searchable */ protected final List<String> aliases; /** Whether or not it's visible (given current filter) */ protected boolean isVisible = true; /** * Constructor * @param shortName * @param fullName */ public GameLoaderNode(final String shortName, final String fullName) { super(shortName); this.fullName = fullName; final AliasesData aliasesData = AliasesData.loadData(); final List<String> loadedAliases = aliasesData.aliasesForGame(this.fullName.replaceAll(Pattern.quote("\\"), "/")); if (loadedAliases != null) { aliases = new ArrayList<String>(loadedAliases.size()); for (final String alias : loadedAliases) { aliases.add( alias .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), "") .replaceAll(Pattern.quote("'"), "") ); } } else { aliases = new ArrayList<String>(); } } /** * @return Child at given index (after filtering if filter == true). */ public TreeNode getChildAt(final int index, final boolean filter) { if (!filter) return super.getChildAt(index); int visibleIdx = -1; final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) e.nextElement(); if (node.isVisible) ++visibleIdx; if (visibleIdx == index) return node; } throw new ArrayIndexOutOfBoundsException("index unmatched after filtering"); } /** * @return Number of child nodes (after filtering if filter == true) */ public int getChildCount(final boolean filter) { if (!filter) return super.getChildCount(); int count = 0; try { final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) e.nextElement(); if (node.isVisible) ++count; } } catch (final Exception e) { // carry on } return count; } /** * Recursively updates visibility based on user's filter text */ public void updateVisibility(final String filterText) { if (isLeaf()) { final String[] fullNameSplit = fullName.split(Pattern.quote("/")); final String gameName = fullNameSplit[fullNameSplit.length-1]; isVisible = ( gameName .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), "") .replaceAll(Pattern.quote("'"), "") .contains(filterText) ); if (!isVisible) { for (final String alias : aliases) { if (alias.contains(filterText)) { isVisible = true; break; } } } } else { isVisible = false; final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final GameLoaderNode child = (GameLoaderNode) e.nextElement(); child.updateVisibility(filterText); if (child.isVisible) isVisible = true; } } } } //------------------------------------------------------------------------- /** * Custom class for our tree model. Provides functionality for the filtering * field. * * Filtering code based on: http://www.java2s.com/Code/Java/Swing-Components/InvisibleNodeTreeExample.htm * * @author Dennis Soemers */ private static class GameLoaderTreeModel extends DefaultTreeModel { /** */ private static final long serialVersionUID = 1L; /** Whether or not we should filter */ protected boolean filterActive = false; /** * Constructor * @param root */ public GameLoaderTreeModel(final GameLoaderNode root) { super(root); } /** * Set whether filter should be active * @param active */ public void setFilterActive(final boolean active) { filterActive = active; } @Override public Object getChild(final Object parent, final int index) { return ((GameLoaderNode) parent).getChildAt(index, filterActive); } @Override public int getChildCount(final Object parent) { return ((GameLoaderNode) parent).getChildCount(filterActive); } } //------------------------------------------------------------------------- /** * Custom class for our tree. Overrides getNextMatch() to allow keyboard-based * searching of games inside collapsed categories/folders. * * @author Dennis Soemers */ private static class GameLoaderTree extends JTree { /** */ private static final long serialVersionUID = 1L; /** * Constructor * @param root */ public GameLoaderTree(final GameLoaderNode root) { super(new GameLoaderTreeModel(root)); } @Override public TreePath getNextMatch ( final String prefix, final int startingRow, final Position.Bias bias ) { final int max = getRowCount(); if (prefix == null) throw new IllegalArgumentException(); if (startingRow < 0 || startingRow >= max) throw new IllegalArgumentException(); final String str = prefix.toUpperCase(); final int increment = (bias == Position.Bias.Forward) ? 1 : -1; int row = startingRow; do { final TreePath path = getPathForRow(row); final GameLoaderNode rowNode = (GameLoaderNode) path.getLastPathComponent(); final Enumeration<?> bfsEnumeration = rowNode.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) bfsEnumeration.nextElement(); final String nodeName = ((String) node.getUserObject()).toUpperCase(); if (nodeName.startsWith(str) && node.fullName.endsWith(".LUD")) return new TreePath(node.getPath()); } row = (row + increment + max) % max; } while (row != startingRow); return null; } /** * Updates visible nodes in tree based on text entered in filter field * @param filterField */ public void updateTreeFilter(final JTextField filterField) { final GameLoaderTreeModel model = (GameLoaderTreeModel) getModel(); model.setFilterActive(false); String filterText = filterField.getText() .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), "") .replaceAll(Pattern.quote("'"), ""); final GameLoaderNode root = ((GameLoaderNode) model.getRoot()); if (filterText.equals("searchgame")) { filterText = ""; } if (filterText.length() > 0) { root.updateVisibility(filterText); model.setFilterActive(true); } model.reload(); if (filterText.length() == 0) { // expand all nodes that have at least one non-leaf child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) bfsEnumeration.nextElement(); final Enumeration<?> children = node.children(); while (children.hasMoreElements()) { final GameLoaderNode child = (GameLoaderNode) children.nextElement(); if (!child.isLeaf()) { expandPath(new TreePath(node.getPath())); break; } } } } else { // expand all nodes that have at least one child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) bfsEnumeration.nextElement(); if (!node.isLeaf()) expandPath(new TreePath(node.getPath())); } // set the first game, found in a depth-first enumeration, // that's a complete match from the start of game's filename, // as the current selection final Enumeration<?> dfsEnumeration = root.depthFirstEnumeration(); while (dfsEnumeration.hasMoreElements()) { final GameLoaderNode node = (GameLoaderNode) dfsEnumeration.nextElement(); if (node.isLeaf()) { final String gameFilename = ((String) node.getUserObject()) .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), "") .replaceAll(Pattern.quote("'"), ""); if (gameFilename.startsWith(filterText)) { // found a complete match at start of filename setSelectionPath(new TreePath(node.getPath())); break; } } } } scrollRowToVisible(getLeadSelectionRow()); } } //------------------------------------------------------------------------- }
22,018
24.514484
136
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/ReconstructionDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import main.FileHandling; import reconstruction.ReconstructionGenerator; /** * @author Matthew.Stephenson and Eric.Piette */ public class ReconstructionDialog extends JDialog { private static final long serialVersionUID = 1L; private final JPanel contentPanel = new JPanel(); final JTextField txtcommonresoutput; JTextField textFieldMaxRecons; JTextField textFieldCSNScore; JTextField textFieldConceptScore; JTextField textFieldPlayability; final JTextField textFieldMaxTries; static String selectedLudPath = ""; /** * Launch the application. */ public static void createAndShowGUI(final PlayerApp app) { try { final ReconstructionDialog dialog = new ReconstructionDialog(app); DialogUtil.initialiseSingletonDialog(dialog, "Reconstruction", null); } catch (final Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public ReconstructionDialog(final PlayerApp app) { setTitle("Reconstruction"); setBounds(100, 100, 450, 350); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); final JLabel lblOutputPath = new JLabel("Output Path"); lblOutputPath.setBounds(12, 56, 149, 38); contentPanel.add(lblOutputPath); final JButton okButton = new JButton("OK"); txtcommonresoutput = new JTextField(); txtcommonresoutput.setText("."); txtcommonresoutput.setBounds(167, 68, 220, 19); contentPanel.add(txtcommonresoutput); txtcommonresoutput.setColumns(10); { final JLabel lblMaximumNumber = new JLabel("Playable Recons"); lblMaximumNumber.setBounds(12, 99, 149, 38); contentPanel.add(lblMaximumNumber); } { textFieldMaxRecons = new JTextField(); textFieldMaxRecons.setText("10"); textFieldMaxRecons.setColumns(10); textFieldMaxRecons.setBounds(280, 109, 130, 19); contentPanel.add(textFieldMaxRecons); } { final JLabel lblCsnScore = new JLabel("Historical Weight"); lblCsnScore.setBounds(12, 170, 149, 38); contentPanel.add(lblCsnScore); } { final JLabel lblConceptScore = new JLabel("Conceptual Weight"); lblConceptScore.setBounds(12, 199, 149, 38); contentPanel.add(lblConceptScore); } // { // final JLabel lblPlayability = new JLabel("Quality"); // lblPlayability.setBounds(12, 228, 149, 38); // contentPanel.add(lblPlayability); // } { textFieldCSNScore = new JTextField(); textFieldCSNScore.setText("1.0"); textFieldCSNScore.setColumns(10); textFieldCSNScore.setBounds(280, 180, 130, 19); contentPanel.add(textFieldCSNScore); } { textFieldConceptScore = new JTextField(); textFieldConceptScore.setText("1.0"); textFieldConceptScore.setColumns(10); textFieldConceptScore.setBounds(280, 209, 130, 19); contentPanel.add(textFieldConceptScore); } // { // textFieldPlayability = new JTextField(); // textFieldPlayability.setText("1.0"); // textFieldPlayability.setColumns(10); // textFieldPlayability.setBounds(280, 238, 130, 19); // contentPanel.add(textFieldPlayability); // } final JButton btnSelectGame = new JButton("Select Game"); btnSelectGame.setBounds(12, 28, 130, 25); contentPanel.add(btnSelectGame); final JLabel selectedGameText = new JLabel(""); selectedGameText.setBounds(177, 21, 233, 38); contentPanel.add(selectedGameText); btnSelectGame.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { String[] choices = FileHandling.listGames(); // Remove any invalid network games from the possible choices final List<String> reconGamesList = new ArrayList<>(); for (final String lud : choices) if (lud.contains("reconstruction/") && !lud.contains("wip/")) reconGamesList.add(lud); choices = reconGamesList.toArray(new String[0]); String initialChoice = choices[0]; for (final String choice : choices) { if (app.manager().savedLudName() != null && app.manager().savedLudName().endsWith(choice.replaceAll(Pattern.quote("\\"), "/"))) { initialChoice = choice; break; } } selectedLudPath = GameLoaderDialog.showDialog(DesktopApp.frame(), choices, initialChoice); selectedGameText.setText(selectedLudPath.split("/")[selectedLudPath.split("/").length-1]); if(!selectedGameText.getText().isEmpty()) okButton.setEnabled(true); } catch (final Exception e1) { // Probably just cancelled the game loader. } } }); final JButton buttonSelectDir = new JButton(""); buttonSelectDir.setBounds(388, 68, 20, 18); final ActionListener buttonListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final JFileChooser fileChooser = DesktopApp.jsonFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Select output directory."); final int jsonReturnVal = fileChooser.showOpenDialog(DesktopApp.frame()); final File directory; if (jsonReturnVal == JFileChooser.APPROVE_OPTION) directory = fileChooser.getSelectedFile(); else directory = null; if (directory != null && directory.exists()) { txtcommonresoutput.setText(directory.getPath()); } else { System.err.println("Could not find output directory."); } } }; buttonSelectDir.addActionListener(buttonListener); contentPanel.add(buttonSelectDir); final JLabel lblMaximumTries = new JLabel("Maximum Tries"); lblMaximumTries.setBounds(12, 128, 149, 38); contentPanel.add(lblMaximumTries); textFieldMaxTries = new JTextField(); textFieldMaxTries.setText("10000"); textFieldMaxTries.setColumns(10); textFieldMaxTries.setBounds(280, 138, 130, 19); contentPanel.add(textFieldMaxTries); final JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); okButton.setEnabled(false); final ActionListener okButtonListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { try { final String outputPath = txtcommonresoutput.getText(); final Integer numRecons = Integer.valueOf(textFieldMaxRecons.getText()); final Integer maxTries = Integer.valueOf(textFieldMaxTries.getText()); Double csnScore = Double.valueOf(textFieldCSNScore.getText()); Double conceptScore = Double.valueOf(textFieldConceptScore.getText()); double totalWeight = csnScore.doubleValue() + conceptScore.doubleValue(); double csnWeight = csnScore.doubleValue() / totalWeight; double conceptWeight = conceptScore.doubleValue() / totalWeight; ReconstructionGenerator.reconstruction(outputPath + File.separatorChar, numRecons.intValue(), maxTries.intValue(), conceptWeight, csnWeight, 0.33, selectedLudPath, ""); // 0.33 will need to be replace by geoWeight } catch (final Exception e) { e.printStackTrace(); } } }; okButton.addActionListener(okButtonListener); } } }
8,083
30.701961
219
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/SVGViewerDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jfree.graphics2d.svg.SVGGraphics2D; import app.DesktopApp; import app.PlayerApp; import app.display.SVGWindow; import app.loading.MiscLoading; import app.utils.SVGUtil; import other.context.Context; /** * Class for showing a dialog to choose a svg to load. * * @author Matthew Stephenson */ public class SVGViewerDialog { static String lastKeyPressed = ""; //------------------------------------------------------------------------- /** * Shows a svg Loader dialog. * * @param frame * @param choices * @return Chosen svg, or null if no choice made */ public static String showDialog(final PlayerApp app, final JFrame frame, final String[] choices) { final JPanel contentPane = new JPanel(); final SVGWindow svgView = new SVGWindow(); contentPane.setLayout(new BorderLayout()); lastKeyPressed = ""; // reset this since it's static, shared between dialogs // convert our list of svgs into a tree final List<svgLoaderNode> leafNodes = new ArrayList<>(); final Map<String, svgLoaderNode> nodesMap = new HashMap<>(); final svgLoaderNode root = new svgLoaderNode("svgs", File.separator + "svg" + File.separator); for (final String choice : choices) { String str = choice.replaceAll(Pattern.quote("\\"), "/"); if (str.startsWith("/")) str = str.substring(1); final String[] parts = str.split("/"); if (!parts[0].equals("svg")) System.err.println("top level is not svg: " + parts[0]); String runningFullName = File.separator + "svg" + File.separator; svgLoaderNode internalNode = root; for (int i = 1; i < parts.length - 1; ++i) { final svgLoaderNode nextInternal; runningFullName += parts[i] + File.separator; if (!nodesMap.containsKey(runningFullName)) { nextInternal = new svgLoaderNode(parts[i], runningFullName); nodesMap.put(runningFullName, nextInternal); int childIdx = 0; while (childIdx < internalNode.getChildCount()) { final svgLoaderNode existingChild = (svgLoaderNode) internalNode.getChildAt(childIdx); final String name = (String) existingChild.getUserObject(); if (name.endsWith(".svg")) { // Our internal node should always go before .lud files break; } else if (parts[i].compareToIgnoreCase(name) < 0) { // Alphabetical ordering means we should go before this node break; } ++childIdx; } internalNode.insert(nextInternal, childIdx); } else { nextInternal = nodesMap.get(runningFullName); } internalNode = nextInternal; } final svgLoaderNode leafNode = new svgLoaderNode(parts[parts.length - 1], choice); nodesMap.put(choice, leafNode); leafNodes.add(leafNode); internalNode.add(leafNode); } final svgLoaderTree tree = new svgLoaderTree(root); expandAllNodes(tree, 0, tree.getRowCount()); // only allow selecting a single leaf, not multiple leaves tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // create our text field for filtering final JTextField filterField = new JTextField(); filterField.setFont(new Font("Arial", Font.PLAIN, 20)); final Font gainFont = new Font("Arial", Font.PLAIN, 20); final Font lostFont = new Font("Arial", Font.PLAIN, 20); final String hint = "Search SVG"; filterField.setText(hint); filterField.setFont(lostFont); filterField.setForeground(Color.GRAY); final KeyEventDispatcher keyDispatcher = new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(final KeyEvent e) { boolean focusRequested = false; if (e.getKeyCode() == KeyEvent.VK_UP) { if (!tree.hasFocus()) { lastKeyPressed = "UP"; tree.requestFocus(); } } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (!tree.hasFocus()) { lastKeyPressed = "DOWN"; tree.requestFocus(); } } else if ( e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_RIGHT && KeyEvent.getKeyText(e.getKeyCode()).length() == 1 ) { if (!filterField.hasFocus()) { lastKeyPressed = Character.toString(e.getKeyChar()); filterField.requestFocus(); focusRequested = true; } } String fileName = null; final TreePath treePath = tree.getSelectionPath(); if (treePath != null) { final svgLoaderNode selectedLeaf = (svgLoaderNode) treePath.getLastPathComponent(); if (selectedLeaf.isLeaf()) fileName = selectedLeaf.fullName; } if (fileName != null) { displayImage(app, fileName, contentPane, svgView); } return focusRequested; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher); tree.addKeyListener(new KeyListener() { @Override public void keyTyped(final KeyEvent e) { // nothing } @Override public void keyPressed(final KeyEvent e) { final int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { updateSVGView(); } if (keyCode == KeyEvent.VK_DOWN) { updateSVGView(); } } private void updateSVGView() { EventQueue.invokeLater(new Runnable() { @Override public void run() { String fileName = null; final TreePath treePath = tree.getSelectionPath(); if (treePath != null) { final svgLoaderNode selectedLeaf = (svgLoaderNode) treePath.getLastPathComponent(); if (selectedLeaf.isLeaf()) fileName = selectedLeaf.fullName; } if (fileName != null) { displayImage(app, fileName, contentPane, svgView); } } }); } @Override public void keyReleased(final KeyEvent e) { // nothing } }); tree.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if (lastKeyPressed == "UP") { tree.setSelectionRow(tree.getLeadSelectionRow()-1); lastKeyPressed = ""; } if (lastKeyPressed == "DOWN") { tree.setSelectionRow(tree.getLeadSelectionRow()+1); lastKeyPressed = ""; } } }); filterField.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if (filterField.getText().equals(hint)) { filterField.setText(""); filterField.setFont(gainFont); } else { filterField.setText(filterField.getText()); filterField.setFont(gainFont); } if (!lastKeyPressed.equals("")) { filterField.setText(filterField.getText() + lastKeyPressed); lastKeyPressed = ""; } setTextColour(); } @Override public void focusLost(final FocusEvent e) { if (filterField.getText().equals(hint) || filterField.getText().length() == 0) { filterField.setText(hint); } setTextColour(); } public void setTextColour() { if (filterField.getText().equals(hint)) { filterField.setFont(lostFont); filterField.setForeground(Color.GRAY); } else { filterField.setFont(gainFont); filterField.setForeground(Color.BLACK); } } }); filterField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(final DocumentEvent e) { handleEvent(e); } @Override public void removeUpdate(final DocumentEvent e) { handleEvent(e); } @Override public void changedUpdate(final DocumentEvent e) { handleEvent(e); } /** * Handle any kind of change in text * @param e */ public void handleEvent(final DocumentEvent e) { tree.updateTreeFilter(filterField); tree.revalidate(); } }); final JScrollPane treeView = new JScrollPane(tree); treeView.setPreferredSize(new Dimension(300, 400)); contentPane.add(treeView, BorderLayout.WEST); contentPane.add(filterField, BorderLayout.SOUTH); contentPane.add(svgView, BorderLayout.CENTER); contentPane.setPreferredSize(new Dimension(1000, 400)); // try to make our dialog resizable contentPane.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(final HierarchyEvent e) { final Window window = SwingUtilities.getWindowAncestor(contentPane); if (window instanceof Dialog) { final Dialog dialog = (Dialog) window; if (!dialog.isResizable()) dialog.setResizable(true); tree.requestFocus(); } } }); // give focus to our tree after the "Ok" button steals it tree.addFocusListener ( new FocusListener() { /** Should only steal back once */ private boolean isFirstTime = true; @Override public void focusGained(final FocusEvent e) { // do nothing } @Override public void focusLost(final FocusEvent e) { if (isFirstTime) { tree.requestFocus(); isFirstTime = false; } } } ); // finally we can create our dialog final URL iconURL = DesktopApp.class.getResource("/ludii-logo-100x100.png"); BufferedImage image = null; try { image = ImageIO.read(iconURL); } catch (final IOException e) { e.printStackTrace(); } final JOptionPane pane = new JOptionPane ( contentPane, JOptionPane.PLAIN_MESSAGE, JOptionPane.CLOSED_OPTION, null, null, null ); final JDialog dialog = pane.createDialog("Choose an SVG to View"); dialog.setIconImage(image); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setModal(true); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { String fileName = null; final TreePath treePath = tree.getSelectionPath(); if (treePath != null) { final svgLoaderNode selectedLeaf = (svgLoaderNode) treePath.getLastPathComponent(); if (selectedLeaf.isLeaf()) fileName = selectedLeaf.fullName; } if (fileName != null) { displayImage(app, fileName, contentPane, svgView); } } }); // expand all nodes that have at least one non-leaf child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) bfsEnumeration.nextElement(); final Enumeration<?> children = node.children(); while (children.hasMoreElements()) { final svgLoaderNode child = (svgLoaderNode) children.nextElement(); if (!child.isLeaf()) { tree.expandPath(new TreePath(node.getPath())); break; } } } // show the dialog dialog.setVisible(true); final Object selectedValue = pane.getValue(); // get rid of our key event dispatcher again KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keyDispatcher); final int result; if (selectedValue == null) { result = JOptionPane.CLOSED_OPTION; } else { if (selectedValue instanceof Integer) result = ((Integer)selectedValue).intValue(); else result = JOptionPane.CLOSED_OPTION; } if (result == JOptionPane.OK_OPTION) { final TreePath treePath = tree.getSelectionPath(); if (treePath != null) { final svgLoaderNode selectedLeaf = (svgLoaderNode) treePath.getLastPathComponent(); if (!selectedLeaf.isLeaf()) return null; return selectedLeaf.fullName; } } return null; } //------------------------------------------------------------------------- /** * Custom class for the nodes in our tree * * Filtering code based on: http://www.java2s.com/Code/Java/Swing-Components/InvisibleNodeTreeExample.htm * * @author Dennis Soemers */ private static class svgLoaderNode extends DefaultMutableTreeNode { /** */ private static final long serialVersionUID = 1L; /** Full name */ public final String fullName; /** Whether or not it's visible (given current filter) */ protected boolean isVisible = true; /** * Constructor * @param shortName * @param fullName */ public svgLoaderNode(final String shortName, final String fullName) { super(shortName); this.fullName = fullName; } /** * @param index * @param filter * @return Child at given index (after filtering if filter == true). */ public TreeNode getChildAt(final int index, final boolean filter) { if (!filter) return super.getChildAt(index); int visibleIdx = -1; final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) e.nextElement(); if (node.isVisible) ++visibleIdx; if (visibleIdx == index) return node; } throw new ArrayIndexOutOfBoundsException("index unmatched after filtering"); } /** * @param filter * @return Number of child nodes (after filtering if filter == true) */ public int getChildCount(final boolean filter) { if (!filter) return super.getChildCount(); int count = 0; final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) e.nextElement(); if (node.isVisible) ++count; } return count; } /** * Recursively updates visibility based on user's filter text * @param filterText */ public void updateVisibility(final String filterText) { if (isLeaf()) { isVisible = ( fullName .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), "") .contains(filterText) ); } else { isVisible = false; final Enumeration<?> e = children.elements(); while (e.hasMoreElements()) { final svgLoaderNode child = (svgLoaderNode) e.nextElement(); child.updateVisibility(filterText); if (child.isVisible) isVisible = true; } } } } //------------------------------------------------------------------------- /** * Custom class for our tree model. Provides functionality for the filtering * field. * * Filtering code based on: http://www.java2s.com/Code/Java/Swing-Components/InvisibleNodeTreeExample.htm * * @author Dennis Soemers */ private static class svgLoaderTreeModel extends DefaultTreeModel { private static final long serialVersionUID = 1L; /** Whether or not we should filter */ protected boolean filterActive = false; /** * Constructor * @param root */ public svgLoaderTreeModel(final svgLoaderNode root) { super(root); } /** * Set whether filter should be active * @param active */ public void setFilterActive(final boolean active) { filterActive = active; } @Override public Object getChild(final Object parent, final int index) { return ((svgLoaderNode) parent).getChildAt(index, filterActive); } @Override public int getChildCount(final Object parent) { return ((svgLoaderNode) parent).getChildCount(filterActive); } } //------------------------------------------------------------------------- /** * Custom class for our tree. Overrides getNextMatch() to allow keyboard-based * searching of svgs inside collapsed categories/folders. * * @author Dennis Soemers */ private static class svgLoaderTree extends JTree { /** */ private static final long serialVersionUID = 1L; /** * Constructor * @param root */ public svgLoaderTree(final svgLoaderNode root) { super(new svgLoaderTreeModel(root)); } @Override public TreePath getNextMatch ( final String prefix, final int startingRow, final Position.Bias bias ) { final int max = getRowCount(); if (prefix == null) throw new IllegalArgumentException(); if (startingRow < 0 || startingRow >= max) throw new IllegalArgumentException(); final String str = prefix.toUpperCase(); final int increment = (bias == Position.Bias.Forward) ? 1 : -1; int row = startingRow; do { final TreePath path = getPathForRow(row); final svgLoaderNode rowNode = (svgLoaderNode) path.getLastPathComponent(); final Enumeration<?> bfsEnumeration = rowNode.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) bfsEnumeration.nextElement(); final String nodeName = ((String) node.getUserObject()).toUpperCase(); if (nodeName.startsWith(str) && nodeName.endsWith(".SVG")) return new TreePath(node.getPath()); } row = (row + increment + max) % max; } while (row != startingRow); return null; } /** * Updates visible nodes in tree based on text entered in filter field * @param filterField */ public void updateTreeFilter(final JTextField filterField) { final svgLoaderTreeModel model = (svgLoaderTreeModel) getModel(); model.setFilterActive(false); String filterText = filterField.getText() .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), ""); final svgLoaderNode root = ((svgLoaderNode) model.getRoot()); if (filterText.equals("searchsvg")) { filterText = ""; } if (filterText.length() > 0) { root.updateVisibility(filterText); model.setFilterActive(true); } model.reload(); if (filterText.length() == 0) { // expand all nodes that have at least one non-leaf child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) bfsEnumeration.nextElement(); final Enumeration<?> children = node.children(); while (children.hasMoreElements()) { final svgLoaderNode child = (svgLoaderNode) children.nextElement(); if (!child.isLeaf()) { expandPath(new TreePath(node.getPath())); break; } } } } else { // expand all nodes that have at least one child final Enumeration<?> bfsEnumeration = root.breadthFirstEnumeration(); while (bfsEnumeration.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) bfsEnumeration.nextElement(); if (!node.isLeaf()) expandPath(new TreePath(node.getPath())); } // set the first svg, found in a depth-first enumeration, // that's a complete match from the start of svg's filename, // as the current selection final Enumeration<?> dfsEnumeration = root.depthFirstEnumeration(); while (dfsEnumeration.hasMoreElements()) { final svgLoaderNode node = (svgLoaderNode) dfsEnumeration.nextElement(); if (node.isLeaf()) { final String svgFilename = ((String) node.getUserObject()) .toLowerCase() .replaceAll(Pattern.quote("-"), "") .replaceAll(Pattern.quote(" "), ""); if (svgFilename.startsWith(filterText)) { // found a complete match at start of filename setSelectionPath(new TreePath(node.getPath())); break; } } } } } } //------------------------------------------------------------------------- private static void expandAllNodes(final JTree tree, final int startingIndex, final int rowCount) { for(int i=startingIndex;i<rowCount;++i) { tree.expandRow(i); } if(tree.getRowCount()!=rowCount) { expandAllNodes(tree, rowCount, tree.getRowCount()); } } //------------------------------------------------------------------------- static void displayImage(final PlayerApp app, final String filePath, final JPanel contentPane, final SVGWindow svgView) { final int sz = contentPane.getWidth()/3; final String fileName = filePath.replaceAll(Pattern.quote("\\"), "/"); final Context context = app.contextSnapshot().getContext(app); final SVGGraphics2D svg = MiscLoading.renderImageSVG(sz, fileName, app.bridge().settingsColour().playerColour(context, 1)); final SVGGraphics2D svg2 = MiscLoading.renderImageSVG(sz, fileName, app.bridge().settingsColour().playerColour(context, 2)); final BufferedImage componentImageDot1 = SVGUtil.createSVGImage(svg.getSVGDocument(), sz, sz); final BufferedImage componentImageDot2 = SVGUtil.createSVGImage(svg2.getSVGDocument(), sz, sz); svgView.setImages(componentImageDot1, componentImageDot2); svgView.repaint(); } }
22,129
23.949267
126
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/SettingsDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.EnumSet; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.json.JSONObject; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.display.dialogs.util.MaxLengthTextDocument; import app.display.util.DesktopGUIUtil; import app.display.views.tabs.TabView; import app.move.MoveFormat; import app.utils.AnimationVisualsType; import main.Constants; import manager.ai.AIDetails; import manager.ai.AIUtil; import other.context.Context; /** * Dialog for changing various user settings. * Mostly auto-generated code. * * @author matthew.stephenson */ @SuppressWarnings("unchecked") public class SettingsDialog extends JDialog { private static final long serialVersionUID = 1L; final JTextField textFieldThinkingTimeAll; private static JTabbedPane tabbedPane = null; private static JPanel playerPanel = null; private static JPanel otherPanel = null; static SettingsDialog dialog; static JTextField[] playerNamesArray = new JTextField[Constants.MAX_PLAYERS+1]; static JComboBox<String>[] playerAgentsArray = new JComboBox[Constants.MAX_PLAYERS+1]; static JComboBox<String>[] playerThinkTimesArray = new JComboBox[Constants.MAX_PLAYERS+1]; /** We temporarily set this to true to ignore extra events generated when switching AI for ALL players. */ static boolean ignorePlayerComboBoxEvents = false; JTextField textFieldMaximumNumberOfTurns; JTextField textFieldTabFontSize; JTextField textFieldEditorFontSize; JTextField textFieldTickLength; //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void createAndShowGUI(final PlayerApp app) { try { dialog = new SettingsDialog(app); DialogUtil.initialiseSingletonDialog(dialog, "Preferences", new Rectangle(DesktopApp.frame().getX() + DesktopApp.frame().getWidth()/2 - 240, DesktopApp.frame().getY(), 500, DesktopApp.frame().getHeight())); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ public SettingsDialog(final PlayerApp app) { super(null, java.awt.Dialog.ModalityType.DOCUMENT_MODAL); setTitle("Settings"); final Context context = app.contextSnapshot().getContext(app); //setBounds(100, 100, 468, 900); getContentPane().setLayout(new BorderLayout(0, 0)); tabbedPane = new JTabbedPane(SwingConstants.TOP); getContentPane().add(tabbedPane, BorderLayout.CENTER); playerPanel = new JPanel(); //playerPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); final JScrollPane scroll = new JScrollPane(playerPanel); tabbedPane.addTab("Player", null, scroll, null); final int numPlayers = context.game().players().count(); final int playerSectionHeight = numPlayers * 30; addPlayerDetails(app, playerPanel, 1, context); addPlayerDetails(app, playerPanel, 2, context); addPlayerDetails(app, playerPanel, 3, context); addPlayerDetails(app, playerPanel, 4, context); addPlayerDetails(app, playerPanel, 5, context); addPlayerDetails(app, playerPanel, 6, context); addPlayerDetails(app, playerPanel, 7, context); addPlayerDetails(app, playerPanel, 8, context); addPlayerDetails(app, playerPanel, 9, context); addPlayerDetails(app, playerPanel, 10, context); addPlayerDetails(app, playerPanel, 11, context); addPlayerDetails(app, playerPanel, 12, context); addPlayerDetails(app, playerPanel, 13, context); addPlayerDetails(app, playerPanel, 14, context); addPlayerDetails(app, playerPanel, 15, context); addPlayerDetails(app, playerPanel, 16, context); textFieldThinkingTimeAll = new JTextField(); textFieldThinkingTimeAll.setBounds(275, 165 + playerSectionHeight, 103, 20); textFieldThinkingTimeAll.setEnabled(false); if (numPlayers > 1) textFieldThinkingTimeAll.setEnabled(true); textFieldThinkingTimeAll.setColumns(10); textFieldThinkingTimeAll.setText("-"); final JLabel lblName = new JLabel("Players"); lblName.setBounds(39, 32, 137, 21); lblName.setFont(new Font("Dialog", Font.BOLD, 16)); final ArrayList<String> aiStringsBlank = DesktopGUIUtil.getAIDropdownStrings(app, true); aiStringsBlank.add("-"); final JComboBox<?> comboBoxAgentAll = new JComboBox<>(aiStringsBlank.toArray()); comboBoxAgentAll.setBounds(118, 165 + playerSectionHeight, 134, 22); comboBoxAgentAll.setEnabled(false); if (numPlayers > 1) { comboBoxAgentAll.setEnabled(true); comboBoxAgentAll.setSelectedIndex(aiStringsBlank.size() - 1); } final DocumentListener documentListenerMaxTurns = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void insertUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void removeUpdate(final DocumentEvent documentEvent) { update(documentEvent); } private void update(final DocumentEvent documentEvent) { int numberTurns = Constants.DEFAULT_TURN_LIMIT; try { numberTurns = Integer.parseInt(textFieldMaximumNumberOfTurns.getText()); } catch (final Exception e) { // not an integer; } context.game().setMaxTurns(numberTurns); app.manager().settingsManager().setTurnLimit(context.game().name(),numberTurns); app.repaint(); } }; final DocumentListener documentListenerTickLength = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void insertUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void removeUpdate(final DocumentEvent documentEvent) { update(documentEvent); } private void update(final DocumentEvent documentEvent) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); double tickLength = app.manager().settingsManager().tickLength(); try { tickLength = Double.parseDouble(textFieldTickLength.getText()); } catch (final Exception e) { // not an integer; } app.manager().settingsManager().setTickLength(tickLength); app.repaint(); } }; final DocumentListener documentListenerTabFontSize = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void insertUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void removeUpdate(final DocumentEvent documentEvent) { update(documentEvent); } private void update(final DocumentEvent documentEvent) { int tabFontSize = app.settingsPlayer().tabFontSize(); try { tabFontSize = Integer.parseInt(textFieldTabFontSize.getText()); } catch (final Exception e) { // not an integer; } app.settingsPlayer().setTabFontSize(tabFontSize); DesktopApp.view().getPanels().clear(); app.repaint(); } }; final DocumentListener documentListenerEditorFontSize = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void insertUpdate(final DocumentEvent documentEvent) { update(documentEvent); } @Override public void removeUpdate(final DocumentEvent documentEvent) { update(documentEvent); } private void update(final DocumentEvent documentEvent) { int editorFontSize = app.settingsPlayer().editorFontSize(); try { editorFontSize = Integer.parseInt(textFieldEditorFontSize.getText()); } catch (final Exception e) { // not an integer; } app.settingsPlayer().setEditorFontSize(editorFontSize); //DesktopApp.view().getPanels().clear(); //app.repaint(); } }; final JLabel lblAgent = new JLabel("Agent"); lblAgent.setBounds(122, 135 + playerSectionHeight, 119, 19); lblAgent.setFont(new Font("Dialog", Font.BOLD, 16)); final JLabel lblAllPlayers = new JLabel("All Players"); lblAllPlayers.setBounds(29, 170 + playerSectionHeight, 78, 14); final JLabel lblThinkingTime = new JLabel("Thinking time"); lblThinkingTime.setBounds(275, 135 + playerSectionHeight, 123, 19); lblThinkingTime.setFont(new Font("Dialog", Font.BOLD, 16)); final JButton btnApply = new JButton("Apply"); btnApply.setFont(new Font("Tahoma", Font.BOLD, 16)); btnApply.setBounds(339, 238 + playerSectionHeight, 97, 29); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // AI type for all if (comboBoxAgentAll.isEnabled() && comboBoxAgentAll.getSelectedIndex() != aiStringsBlank.size() - 1) { // set AI name/type for (int i = 1; i <= Constants.MAX_PLAYERS; i++) playerAgentsArray[i].setSelectedItem(comboBoxAgentAll.getSelectedItem().toString()); } // AI search time for all if (textFieldThinkingTimeAll.isEnabled()) { try { double allSearchTimeValue = Double.valueOf(textFieldThinkingTimeAll.getText()).doubleValue(); if (allSearchTimeValue <= 0) allSearchTimeValue = 1.0; for (int i = 1; i <= Constants.MAX_PLAYERS; i++) playerThinkTimesArray[i].setSelectedItem(Double.valueOf(allSearchTimeValue)); } catch (final Exception E) { // invalid think time } } applyPlayerDetails(app, context); app.manager().settingsNetwork().backupAiPlayers(app.manager()); // clear and recreate the panels EventQueue.invokeLater(new Runnable() { @Override public void run() { DesktopApp.view().createPanels(); } }); dispose(); } }); playerPanel.setLayout(null); playerPanel.setPreferredSize(new Dimension(450, 320 + playerSectionHeight)); final JSeparator separator_3 = new JSeparator(); separator_3.setBounds(0, 116 + playerSectionHeight, 475, 8); playerPanel.add(separator_3); playerPanel.add(lblName); playerPanel.add(btnApply); playerPanel.add(lblAllPlayers); playerPanel.add(lblAgent); playerPanel.add(comboBoxAgentAll); playerPanel.add(textFieldThinkingTimeAll); playerPanel.add(lblThinkingTime); final JSeparator separator_4 = new JSeparator(); separator_4.setBounds(0, 216 + playerSectionHeight, 475, 8); playerPanel.add(separator_4); final JButton buttonResetPlayerNames = new JButton(""); buttonResetPlayerNames.setBounds(212, 242 + playerSectionHeight, 26, 23); playerPanel.add(buttonResetPlayerNames); buttonResetPlayerNames.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { for (int i = 1; i < app.manager().aiSelected().length; i++) { app.manager().aiSelected()[i].setName("Player " + i); playerNamesArray[i].setText("Player " + i); app.manager().aiSelected()[i].setThinkTime(1.0); final JSONObject json = new JSONObject().put("AI", new JSONObject() .put("algorithm", "Human") ); AIUtil.updateSelectedAI(app.manager(), json, i, "Human"); applyPlayerDetails(app, context); } createAndShowGUI(app); } }); if (app.manager().settingsNetwork().getActiveGameId() != 0) { comboBoxAgentAll.setEnabled(false); textFieldThinkingTimeAll.setEnabled(false); buttonResetPlayerNames.setEnabled(false); if (!app.manager().settingsNetwork().getOnlineAIAllowed()) btnApply.setEnabled(false); } final JLabel label = new JLabel("Reset Names to Defaults"); label.setFont(new Font("Dialog", Font.PLAIN, 14)); label.setBounds(29, 247 + playerSectionHeight, 192, 17); playerPanel.add(label); otherPanel = new JPanel(); //otherPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); final JScrollPane scroll2 = new JScrollPane(otherPanel); tabbedPane.addTab("Advanced", null, scroll2, null); final JComboBox<String> comboBox = new JComboBox<>(); comboBox.setBounds(320, 780, 124, 22); final JLabel lblPieceStyles = new JLabel("Piece Style"); lblPieceStyles.setBounds(30, 780, 155, 21); lblPieceStyles.setFont(new Font("Dialog", Font.BOLD, 14)); String[] pieceDesigns = context.game().metadata().graphics().pieceFamilies(); if (pieceDesigns == null) pieceDesigns = new String[0]; for (final String s : pieceDesigns) comboBox.addItem(s); if (!app.bridge().settingsVC().pieceFamily(context.game().name()).equals("")) comboBox.setSelectedItem(app.bridge().settingsVC().pieceFamily(context.game().name())); comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setPieceFamily(context.game().name(), comboBox.getSelectedItem().toString()); app.graphicsCache().clearAllCachedImages(); app.repaint(); } }); if (comboBox.getItemCount() == 0) comboBox.setEnabled(false); else comboBox.setEnabled(true); otherPanel.add(lblPieceStyles); otherPanel.add(comboBox); final JLabel lblMaximumNumberOfTurns = new JLabel("Maximum turn limit (per player)"); lblMaximumNumberOfTurns.setBounds(30, 40, 281, 19); lblMaximumNumberOfTurns.setFont(new Font("Dialog", Font.BOLD, 14)); lblMaximumNumberOfTurns.setToolTipText("<html>The maximum number of turns each player is allowed to make.<br>" + "If a player has had more turns than this value, the game is a draw for all remaining active players.</html>"); textFieldMaximumNumberOfTurns = new JTextField(); textFieldMaximumNumberOfTurns.setBounds(321, 40, 86, 20); textFieldMaximumNumberOfTurns.setColumns(10); // AlwaysAutoPass final JLabel lblAlwaysAutoPass = new JLabel("Auto Pass Stochastic Game"); lblAlwaysAutoPass.setFont(new Font("Dialog", Font.BOLD, 14)); lblAlwaysAutoPass.setBounds(30, 120, 227, 17); otherPanel.add(lblAlwaysAutoPass); final JCheckBox checkBoxAlwaysAutoPass = new JCheckBox("yes"); checkBoxAlwaysAutoPass.setSelected(false); checkBoxAlwaysAutoPass.setBounds(321, 120, 86, 23); otherPanel.add(checkBoxAlwaysAutoPass); // Coordinate outline final JLabel lblCoordOutline = new JLabel("Coordinate outline"); lblCoordOutline.setFont(new Font("Dialog", Font.BOLD, 14)); lblCoordOutline.setBounds(30, 160, 227, 17); otherPanel.add(lblCoordOutline); final JCheckBox checkBoxCoordOutline = new JCheckBox("yes"); checkBoxCoordOutline.setSelected(false); checkBoxCoordOutline.setBounds(321, 160, 86, 23); otherPanel.add(checkBoxCoordOutline); // Developer options final JLabel lblDevMode = new JLabel("Developer options"); lblDevMode.setBounds(30, 200, 227, 17); lblDevMode.setFont(new Font("Dialog", Font.BOLD, 14)); final JCheckBox checkBoxDevMode = new JCheckBox("yes"); checkBoxDevMode.setBounds(321, 200, 86, 23); // Hide AI moves final JLabel lblHideAiPieces = new JLabel("Hide AI moves"); lblHideAiPieces.setBounds(30, 240, 227, 17); lblHideAiPieces.setFont(new Font("Dialog", Font.BOLD, 14)); final JCheckBox radioButtonHideAiMoves = new JCheckBox("yes"); radioButtonHideAiMoves.setBounds(321, 240, 86, 23); radioButtonHideAiMoves.setSelected(true); // Show phase in title final JLabel lblShowPhase = new JLabel("Display phase in title"); lblShowPhase.setBounds(30, 820, 227, 17); lblShowPhase.setFont(new Font("Dialog", Font.BOLD, 14)); final JCheckBox rdbtnShowPhase = new JCheckBox("yes"); rdbtnShowPhase.setBounds(321, 820, 86, 23); rdbtnShowPhase.setSelected(app.settingsPlayer().showPhaseInTitle()); rdbtnShowPhase.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setShowPhaseInTitle(rdbtnShowPhase.isSelected()); app.updateFrameTitle(false); app.repaint(); } }); otherPanel.add(lblShowPhase); otherPanel.add(rdbtnShowPhase); // Movement animation final JLabel lblShowMovementAnimation = new JLabel("Movement animation"); lblShowMovementAnimation.setBounds(30, 280, 227, 17); lblShowMovementAnimation.setFont(new Font("Dialog", Font.BOLD, 14)); final String[] animationTypes = new String[] { "None", "Single", "All" }; final JComboBox<String> comboBoxMovementAnimation = new JComboBox<>(); comboBoxMovementAnimation.setBounds(321, 280, 86, 23); for (final String s : animationTypes) comboBoxMovementAnimation.addItem(s); for (int i = 0; i < animationTypes.length; i++) if (animationTypes[i].equals(app.settingsPlayer().animationType().name())) comboBoxMovementAnimation.setSelectedIndex(i); comboBoxMovementAnimation.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setAnimationType(AnimationVisualsType.valueOf(comboBoxMovementAnimation.getSelectedItem().toString())); } }); comboBoxMovementAnimation.setEnabled(true); // Moves use coordinates final JLabel lblMovesUseCoordinates = new JLabel("Moves use coordinates"); lblMovesUseCoordinates.setBounds(30, 320, 227, 17); lblMovesUseCoordinates.setFont(new Font("Dialog", Font.BOLD, 14)); final JCheckBox rdbtnMoveCoord = new JCheckBox("yes"); rdbtnMoveCoord.setBounds(321, 320, 86, 23); // Sound options final JLabel lblSoundEffectAfter = new JLabel("<html>Sound effect after AI or<br>network move</html>"); lblSoundEffectAfter.setBounds(30, 480, 227, 34); lblSoundEffectAfter.setFont(new Font("Dialog", Font.BOLD, 14)); final JCheckBox checkBoxSoundEffect = new JCheckBox("yes"); checkBoxSoundEffect.setBounds(321, 480, 86, 23); checkBoxSoundEffect.setSelected(false); // Move format final JLabel lblMoveFormat = new JLabel("Move Format"); lblMoveFormat.setBounds(30, 530, 227, 17); lblMoveFormat.setFont(new Font("Dialog", Font.BOLD, 14)); final EnumSet<MoveFormat> moveFormats = EnumSet.allOf( MoveFormat.class); final JComboBox<String> comboBoxFormat = new JComboBox<>(); comboBoxFormat.setBounds(321, 530, 86, 23); for (final MoveFormat format : moveFormats) comboBoxFormat.addItem(format.name()); comboBoxFormat.setSelectedItem(app.settingsPlayer().moveFormat().name()); comboBoxFormat.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setMoveFormat(MoveFormat.valueOf(comboBoxFormat.getSelectedItem().toString())); DesktopApp.view().tabPanel().page(TabView.PanelMoves).updatePage(context); } }); comboBoxFormat.setEnabled(true); final JLabel lblTabFontSize = new JLabel("Tab Font Size"); lblTabFontSize.setBounds(30, 580, 281, 19); lblTabFontSize.setFont(new Font("Dialog", Font.BOLD, 14)); lblTabFontSize.setToolTipText("<html>The font size for the text displayed in the tabs.<br>"); textFieldTabFontSize = new JTextField(); textFieldTabFontSize.setBounds(321, 580, 86, 20); textFieldTabFontSize.setColumns(10); textFieldTabFontSize.setText("" + app.settingsPlayer().tabFontSize()); textFieldTabFontSize.getDocument().addDocumentListener(documentListenerTabFontSize); final JLabel lblEditorFontSize = new JLabel("Editor Font Size"); lblEditorFontSize.setBounds(30, 620, 281, 19); lblEditorFontSize.setFont(new Font("Dialog", Font.BOLD, 14)); lblEditorFontSize.setToolTipText("<html>The font size for the text displayed in the editor.<br>"); textFieldEditorFontSize = new JTextField(); textFieldEditorFontSize.setBounds(321, 620, 86, 20); textFieldEditorFontSize.setColumns(10); textFieldEditorFontSize.setText("" + app.settingsPlayer().editorFontSize()); textFieldEditorFontSize.getDocument().addDocumentListener(documentListenerEditorFontSize); final JCheckBox checkBoxEditorAutocomplete = new JCheckBox("yes"); checkBoxEditorAutocomplete.setSelected(false); checkBoxEditorAutocomplete.setBounds(321, 660, 86, 23); otherPanel.add(checkBoxEditorAutocomplete); final JCheckBox checkBoxNetworkPolling = new JCheckBox("yes"); checkBoxNetworkPolling.setSelected(false); checkBoxNetworkPolling.setBounds(321, 700, 86, 23); otherPanel.add(checkBoxNetworkPolling); final JCheckBox checkBoxNetworkRefresh = new JCheckBox("yes"); checkBoxNetworkRefresh.setSelected(false); checkBoxNetworkRefresh.setBounds(321, 740, 86, 23); otherPanel.add(checkBoxNetworkRefresh); final JLabel labelSaveTrial = new JLabel("Save Trial After Moves"); labelSaveTrial.setFont(new Font("Dialog", Font.BOLD, 14)); labelSaveTrial.setBounds(30, 400, 227, 17); otherPanel.add(labelSaveTrial); final JCheckBox checkBoxSaveTrial = new JCheckBox("yes"); checkBoxSaveTrial.setSelected(true); checkBoxSaveTrial.setBounds(321, 400, 86, 23); otherPanel.add(checkBoxSaveTrial); final JLabel labelFlatBoard = new JLabel("Flat Board"); labelFlatBoard.setFont(new Font("Dialog", Font.BOLD, 14)); labelFlatBoard.setBounds(30, 440, 227, 17); otherPanel.add(labelFlatBoard); final JCheckBox checkBoxFlatBoard = new JCheckBox("yes"); checkBoxFlatBoard.setSelected(true); checkBoxFlatBoard.setBounds(321, 440, 86, 23); otherPanel.add(checkBoxFlatBoard); checkBoxDevMode.setSelected(app.settingsPlayer().devMode()); checkBoxDevMode.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setDevMode(checkBoxDevMode.isSelected()); app.resetMenuGUI(); app.repaint(); } }); checkBoxSoundEffect.setSelected(app.settingsPlayer().isMoveSoundEffect()); checkBoxSoundEffect.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setMoveSoundEffect(checkBoxSoundEffect.isSelected()); } }); checkBoxCoordOutline.setSelected(app.bridge().settingsVC().coordWithOutline()); checkBoxCoordOutline.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setCoordWithOutline(checkBoxCoordOutline.isSelected()); app.repaint(); } }); checkBoxAlwaysAutoPass.setSelected(app.manager().settingsManager().alwaysAutoPass()); checkBoxAlwaysAutoPass.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.manager().settingsManager().setAlwaysAutoPass(checkBoxAlwaysAutoPass.isSelected()); app.repaint(); } }); radioButtonHideAiMoves.setSelected(app.settingsPlayer().hideAiMoves()); radioButtonHideAiMoves.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setHideAiMoves(radioButtonHideAiMoves.isSelected()); } }); rdbtnMoveCoord.setSelected(app.settingsPlayer().isMoveCoord()); rdbtnMoveCoord.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setMoveCoord(rdbtnMoveCoord.isSelected()); app.updateTabs(context); } }); checkBoxSaveTrial.setSelected(app.settingsPlayer().saveTrialAfterMove()); checkBoxSaveTrial.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setSaveTrialAfterMove(checkBoxSaveTrial.isSelected()); } }); checkBoxFlatBoard.setSelected(app.bridge().settingsVC().flatBoard()); checkBoxFlatBoard.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.bridge().settingsVC().setFlatBoard(checkBoxFlatBoard.isSelected()); DesktopApp.view().createPanels(); app.repaint(); } }); checkBoxEditorAutocomplete.setSelected(app.settingsPlayer().editorAutocomplete()); checkBoxEditorAutocomplete.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setEditorAutocomplete(checkBoxEditorAutocomplete.isSelected()); } }); checkBoxNetworkPolling.setSelected(app.manager().settingsNetwork().longerNetworkPolling()); checkBoxNetworkPolling.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.manager().settingsNetwork().setLongerNetworkPolling(checkBoxNetworkPolling.isSelected()); } }); checkBoxNetworkRefresh.setSelected(app.manager().settingsNetwork().noNetworkRefresh()); checkBoxNetworkRefresh.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.manager().settingsNetwork().setNoNetworkRefresh(checkBoxNetworkRefresh.isSelected()); } }); textFieldTickLength = new JTextField(); textFieldTickLength.setText("0"); textFieldTickLength.setColumns(10); textFieldTickLength.setBounds(321, 76, 86, 20); otherPanel.add(textFieldTickLength); textFieldMaximumNumberOfTurns.setText("" + context.game().getMaxTurnLimit()); textFieldTickLength.setText("" + app.manager().settingsManager().tickLength()); otherPanel.setLayout(null); otherPanel.setPreferredSize(new Dimension(450, 850)); otherPanel.add(lblShowMovementAnimation); otherPanel.add(comboBoxMovementAnimation); otherPanel.add(lblDevMode); otherPanel.add(checkBoxDevMode); otherPanel.add(lblSoundEffectAfter); otherPanel.add(checkBoxSoundEffect); otherPanel.add(lblHideAiPieces); otherPanel.add(radioButtonHideAiMoves); otherPanel.add(lblMovesUseCoordinates); otherPanel.add(rdbtnMoveCoord); otherPanel.add(lblMaximumNumberOfTurns); otherPanel.add(textFieldMaximumNumberOfTurns); otherPanel.add(lblTabFontSize); otherPanel.add(textFieldTabFontSize); otherPanel.add(lblEditorFontSize); otherPanel.add(textFieldEditorFontSize); otherPanel.add(lblMoveFormat); otherPanel.add(comboBoxFormat); final JLabel tickLabel = new JLabel("Tick length (seconds)"); tickLabel.setToolTipText("<html>The maximum number of turns each player is allowed to make.<br>If a player has had more turns than this value, the game is a draw for all remaining active players.</html>"); tickLabel.setFont(new Font("Dialog", Font.BOLD, 14)); tickLabel.setBounds(30, 76, 281, 19); otherPanel.add(tickLabel); final JLabel lblEditorAutocomplete = new JLabel("Editor Autocomplete"); lblEditorAutocomplete.setToolTipText("<html>The font size for the text displayed in the editor.<br>"); lblEditorAutocomplete.setFont(new Font("Dialog", Font.BOLD, 14)); lblEditorAutocomplete.setBounds(30, 660, 281, 19); otherPanel.add(lblEditorAutocomplete); final JLabel lblNetworkPolling = new JLabel("Network Less frequent polling"); lblNetworkPolling.setToolTipText("<html>Poll the Ludii server less often when logged in. Good for poor network connections<br>"); lblNetworkPolling.setFont(new Font("Dialog", Font.BOLD, 14)); lblNetworkPolling.setBounds(30, 700, 281, 19); otherPanel.add(lblNetworkPolling); final JLabel lblNetworkRefresh = new JLabel("Network disable auto-refresh"); lblNetworkRefresh.setToolTipText("<html>Do not auto-refresh the network dialog.<br>"); lblNetworkRefresh.setFont(new Font("Dialog", Font.BOLD, 14)); lblNetworkRefresh.setBounds(30, 740, 281, 19); otherPanel.add(lblNetworkRefresh); textFieldMaximumNumberOfTurns.getDocument().addDocumentListener(documentListenerMaxTurns); textFieldTickLength.getDocument().addDocumentListener(documentListenerTickLength); if (app.manager().settingsNetwork().getActiveGameId() != 0) { textFieldMaximumNumberOfTurns.setEnabled(false); } } //------------------------------------------------------------------------- /** * Called for every player * * @param playerJpanel * @param playerId * @param context */ static void addPlayerDetails(final PlayerApp app, final JPanel playerJpanel, final int playerId, final Context context) { // Player Labels (fixed) final int maxNameLength = 21; final JLabel lblPlayer_1 = new JLabel("Player " + playerId); lblPlayer_1.setBounds(20, 49 + playerId*30, 74, 14); playerJpanel.add(lblPlayer_1); // Player Names final JTextField textFieldPlayerName1 = new JTextField(); textFieldPlayerName1.setBounds(100, 46 + playerId*30, 130, 20); final MaxLengthTextDocument maxLength1 = new MaxLengthTextDocument(); maxLength1.setMaxChars(maxNameLength); textFieldPlayerName1.setDocument(maxLength1); textFieldPlayerName1.setEnabled(true); textFieldPlayerName1.setText(app.manager().aiSelected()[playerId].name()); playerJpanel.add(textFieldPlayerName1); // AI Algorithm final AIDetails associatedAI = app.manager().aiSelected()[playerId]; final String[] comboBoxContents = DesktopGUIUtil.getAIDropdownStrings(app, true).toArray(new String[DesktopGUIUtil.getAIDropdownStrings(app, true).size()]); final JComboBox<String> myComboBox = new JComboBox<String>(comboBoxContents); //comboBoxContents myComboBox.setBounds(240, 46 + playerId*30, 100, 20); if (!myComboBox.getSelectedItem().equals(associatedAI.menuItemName())) myComboBox.setSelectedItem(associatedAI.menuItemName()); playerJpanel.add(myComboBox); // AI think time final String[] comboBoxContentsThinkTime = {"1s", "2s", "3s", "5s", "10s", "30s", "60s", "120s", "180s", "240s", "300s"}; final JComboBox<String> myComboBoxThinkTime = new JComboBox<String>(comboBoxContentsThinkTime); //comboBoxContentsThinkTime myComboBoxThinkTime.setBounds(350, 46 + playerId*30, 60, 20); myComboBoxThinkTime.setEditable(true); final DecimalFormat format = new DecimalFormat("0.#"); myComboBoxThinkTime.setSelectedItem(String.valueOf(format.format(associatedAI.thinkTime())) + "s"); playerJpanel.add(myComboBoxThinkTime); // Hide boxes for players not in this game. if (context.game().players().count() < playerId) { textFieldPlayerName1.setVisible(false); lblPlayer_1.setVisible(false); myComboBoxThinkTime.setVisible(false); myComboBox.setVisible(false); } // Hide certain details if this is a network game. if (app.manager().settingsNetwork().getActiveGameId() != 0) { textFieldPlayerName1.setEnabled(false); if (!app.manager().settingsNetwork().getOnlineAIAllowed() || playerId != app.manager().settingsNetwork().getNetworkPlayerNumber()) { myComboBoxThinkTime.setEnabled(false); myComboBox.setEnabled(false); } } // Save selected entries. playerNamesArray[playerId] = textFieldPlayerName1; playerAgentsArray[playerId] = myComboBox; playerThinkTimesArray[playerId] = myComboBoxThinkTime; } //------------------------------------------------------------------------- /** * Applies the selected details for the players * @param context */ static void applyPlayerDetails(final PlayerApp app, final Context context) { for (int i = 1; i < playerNamesArray.length; i++) { // Player Names final String name = playerNamesArray[i].getText(); if (name != null) app.manager().aiSelected()[i].setName(name); else app.manager().aiSelected()[i].setName(""); // Think time String comboBoxThinkTime = playerThinkTimesArray[i].getSelectedItem().toString(); if (comboBoxThinkTime.toLowerCase().charAt(comboBoxThinkTime.length()-1) == 's') comboBoxThinkTime = comboBoxThinkTime.substring(0, comboBoxThinkTime.length()-1); double thinkTime = 0.0; try { thinkTime = Double.valueOf(comboBoxThinkTime.toString()).doubleValue(); } catch (final Exception e2) { System.out.println("Invalid think time: " + comboBoxThinkTime.toString()); } if (thinkTime <= 0) thinkTime = 1; app.manager().aiSelected()[i].setThinkTime(thinkTime); // AI agent final JSONObject json = new JSONObject().put("AI", new JSONObject() .put("algorithm", playerAgentsArray[i].getSelectedItem().toString()) ); AIUtil.updateSelectedAI(app.manager(), json, i, playerAgentsArray[i].getSelectedItem().toString()); // Need to initialise the AI if "Ludii AI" selected, so we can get the algorithm name. if (playerAgentsArray[i].getSelectedItem().toString().equals("Ludii AI")) app.manager().aiSelected()[i].ai().initIfNeeded(app.contextSnapshot().getContext(app).game(), i); } app.manager().settingsNetwork().backupAiPlayers(app.manager()); } }
33,240
32.747208
209
java