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
MicroRTS
MicroRTS-master/src/ai/synthesis/runners/cleanAST/PerformCleanerAST.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.synthesis.runners.cleanAST; import ai.abstraction.HeavyRush; import ai.abstraction.LightRush; import ai.abstraction.RangedRush; import ai.abstraction.WorkerRush; import ai.core.AI; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCompiler.IDSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCompiler.MainDSLCompiler; import ai.synthesis.dslForScriptGenerator.DslAI; import ai.synthesis.grammar.dslTree.builderDSLTree.BuilderDSLTreeSingleton; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import ai.synthesis.grammar.dslTree.utils.ReduceDSLController; import ai.synthesis.grammar.dslTree.utils.SerializableController; import gui.PhysicalGameStatePanel; import java.awt.event.WindowEvent; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens */ public class PerformCleanerAST { //Smart Evaluation Settings static String initialState; private final static int CYCLES_LIMIT = 200; public static void main(String[] args) { BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); // Create a file chooser final JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(System.getProperty("user.home"))); int result = fc.showOpenDialog(new JDialog()); long start = System.nanoTime(); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); System.out.println("Selected file: " + selectedFile.getAbsolutePath()); iDSL rec = SerializableController.recoverySerializable(selectedFile.getName(), selectedFile.getAbsolutePath().replace(selectedFile.getName(), "")); System.out.println("Selected AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); try { //perform cleaning run_clean_ast(rec); System.out.println("Cleaned AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); } catch (Exception ex) { Logger.getLogger(PerformCleanerAST.class.getName()).log(Level.SEVERE, null, ex); } } long elapsedTime = System.nanoTime() - start; System.out.println("Time elapsed:" + elapsedTime); System.exit(0); } private static void run_clean_ast(iDSL rec) throws Exception { String map = "maps/8x8/basesWorkers8x8A.xml"; UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load(map, utt); //printMatchDetails(sIA1,sIA2,map); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 4000; int PERIOD = 20; boolean gameover = false; if (pgs.getHeight() == 8) { MAXCYCLES = 3000; } if (pgs.getHeight() == 16) { MAXCYCLES = 5000; //MAXCYCLES = 1000; } if (pgs.getHeight() == 24) { MAXCYCLES = 6000; } if (pgs.getHeight() == 32) { MAXCYCLES = 7000; } if (pgs.getHeight() == 64) { MAXCYCLES = 12000; } AI ai = buildCommandsIA(utt, rec); List<AI> bot_ais; bot_ais = new ArrayList(Arrays.asList(new AI[]{ new WorkerRush(utt), // new HeavyRush(utt), // new RangedRush(utt), // new LightRush(utt), //new botEmptyBase(utt, "for(u) (train(Worker,8,EnemyDir) train(Heavy,6,Left) if(HaveUnitsToDistantToEnemy(Worker,7,u)) (train(Worker,1,Up)) (harvest(3,u))) for(u) (if(HaveQtdUnitsAttacking(Heavy,9)) (attack(Heavy,mostHealthy,u)) (attack(Worker,closest,u)))", "script1") //new NaiveMCTS(utt), // //new PuppetSearchMCTS(utt), //new SCVPlus(utt) //new StrategyTactics(utt),//, //new A3NNoWait(100, -1, 100, 8, 0.3F, 0.0F, 0.4F, 0, new RandomBiasedAI(utt), // new SimpleSqrtEvaluationFunction3(), true, utt, "ManagerClosestEnemy", 3, // decodeScripts(utt, "0;"), "A3N") })); for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, ai, bot_ai, map, utt, PERIOD); } for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, bot_ai, ai, map, utt, PERIOD); } ReduceDSLController.removeUnactivatedParts(rec, new ArrayList<>(((DslAI) ai).getCommands())); } private static AI buildCommandsIA(UnitTypeTable utt, iDSL code) { IDSLCompiler compiler = new MainDSLCompiler(); HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsDSL = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsDSL, "P1", code, counterByFunction); return aiscript; } private static void run_match(int MAXCYCLES, AI ai1, AI ai2, String map, UnitTypeTable utt, int PERIOD) throws Exception { System.out.println(ai1 + " " + ai2); boolean gameover = false; PhysicalGameState pgs = PhysicalGameState.load(map, utt); GameState gs = new GameState(pgs, utt); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; JFrame w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); do { if (System.currentTimeMillis() >= nextTimeToUpdate) { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: if (smartEvaluationForStop(gs)) { gameover = true; }else{ gameover = gs.cycle(); } w.repaint(); nextTimeToUpdate += PERIOD; } else { try { Thread.sleep(1); } catch (Exception e) { System.err.println("ai.synthesis.runners.roundRobinLocal.RoundRobinGrammarAgainstGrammar.run() " + e.getMessage()); } } } while (!gameover && (gs.getTime() <= MAXCYCLES)); System.out.println("Winner: "+ gs.winner()); w.dispatchEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING)); } private static boolean smartEvaluationForStop(GameState gs) { if (gs.getTime() == 0) { String cleanState = cleanStateInformation(gs); initialState = cleanState; } else if (gs.getTime() % CYCLES_LIMIT == 0) { String cleanState = cleanStateInformation(gs); if(cleanState.equals(initialState)){ //System.out.println("** Smart Stop activate.\n Original state =\n"+initialState+ // " verified same state at \n"+cleanState); return true; }else{ initialState = cleanState; } } return false; } private static String cleanStateInformation(GameState gs) { String sGame = gs.toString().replace("\n", ""); sGame = sGame.substring(sGame.indexOf("PhysicalGameState:")); sGame = sGame.replace("PhysicalGameState:", "").trim(); return sGame; } }
8,080
38.612745
282
java
MicroRTS
MicroRTS-master/src/ai/synthesis/runners/cleanAST/PerformCleanerASTOptim.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.synthesis.runners.cleanAST; import ai.core.AI; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCompiler.IDSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCompiler.MainDSLCompiler; import ai.synthesis.dslForScriptGenerator.DslAI; import ai.synthesis.grammar.dslTree.BooleanDSL; import ai.synthesis.grammar.dslTree.CDSL; import ai.synthesis.grammar.dslTree.CommandDSL; import ai.synthesis.grammar.dslTree.EmptyDSL; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S5DSL; import ai.synthesis.grammar.dslTree.builderDSLTree.BuilderDSLTreeSingleton; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import ai.synthesis.grammar.dslTree.utils.ReduceDSLController; import ai.synthesis.grammar.dslTree.utils.SerializableController; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JFileChooser; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens */ public class PerformCleanerASTOptim { //Smart Evaluation Settings static String initialState; private final static int CYCLES_LIMIT = 200; public static void main(String[] args) { BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); // Create a file chooser final JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(System.getProperty("user.home"))); int result = fc.showOpenDialog(new JDialog()); long start = System.nanoTime(); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); System.out.println("Selected file: " + selectedFile.getAbsolutePath()); iDSL rec = SerializableController.recoverySerializable(selectedFile.getName(), selectedFile.getAbsolutePath().replace(selectedFile.getName(), "")); System.out.println("Selected AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); try { //perform cleaning run_clean_ast(rec); System.out.println("Cleaned AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); } catch (Exception ex) { Logger.getLogger(PerformCleanerASTOptim.class.getName()).log(Level.SEVERE, null, ex); } } long elapsedTime = System.nanoTime() - start; System.out.println("Time elapsed:" + elapsedTime); System.exit(0); } private static void run_clean_ast(iDSL rec) throws Exception { String map = "maps/8x8/basesWorkers8x8A.xml"; UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load(map, utt); //printMatchDetails(sIA1,sIA2,map); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 4000; int PERIOD = 20; boolean gameover = false; if (pgs.getHeight() == 8) { MAXCYCLES = 3000; } if (pgs.getHeight() == 16) { MAXCYCLES = 5000; //MAXCYCLES = 1000; } if (pgs.getHeight() == 24) { MAXCYCLES = 6000; } if (pgs.getHeight() == 32) { MAXCYCLES = 7000; } if (pgs.getHeight() == 64) { MAXCYCLES = 12000; } AI ai = buildCommandsIA(utt, rec); EmptyDSL empty = new EmptyDSL(); // comandos CommandDSL c1 = new CommandDSL("harvest(1)"); CommandDSL c2 = new CommandDSL("train(Worker,50,EnemyDir)"); CommandDSL c3 = new CommandDSL("attack(Worker,closest)"); // booleanos BooleanDSL b1 = new BooleanDSL("HaveUnitsToDistantToEnemy(Worker,3)"); //Cs CDSL C1 = new CDSL(c1); CDSL C2 = new CDSL(c2); CDSL C3 = new CDSL(c3); //S5 S5DSL S5 = new S5DSL(b1); //S2 S2DSL S2 = new S2DSL(S5, C3); //S1 S1DSL S13 = new S1DSL(S2, new S1DSL(empty)); S1DSL S12 = new S1DSL(C2, S13); // Raiz iDSL ScrI = new S1DSL(C1, S12); System.out.println(ScrI.translate()); BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) ScrI); List<AI> bot_ais; bot_ais = new ArrayList(Arrays.asList(new AI[]{ // new WorkerRush(utt), // new HeavyRush(utt), // new RangedRush(utt), // new LightRush(utt), // new botEmptyBase(utt, "harvest(4) build(Barrack,2,Down) train(Worker,100,EnemyDir) " // + "attack(Worker,closest) attack(Light,closest) train(Ranged,100,EnemyDir) " // + "attack(Ranged,closest)", "script1") buildCommandsIA2(utt, ScrI) //new NaiveMCTS(utt), // //new PuppetSearchMCTS(utt), //new SCVPlus(utt) //new StrategyTactics(utt),//, //new A3NNoWait(100, -1, 100, 8, 0.3F, 0.0F, 0.4F, 0, new RandomBiasedAI(utt), // new SimpleSqrtEvaluationFunction3(), true, utt, "ManagerClosestEnemy", 3, // decodeScripts(utt, "0;"), "A3N") })); int lim = 2; for (int i = 0; i < lim; i++) { for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, ai, bot_ai, map, utt, PERIOD, gs.clone()); } for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, bot_ai, ai, map, utt, PERIOD, gs.clone()); } } ReduceDSLController.removeUnactivatedParts(rec, new ArrayList<>(((DslAI) ai).getCommands())); System.out.println(rec.translate()); ai = buildCommandsIA(utt, rec); for (int i = 0; i < lim; i++) { for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, ai, bot_ai, map, utt, PERIOD, gs.clone()); } for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, bot_ai, ai, map, utt, PERIOD, gs.clone()); } } } private static AI buildCommandsIA(UnitTypeTable utt, iDSL code) { IDSLCompiler compiler = new MainDSLCompiler(); HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsDSL = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsDSL, "P1", code, counterByFunction); return aiscript; } private static AI buildCommandsIA2(UnitTypeTable utt, iDSL code) { IDSLCompiler compiler = new MainDSLCompiler(); HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsDSL = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsDSL, "P_Init", code, counterByFunction); return aiscript; } private static void run_match(int MAXCYCLES, AI ai1, AI ai2, String map, UnitTypeTable utt, int PERIOD, GameState gs) throws Exception { System.out.println(ai1 + " " + ai2); boolean gameover = false; //JFrame w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); do { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: if (smartEvaluationForStop(gs)) { gameover = true; } else { gameover = gs.cycle(); } //w.repaint(); } while (!gameover && (gs.getTime() <= MAXCYCLES)); System.out.println("Winner: " + gs.winner()); } private static boolean smartEvaluationForStop(GameState gs) { if (gs.getTime() == 0) { String cleanState = cleanStateInformation(gs); initialState = cleanState; } else if (gs.getTime() % CYCLES_LIMIT == 0) { String cleanState = cleanStateInformation(gs); if (cleanState.equals(initialState)) { //System.out.println("** Smart Stop activate.\n Original state =\n"+initialState+ // " verified same state at \n"+cleanState); return true; } else { initialState = cleanState; } } return false; } private static String cleanStateInformation(GameState gs) { String sGame = gs.toString().replace("\n", ""); sGame = sGame.substring(sGame.indexOf("PhysicalGameState:")); sGame = sGame.replace("PhysicalGameState:", "").trim(); return sGame; } }
9,322
38.504237
140
java
MicroRTS
MicroRTS-master/src/ai/synthesis/runners/cleanAST/SimpleTest.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.synthesis.runners.cleanAST; import ai.core.AI; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCompiler.IDSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCompiler.MainDSLCompiler; import ai.synthesis.dslForScriptGenerator.DslAI; import ai.synthesis.grammar.dslTree.BooleanDSL; import ai.synthesis.grammar.dslTree.CDSL; import ai.synthesis.grammar.dslTree.CommandDSL; import ai.synthesis.grammar.dslTree.EmptyDSL; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S5DSL; import ai.synthesis.grammar.dslTree.S5DSLEnum; import ai.synthesis.grammar.dslTree.builderDSLTree.BuilderDSLTreeSingleton; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import ai.synthesis.grammar.dslTree.utils.ReduceDSLController; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens */ public class SimpleTest { //Smart Evaluation Settings static String initialState; private final static int CYCLES_LIMIT = 200; public static void main(String[] args) { BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); long start = System.nanoTime(); EmptyDSL empty = new EmptyDSL(); // comandos CommandDSL c1 = new CommandDSL("harvest(1)"); CommandDSL c2 = new CommandDSL("train(Worker,50,EnemyDir)"); CommandDSL c3 = new CommandDSL("attack(Worker,closest)"); // booleanos BooleanDSL b1 = new BooleanDSL("HaveUnitsToDistantToEnemy(Worker,3)"); //Cs CDSL C1 = new CDSL(c1); CDSL C2 = new CDSL(c2); CDSL C3 = new CDSL(c3); //S5 S5DSL S5 = new S5DSL(S5DSLEnum.NOT, b1); //S2 S2DSL S2 = new S2DSL(S5, C3); //S1 S1DSL S13 = new S1DSL(S2, new S1DSL(empty)); S1DSL S12 = new S1DSL(C2, S13); // Raiz iDSL rec = new S1DSL(C1, S12); System.out.println("Selected AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); try { //perform cleaning run_clean_ast(rec); System.out.println("Cleaned AST:" + rec.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) rec); } catch (Exception ex) { Logger.getLogger(SimpleTest.class.getName()).log(Level.SEVERE, null, ex); } long elapsedTime = System.nanoTime() - start; System.out.println("Time elapsed:" + elapsedTime); System.exit(0); } private static void run_clean_ast(iDSL rec) throws Exception { String map = "maps/8x8/basesWorkers8x8A.xml"; System.out.println(map); UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load(map, utt); //printMatchDetails(sIA1,sIA2,map); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 4000; int PERIOD = 20; boolean gameover = false; if (pgs.getHeight() == 8) { MAXCYCLES = 3000; } if (pgs.getHeight() == 16) { MAXCYCLES = 5000; //MAXCYCLES = 1000; } if (pgs.getHeight() == 24) { MAXCYCLES = 6000; } if (pgs.getHeight() == 32) { MAXCYCLES = 7000; } if (pgs.getHeight() == 64) { MAXCYCLES = 12000; } TradutorDSL td = new TradutorDSL("(ε) for(u) ((ε) attack(Ranged,closest,u) attack(Heavy,closest,u)) (ε) (ε) if(HaveQtdUnitsbyType(Ranged,4)) then((ε))"); TradutorDSL td2 = new TradutorDSL("for(u) (train(Worker,50,Up,u) harvest(50,u) moveToUnit(Ranged,Enemy,strongest,u) if(HaveQtdUnitsbyType(Worker,5,u)) then(train(Ranged,50,Right,u)) (ε)) for(u) (if(HaveQtdEnemiesbyType(Heavy,7,u)) then((ε)) else(attack(Ranged,mostHealthy,u))) for(u) (if(HaveQtdUnitsbyType(Heavy,15,u)) then((ε)) else(build(Barrack,50,Up,u)) if(HaveQtdEnemiesbyType(Ranged,17,u)) then((ε)))"); rec = td.getAST(); AI ai = buildCommandsIA(utt, rec); EmptyDSL empty = new EmptyDSL(); // comandos CommandDSL c1 = new CommandDSL("harvest(1)"); CommandDSL c2 = new CommandDSL("train(Worker,50,EnemyDir)"); CommandDSL c3 = new CommandDSL("attack(Worker,closest)"); // booleanos BooleanDSL b1 = new BooleanDSL("HaveUnitsToDistantToEnemy(Worker,3)"); //Cs CDSL C1 = new CDSL(c1); CDSL C2 = new CDSL(c2); CDSL C3 = new CDSL(c3); //S5 S5DSL S5 = new S5DSL(b1); //S2 S2DSL S2 = new S2DSL(S5, C3); //S1 S1DSL S13 = new S1DSL(S2, new S1DSL(empty)); S1DSL S12 = new S1DSL(C2, S13); // Raiz iDSL ScrI = new S1DSL(C1, S12); ScrI = td2.getAST(); System.out.println(ScrI.translate()); BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) ScrI); int val = BuilderDSLTreeSingleton.getNumberofNodes((iNodeDSLTree) ScrI); HashSet<iNodeDSLTree> test = BuilderDSLTreeSingleton.getAllNodes((iNodeDSLTree) ScrI); List<AI> bot_ais; bot_ais = new ArrayList(Arrays.asList(new AI[]{ // new WorkerRush(utt), // new HeavyRush(utt), // new RangedRush(utt), // new LightRush(utt), // new botEmptyBase(utt, "harvest(4) build(Barrack,2,Down) train(Worker,100,EnemyDir) " // + "attack(Worker,closest) attack(Light,closest) train(Ranged,100,EnemyDir) " // + "attack(Ranged,closest)", "script1") buildCommandsIA2(utt, ScrI) //new NaiveMCTS(utt), // //new PuppetSearchMCTS(utt), //new SCVPlus(utt) //new StrategyTactics(utt),//, //new A3NNoWait(100, -1, 100, 8, 0.3F, 0.0F, 0.4F, 0, new RandomBiasedAI(utt), // new SimpleSqrtEvaluationFunction3(), true, utt, "ManagerClosestEnemy", 3, // decodeScripts(utt, "0;"), "A3N") })); int lim = 2; for (int i = 0; i < lim; i++) { for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, ai, bot_ai, map, utt, PERIOD, gs.clone()); } for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, bot_ai, ai, map, utt, PERIOD, gs.clone()); } } ReduceDSLController.removeUnactivatedParts(rec, new ArrayList<>(((DslAI) ai).getCommands())); System.out.println(rec.translate()); ai = buildCommandsIA(utt, rec); for (int i = 0; i < lim; i++) { for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, ai, bot_ai, map, utt, PERIOD, gs.clone()); } for (AI bot_ai : bot_ais) { run_match(MAXCYCLES, bot_ai, ai, map, utt, PERIOD, gs.clone()); } } } private static AI buildCommandsIA(UnitTypeTable utt, iDSL code) { IDSLCompiler compiler = new MainDSLCompiler(); HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsDSL = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsDSL, "P1", code, counterByFunction); return aiscript; } private static AI buildCommandsIA2(UnitTypeTable utt, iDSL code) { IDSLCompiler compiler = new MainDSLCompiler(); HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsDSL = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsDSL, "P_Init", code, counterByFunction); return aiscript; } private static void run_match(int MAXCYCLES, AI ai1, AI ai2, String map, UnitTypeTable utt, int PERIOD, GameState gs) throws Exception { System.out.println(ai1 + " " + ai2); boolean gameover = false; //JFrame w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); do { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: if (smartEvaluationForStop(gs)) { gameover = true; } else { gameover = gs.cycle(); } //w.repaint(); } while (!gameover && (gs.getTime() <= MAXCYCLES)); System.out.println("Winner: " + gs.winner()); } private static boolean smartEvaluationForStop(GameState gs) { if (gs.getTime() == 0) { String cleanState = cleanStateInformation(gs); initialState = cleanState; } else if (gs.getTime() % CYCLES_LIMIT == 0) { String cleanState = cleanStateInformation(gs); if (cleanState.equals(initialState)) { //System.out.println("** Smart Stop activate.\n Original state =\n"+initialState+ // " verified same state at \n"+cleanState); return true; } else { initialState = cleanState; } } return false; } private static String cleanStateInformation(GameState gs) { String sGame = gs.toString().replace("\n", ""); sGame = sGame.substring(sGame.indexOf("PhysicalGameState:")); sGame = sGame.replace("PhysicalGameState:", "").trim(); return sGame; } }
10,140
39.242063
418
java
MicroRTS
MicroRTS-master/src/ai/synthesis/runners/cleanAST/TradutorDSL.java
package ai.synthesis.runners.cleanAST; import java.util.LinkedList; import java.util.Queue; import ai.synthesis.grammar.dslTree.BooleanDSL; import ai.synthesis.grammar.dslTree.CDSL; import ai.synthesis.grammar.dslTree.CommandDSL; import ai.synthesis.grammar.dslTree.EmptyDSL; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S3DSL; import ai.synthesis.grammar.dslTree.S4DSL; import ai.synthesis.grammar.dslTree.S5DSL; import ai.synthesis.grammar.dslTree.S5DSLEnum; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; //Tradutor de string pro formato ast //Não verifica se o script foi escrito corretamente public class TradutorDSL { String scriptOriginal; iDSL astScript; Queue<String> filaRaiz = new LinkedList<>(); public TradutorDSL(String s) { this.scriptOriginal = s; createDSL(); } private void createDSL() { this.filaRaiz = createFila(this.scriptOriginal); //EmptyDSL empty = new EmptyDSL(); //System.out.println("Fila raiz: " + this.filaRaiz + "\n"); if(this.filaRaiz.peek() == null) { //System.out.println("Fila raiz: " + this.filaRaiz.peek() + "."); astScript = new S1DSL(new EmptyDSL()); } String topoRaiz = ""; String proximo = ""; //for(int i = 0; i < this.filaRaiz.size(); i++) { topoRaiz = this.filaRaiz.remove(); proximo = this.filaRaiz.peek(); //System.out.println("PRÓXIMO: " + proximo); if(topoRaiz.startsWith("if")) { //System.out.println("S1 <--- S2 S1"); //this.astScript = new S1DSL(createS2(topoRaiz), createS1q(this.filaRaiz)); //this.astScript = createS2q(topoRaiz, this.filaRaiz); if(proximo != null) if(proximo.startsWith("else") && proximo.endsWith(")")) proximo = this.filaRaiz.remove(); this.astScript = new S1DSL(createS2(topoRaiz, proximo), createS1q(this.filaRaiz)); } else if(topoRaiz.startsWith("for")) { //System.out.println("S1 <--- S3 S1"); //this.astScript = new S1DSL(createS3(topoRaiz), createS1q(this.filaRaiz)); //this.astScript = createS3q(topoRaiz, this.filaRaiz); this.astScript = new S1DSL(createS3(topoRaiz), createS1q(this.filaRaiz)); } else { //System.out.println("filaRaiz = " + this.filaRaiz); //System.out.println("Raiz: S1 <--- C S1"); //if(this.filaRaiz != null) this.astScript = new S1DSL(createC(createFila(topoRaiz)), createS1q(this.filaRaiz)); //this.astScript = new S1DSL(createC(createFila(topoRaiz))); } //} //System.out.println("S1 <--- empty"); //System.out.println("============ AST Resultado =============="); //System.out.println(this.astScript.translate()); //System.out.println("========================================="); } private S2DSL createS2(String topo, String proximo) { topo = topo.trim(); if(proximo != null) proximo = proximo.trim(); Queue<String> filaThen = new LinkedList<>(); Queue<String> filaElse = new LinkedList<>(); //System.out.println("\nCreateS2 Sendo implementada"); //System.out.println("--- Topo: " + topo); //System.out.println("--- Próximo: " + proximo); String[] arrFila = topo.split(" "); //bzinho String bzinho = arrFila[0]; bzinho = bzinho.substring(3, bzinho.length()-1); //Retira parênteses do if if(arrFila.length == 2) { //System.out.println("Só há um comando then"); filaThen.add(arrFila[1].substring(5, arrFila[1].length()-1)); //System.out.println("Fila then: " + filaThen); } else { arrFila[1] = arrFila[1].substring(5, arrFila[1].length()); arrFila[arrFila.length-1] = arrFila[arrFila.length-1].substring(0, arrFila[arrFila.length-1].length()-1); //System.out.println("primeiro comando do if: " + arrFila[1]); //System.out.println("último comando do if: " + arrFila[arrFila.length-1]); //Separa comandos then dos comandos else for(int i = 1; i < arrFila.length; i++) { //if(arrFila[i].startsWith("(")) { // System.out.println("é o conjunto de comandos else: " + arrFila[i]); //} else { //System.out.println("é um comando then: " + arrFila[i]); filaThen.add(arrFila[i]); //System.out.println("Fila then: " + filaThen); //} } } if(proximo != null) if(!proximo.isEmpty() && proximo.startsWith("else(")) { proximo = proximo.trim(); proximo = proximo.substring(5, proximo.length()-1); //System.out.println("--- proximo antes de virar fila: " + proximo); filaElse = createFila(proximo); //System.out.println("Fila else: " + filaElse); } //System.out.println("=== B"); //System.out.println("bzinho: " + bzinho); //System.out.println("{then}: " + filaThen); //System.out.println("{else}: " + filaElse); if(filaElse.isEmpty()) return new S2DSL(createS5(bzinho), createC(filaThen)); return new S2DSL(createS5(bzinho), createC(filaThen), createC(filaElse)); } private S5DSL createS5(String bzinho) { if(bzinho.contains("!")) { bzinho = bzinho.substring(1, bzinho.length()); return new S5DSL(S5DSLEnum.NOT, new BooleanDSL(bzinho)); } return new S5DSL(new BooleanDSL(bzinho)); } private CDSL createC(Queue<String> fila) { //System.out.println("\nCreateC Sendo implementada"); //System.out.println("Fila do C: " + fila); // ... <-- C <-- c if(fila.size() == 1) { //System.out.println("fim dessa linha do c"); //if(fila.peek().contains("ε")) return new CDSL(new EmptyDSL()); String command = fila.peek(); //System.out.println(command); if(fila.peek().contains("(e)")) return new CDSL(new EmptyDSL()); return new CDSL(new CommandDSL(fila.remove())); } if(fila.size() > 1) { //System.out.println("C <--- C c"); String c = fila.remove(); return new CDSL(new CommandDSL(c), createC(fila)); } //return new CDSL(new EmptyDSL()); return null; } private S3DSL createS3(String topo) { String[] arrFila = topo.split(" "); String fila = ""; for(int i = 1; i < arrFila.length; i++) fila += " " + arrFila[i]; //System.out.println("CreateS3 Sendo implementada"); //System.out.println("==== FOR"); //System.out.println("For completo: " + topo); //System.out.println("For retirado: " + arrFila[0]); fila = fila.trim(); fila = fila.substring(1, fila.length()-1); Queue<String> filaS4 = createFila(fila); //System.out.println("{S4}: " + filaS4); return new S3DSL(createS4(filaS4)); } private S4DSL createS4(Queue<String> filaS4) { String topo = ""; String proximo = ""; if(filaS4.isEmpty()) { //return new S4DSL(new EmptyDSL()); return null; } if(!filaS4.isEmpty()) { topo = filaS4.remove(); proximo = filaS4.peek(); //System.out.println("Próximo comando: " + proximo); } //System.out.println("CreateS4 Sendo implementada"); if(topo.startsWith("if")) { //System.out.println("S4 <--- S2 S4"); if(proximo != null) if(proximo.startsWith("else(") && proximo.endsWith(")")) proximo = filaS4.remove(); return new S4DSL(createS2(topo, proximo), createS4(filaS4)); } if(!filaS4.isEmpty()) return new S4DSL(createC(createFila(topo)), createS4(filaS4)); if(filaS4.isEmpty() && !topo.isEmpty()) return new S4DSL(createC(createFila(topo))); //return new S4DSL(new EmptyDSL()); return null; } private S1DSL createS1q(Queue<String> fila) { //System.out.println("\nCreateS1 Fila Sendo implementada"); String topo = ""; String proximo = ""; //System.out.println("Fila do S1: " + fila); if(!fila.isEmpty()) { topo = fila.remove(); proximo = fila.peek(); //System.out.println("Topo: " + topo); //System.out.println("Próximo comando: " + proximo); } if(topo.startsWith("if")) { //System.out.println("S1 <--- S2 S1"); if(proximo != null) if(proximo.startsWith("else(") && proximo.endsWith(")")) proximo = fila.remove(); return new S1DSL(createS2(topo, proximo), createS1q(fila)); } else if(topo.startsWith("for")) { //System.out.println("S1 <--- S3 S1"); return new S1DSL(createS3(topo), createS1q(fila)); } else if(!fila.isEmpty()){ //System.out.println("S1 <--- C S1"); return new S1DSL(createC(createFila(topo)), createS1q(fila)); } else if(fila.isEmpty() && !topo.isEmpty()) { //System.out.println("S1 <--- C empty"); return new S1DSL(createC(createFila(topo))); //return new S1DSL(createC(createFila(topo)), new EmptyDSL()); } //System.out.println("S1 <--- empty"); return null; //return new S1DSL(new EmptyDSL()); } // Retorna fila do trecho fornecido, separando comandos comuns, ifs e fors completos private Queue<String> createFila(String trecho) { //System.out.println("Trecho no createFila: " + trecho); Queue<String> fila = new LinkedList<>(); trecho = trecho + " "; //System.out.println("Create fila"); Boolean insideIF = false; Boolean insideFOR = false; Boolean insideCommand = false; Boolean scape = false; Boolean hasElse = false; int indiceInicio = 0; int indiceFinal = trecho.length() - 1; int cAbrePar = 0, cFechaPar = 0; char[] scrOriginal = trecho.toCharArray(); if(trecho.contains("else")) hasElse = true; for(int i = 0; i < trecho.length(); i++) { //System.out.println("char iteração: " + scrOriginal[i]); //Encontrou um for if(i+2 < trecho.length() && !insideIF && !insideFOR && !insideCommand) { //System.out.println("> 2"); if(scrOriginal[i] == 'f' && scrOriginal[i+1] == 'o' && scrOriginal[i+2] == 'r') { //System.out.println("ENCONTROU FOR"); insideFOR = true; indiceInicio = i; cAbrePar = 0; cFechaPar = 0; } //Encontrou um if } if(i+1 < trecho.length() && !insideIF && !insideFOR && !insideCommand) { if(scrOriginal[i] == 'i' && scrOriginal[i+1] == 'f') { //System.out.println("ENCONTROU IF"); insideIF = true; indiceInicio = i; cAbrePar = 0; cFechaPar = 0; } //Encontrou um comando } if(!insideCommand && !insideIF && !insideFOR && scrOriginal[i] != ' '){ //System.out.println("ENCONTROU COMANDO"); insideCommand = true; indiceInicio = i; //Encontrou espaço em branco } else if(!insideCommand && !insideIF && !insideFOR && scrOriginal[i] == ' ') { scape = true; } if(insideFOR) { if(scrOriginal[i] == '(') cAbrePar++; if(scrOriginal[i] == ')') cFechaPar++; if(cAbrePar >= 3 && cAbrePar == cFechaPar) { //System.out.println("acabou um for"); indiceFinal = i+1; insideFOR = false; cAbrePar = 0; cFechaPar = 0; } } else if(insideIF) { if(scrOriginal[i] == '(') cAbrePar++; if(scrOriginal[i] == ')') cFechaPar++; if(cAbrePar >= 3 && cAbrePar == cFechaPar) { //System.out.println("acabou um if"); //System.out.println("penultimo char do if: " + scrOriginal[i-1]); indiceFinal = i+1; insideIF = false; cAbrePar = 0; cFechaPar = 0; } } else if(insideCommand) { if(scrOriginal[i] == '(') cAbrePar++; if(scrOriginal[i] == ')') cFechaPar++; if(cAbrePar > 0 && cAbrePar == cFechaPar) { //System.out.println("acabou um comando"); indiceFinal = i+1; insideCommand = false; cAbrePar = 0; cFechaPar = 0; } /* if(scrOriginal[i] == ' ') { //System.out.println("acabou um comando"); indiceFinal = i; //if(scrOriginal[i-1] == ')' && scrOriginal[i-2] == ')') indiceFinal = i-1; insideCommand = false; } */ } if(!insideIF && !insideFOR && !insideCommand && !scape) { String adicionar = trecho.substring(indiceInicio, indiceFinal); adicionar = adicionar.trim(); // retira parênteses desnecessários //if(adicionar.startsWith("(")) { // adicionar = trecho.substring(indiceInicio+1, indiceFinal); //} //System.out.println("Adicionando comando à fila: " + adicionar); //if(adicionar != "(ε)") fila.add(adicionar); indiceInicio = 0; indiceFinal = trecho.length() - 1; } scape = false; } //System.out.println("Fila: " + fila); return fila; } public iDSL getAST() { return this.astScript; } }
12,053
30.637795
108
java
MicroRTS
MicroRTS-master/src/gui/JTextAreaWriter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import java.io.IOException; import java.io.Writer; import javax.swing.JTextArea; /** * * @author santi */ public class JTextAreaWriter extends Writer { JTextArea m_ta; public JTextAreaWriter(JTextArea ta) { m_ta = ta; } public void write(char[] cbuf, int off, int len) throws IOException { StringBuilder tmp = new StringBuilder(); for(int i = off;i<off+len;i++) { tmp.append(cbuf[i]); } m_ta.append(tmp.toString()); m_ta.repaint(); } public void flush() throws IOException { m_ta.repaint(); } public void close() throws IOException { } }
871
20.268293
79
java
MicroRTS
MicroRTS-master/src/gui/MouseController.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import ai.core.AI; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.pathfinding.BFSPathFinding; import ai.core.ParameterSpecification; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import rts.*; import rts.units.Unit; /** * * @author santi * * To play the game with mouse: * - Left-click on units to select them * - Left click on the unit type names at the bottom of the screen (once you have selected * a unit that can train/build units) to select a unit type * - Right click to send actions, for example: * - right-clicking on an empty space makes the selected unit move * - right-clicking on an enemy makes the selected unit go to attack * - right-clicking on a resource makes the selected worker start harvesting * - if you have a unit type selected (bottom of the screen) and right-click in an empty * space, the selected worker will go and build a building in the desired place. */ public class MouseController extends AbstractionLayerAI { PhysicalGameStateMouseJFrame m_frame; PGSMouseListener m_mouseListener; public MouseController(PhysicalGameStateMouseJFrame frame) { super(new BFSPathFinding()); m_frame = frame; reset(); } public void setFrame(PhysicalGameStateMouseJFrame frame) { m_frame = frame; reset(); } public void reset() { // attach the mouse listener to the frame (make sure we only add one, and also remove the old ones): if (m_frame!=null) { MouseListener []mla = m_frame.getMouseListeners(); for(MouseListener ml:mla) { if (ml instanceof PGSMouseListener) m_frame.removeMouseListener(ml); } m_mouseListener = new PGSMouseListener(this, m_frame, null, -1); m_frame.addMouseListener(m_mouseListener); m_frame.addMouseMotionListener(m_mouseListener); m_frame.addKeyListener(m_mouseListener); } } public AI clone() { return new MouseController(m_frame); } public PlayerAction getAction(int player, GameState gs) { m_mouseListener.setPlayer(player); m_mouseListener.setGameState(gs); PhysicalGameState pgs = gs.getPhysicalGameState(); for(Unit u:pgs.getUnits()) { if (u.getPlayer()==player) { AbstractAction aa = actions.get(u); if (aa == null) { idle(u); } else if (aa.completed(gs)) { idle(u); } } } return translateActions(player, gs); } public PlayerAction translateActions(int player, GameState gs) { PhysicalGameState pgs = gs.getPhysicalGameState(); PlayerAction pa = new PlayerAction(); List<Integer> usedCells = new LinkedList<>(); // Execute abstract actions: ResourceUsage r = gs.getResourceUsage(); List<Unit> toDelete = new LinkedList<>(); for(AbstractAction aa:actions.values()) { // Unit u = null; // for(Unit u2:pgs.getUnits()) { // if (u2.getID() == aa.getUnit().getID()) { // u = u2; // aa.setUnit(u); // replace the unit by the right one // break; // } // } // if (u==null) { if (!pgs.getUnits().contains(aa.getUnit())) { // The unit is dead: toDelete.add(aa.getUnit()); } else if (gs.getActionAssignment(aa.getUnit())==null) { UnitAction ua = aa.execute(gs); if (ua!=null) { pa.addUnitAction(aa.getUnit(), ua); ResourceUsage r2 = ua.resourceUsage(aa.getUnit(), pgs); // We set the terrain to the positions where units are going to move as temporary walls, // to prevent other units from the player to want to move there and avoid conflicts for(Integer cell:r2.getPositionsUsed()) { int cellx = cell%pgs.getWidth(); int celly = cell/pgs.getWidth(); if (pgs.getTerrain(cellx,celly)==PhysicalGameState.TERRAIN_NONE) { usedCells.add(cell); pgs.setTerrain(cellx,celly,PhysicalGameState.TERRAIN_WALL); } } ResourceUsage r_merged = r.mergeIntoNew(r2); if (!pa.consistentWith(r_merged, gs)) { pa.removeUnitAction(aa.getUnit(), ua); } else { r = r_merged; } } } } for(Unit u:toDelete) actions.remove(u); // Remove all the temporary walls added above: for(Integer cell:usedCells) { int cellx = cell%pgs.getWidth(); int celly = cell/pgs.getWidth(); pgs.setTerrain(cellx,celly,PhysicalGameState.TERRAIN_NONE); } pa.fillWithNones(gs,player, 1); return pa; } @Override public List<ParameterSpecification> getParameters() { return new ArrayList<>(); } }
5,639
34.696203
108
java
MicroRTS
MicroRTS-master/src/gui/MouseControllerPanel.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.LinkedList; import java.util.List; import javax.swing.JPanel; /** * * @author santi */ public class MouseControllerPanel extends JPanel { public int offset_x = 16; public int offset_y = 16; public int separation_x = 16; List<String> buttons = new LinkedList<>(); List<Character> buttonQuickKeys = new LinkedList<>(); List<Rectangle2D> buttonRectangles = new LinkedList<>(); List<String> toHighlight = new LinkedList<>(); public MouseControllerPanel() { } public void clearButtons() { buttons.clear(); buttonQuickKeys.clear(); buttonRectangles.clear(); } public void highlight(String b) { toHighlight.add(b); } public void clearHighlight() { toHighlight.clear(); } public void addButton(String b, Character qk) { buttons.add(b); buttonQuickKeys.add(qk); Rectangle2D r = new Rectangle.Double(0, 0, 72, 32); buttonRectangles.add(r); } public String getContentAtCoordinates(int x, int y) { // return the button over which the coordinates are: int bx = offset_x; int by = offset_y; for(int i = 0;i<buttons.size();i++) { String button = buttons.get(i); Rectangle2D r = buttonRectangles.get(i); if (x>=bx+r.getX() && x<bx+r.getX()+r.getWidth() && y>=by+r.getY() && y<by+r.getY()+r.getHeight()) { return button; } bx+=separation_x+r.getWidth(); } return null; } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; int x = offset_x; int y = offset_y; for(int i = 0;i<buttons.size();i++) { String button = buttons.get(i); Character quickKey = buttonQuickKeys.get(i); int idx = -1; if (quickKey!=null) { for(int j = 0;j<button.length();j++) { Character c = button.charAt(j); c = Character.toLowerCase(c); if (c.equals(quickKey)) { idx = j; break; } } // System.out.println("index of '" + quickKey + "' in '" + button + "' is " + idx); } Rectangle2D r = buttonRectangles.get(i); g2d.setColor(Color.darkGray); if (toHighlight.contains(button)) g2d.setColor(Color.green); g2d.fillRect(x, y, (int)r.getWidth(), (int)r.getHeight()); g2d.setColor(Color.lightGray); g2d.fillRect(x+1, y+1, (int)r.getWidth()-2, (int)r.getHeight()-2); g2d.setColor(Color.black); if (idx==-1) { g2d.drawString(button, x + 10, y + 22); } else { String s1 = button.substring(0,idx); String s2 = button.substring(idx,idx+1); String s3 = button.substring(idx+1); g2d.drawString(s1, x + 10, y + 22); FontMetrics fm = g2d.getFontMetrics(); int w1 = fm.stringWidth(s1); g2d.setColor(Color.red); g2d.drawString(s2, x + 10 + w1, y + 22); int w2 = fm.stringWidth(s2); g2d.setColor(Color.black); g2d.drawString(s3, x + 10 + w1 + w2, y + 22); } x+=(int)r.getWidth(); x+=separation_x; } } }
3,791
29.336
98
java
MicroRTS
MicroRTS-master/src/gui/PGSMouseListener.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.units.Unit; import rts.units.UnitType; import util.Pair; /** * * @author santi */ public class PGSMouseListener implements MouseListener, MouseMotionListener, KeyListener { MouseController AI; PhysicalGameStateMouseJFrame frame; GameState gs; int playerID = -1; List<Unit> selectedUnits = new ArrayList<>(); String selectedButton; HashMap<Character,String> unitTypeQuickKeys = new HashMap<>(); public PGSMouseListener(MouseController a_AI, PhysicalGameStateMouseJFrame a_frame, GameState a_gs, int a_playerID) { AI = a_AI; frame = a_frame; gs = a_gs; playerID = a_playerID; } public void setGameState(GameState a_gs) { gs = a_gs; } public void setPlayer(int a_playerID) { playerID = a_playerID; } public void clearQuickKeys() { unitTypeQuickKeys.clear(); } public Character addQuickKey(String unitTypeName) { for(int i = 0;i<unitTypeName.length();i++) { Character c = unitTypeName.charAt(i); c = Character.toLowerCase(c); boolean found = false; for(Character qk:unitTypeQuickKeys.keySet()) { if (qk.equals(c)) { found = true; break; } } if (!found) { unitTypeQuickKeys.put(c, unitTypeName); return c; } } return null; } public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); Pair<Integer,Integer> coordinates = null; Unit rawUnit = null; Unit unit = null; String button = null; if (gs==null) return; PhysicalGameStatePanel panel = frame.getPanel(); MouseControllerPanel mousePanel = frame.getMousePanel(); Object tmp = frame.getContentAtCoordinates(x,y); if (tmp!=null) { if (tmp instanceof Pair) { coordinates = (Pair<Integer,Integer>)tmp; rawUnit = gs.getPhysicalGameState().getUnitAt(coordinates.m_a, coordinates.m_b); if (rawUnit!=null && rawUnit.getPlayer()==playerID) { unit = rawUnit; coordinates = null; } } else if (tmp instanceof String) { button = (String)tmp; } } if (e.getButton()==MouseEvent.BUTTON1) { // left click (select/deselect units): if (unit!=null) { selectedUnits.clear(); selectedUnits.add(unit); selectedButton = null; updateButtons(); } else if (button!=null) { selectedButton = button; for(Unit selectedUnit:selectedUnits) { if (!selectedUnit.getType().canMove) { UnitType ut = gs.getUnitTypeTable().getUnitType(selectedButton); if (ut!=null) { AI.train(selectedUnit, ut); selectedButton = null; } } } } else { if (insideOfGameArea(e.getX(), e.getY())) { selectedUnits.clear(); selectedButton = null; mousePanel.clearButtons(); clearQuickKeys(); } } } else if (e.getButton()==MouseEvent.BUTTON3) { // right click (execute actions): for(Unit selectedUnit:selectedUnits) { if (coordinates!=null) { // If the unit can move and the cell is empty: send action if (rawUnit!=null) { if (rawUnit.getType().isResource) { // if the unit can harvest, then harvest: if (selectedUnit.getType().canHarvest) { Unit base = null; double bestD = 0; for(Unit u:gs.getPhysicalGameState().getUnits()) { if (u.getPlayer()==playerID && u.getType().isStockpile) { double d = (selectedUnit.getX() - u.getX()) + (selectedUnit.getY() - u.getY()); if (base==null || d<bestD) { base = u; bestD = d; } } } if (base!=null) { AI.harvest(selectedUnit, rawUnit, base); } } } else if (!rawUnit.getType().isResource && rawUnit.getPlayer()!=playerID) { if (selectedUnit.getType().canAttack) { AI.attack(selectedUnit, rawUnit); } } else { // Ignore } } else { UnitType ut = gs.getUnitTypeTable().getUnitType(selectedButton); if (ut==null) { // If the unit can move, then move: if (selectedUnit.getType().canMove) { AI.move(selectedUnit, coordinates.m_a, coordinates.m_b); } } else { // produce: if (selectedUnit.getType().canMove) { AI.build(selectedUnit, ut, coordinates.m_a, coordinates.m_b); } } } } } } panel.clearHighlights(); mousePanel.clearHighlight(); for(Unit selectedUnit:selectedUnits) { panel.highlight(selectedUnit); } if (unit!=null) panel.highlight(unit); if (selectedButton!=null) mousePanel.highlight(selectedButton); if (button!=null) mousePanel.highlight(button); } public void mousePressed(MouseEvent e) { if (e.getButton()==MouseEvent.BUTTON1) { Insets insets = frame.getInsets(); frame.panel.m_mouse_selection_x0 = frame.panel.m_mouse_selection_x1 = e.getX() - insets.left; frame.panel.m_mouse_selection_y0 = frame.panel.m_mouse_selection_y1 = e.getY() - insets.top; frame.repaint(); } } public void mouseReleased(MouseEvent e) { // identify the units to be selected: if (!insideOfGameArea(e.getX(), e.getY())) { frame.panel.m_mouse_selection_x0 = frame.panel.m_mouse_selection_x1 = -1; frame.panel.m_mouse_selection_y0 = frame.panel.m_mouse_selection_y1 = -1; return; } if (e.getButton()==MouseEvent.BUTTON1) { int x0 = Math.min(frame.panel.m_mouse_selection_x0, frame.panel.m_mouse_selection_x1); int x1 = Math.max(frame.panel.m_mouse_selection_x0, frame.panel.m_mouse_selection_x1); int y0 = Math.min(frame.panel.m_mouse_selection_y0, frame.panel.m_mouse_selection_y1); int y1 = Math.max(frame.panel.m_mouse_selection_y0, frame.panel.m_mouse_selection_y1); Pair<Integer,Integer> tmp0 = frame.panel.getContentAtCoordinatesBounded(x0, y0); Pair<Integer,Integer> tmp1 = frame.panel.getContentAtCoordinatesBounded(x1, y1); // System.out.println(tmp0 + " - " + tmp1); frame.panel.m_mouse_selection_x0 = frame.panel.m_mouse_selection_x1 = -1; frame.panel.m_mouse_selection_y0 = frame.panel.m_mouse_selection_y1 = -1; if (tmp0!=null && tmp1!=null) { PhysicalGameStatePanel panel = frame.getPanel(); MouseControllerPanel mousePanel = frame.getMousePanel(); panel.clearHighlights(); mousePanel.clearHighlight(); selectedUnits.clear(); Pair<Integer,Integer> coordinates0 = (Pair<Integer,Integer>)tmp0; Pair<Integer,Integer> coordinates1 = (Pair<Integer,Integer>)tmp1; for(int i = coordinates0.m_b;i<=coordinates1.m_b;i++) { for(int j = coordinates0.m_a;j<=coordinates1.m_a;j++) { Unit u = gs.getPhysicalGameState().getUnitAt(j,i); if (u!=null) { if (u.getPlayer()==playerID) { panel.highlight(u); selectedUnits.add(u); } } } } updateButtons(); } frame.repaint(); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { if (e.getButton()==MouseEvent.BUTTON1) { Insets insets = frame.getInsets(); frame.panel.m_mouse_selection_x1 = e.getX() - insets.left; frame.panel.m_mouse_selection_y1 = e.getY() - insets.top; frame.repaint(); } } public void mouseMoved(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (gs==null) return; PhysicalGameStatePanel panel = frame.getPanel(); MouseControllerPanel mousePanel = frame.getMousePanel(); panel.clearHighlights(); mousePanel.clearHighlight(); for(Unit selectedUnit:selectedUnits) panel.highlight(selectedUnit); if (selectedButton!=null) mousePanel.highlight(selectedButton); Object tmp = frame.getContentAtCoordinates(x,y); if (tmp!=null) { if (tmp instanceof Pair) { Pair<Integer,Integer> coordinates = (Pair<Integer,Integer>)tmp; Unit u = gs.getPhysicalGameState().getUnitAt(coordinates.m_a, coordinates.m_b); if (u!=null) { if (u.getPlayer()==playerID) panel.highlight(u); } } else if (tmp instanceof String) { mousePanel.highlight((String)tmp); } } } public void keyTyped(KeyEvent keyEvent) { } public void keyPressed(KeyEvent keyEvent) { } public void keyReleased(KeyEvent keyEvent) { char kc = keyEvent.getKeyChar(); String button = unitTypeQuickKeys.get(kc); // System.out.println("key pressed: '" + kc + "', corresponding to button: " + button); if (button!=null) { // some unit type selected: selectedButton = button; for(Unit selectedUnit:selectedUnits) { if (!selectedUnit.getType().canMove) { UnitType ut = gs.getUnitTypeTable().getUnitType(selectedButton); if (ut!=null) { AI.train(selectedUnit, ut); } } } } MouseControllerPanel mousePanel = frame.getMousePanel(); mousePanel.clearHighlight(); if (selectedButton!=null) mousePanel.highlight(selectedButton); if (button!=null) mousePanel.highlight(button); mousePanel.repaint(); } private void updateButtons() { MouseControllerPanel mousePanel = frame.getMousePanel(); mousePanel.clearButtons(); clearQuickKeys(); List<UnitType> shared = null; for(Unit u:selectedUnits) { if (shared==null) { shared = new ArrayList<>(u.getType().produces); } else { List<UnitType> toDelete = new ArrayList<>(); for(UnitType ut:shared) { if (!u.getType().produces.contains(ut)) { toDelete.add(ut); } } shared.removeAll(toDelete); } } if (shared!=null) { for(UnitType ut:shared) { // Add a quick Key: Character qk = addQuickKey(ut.name); mousePanel.addButton(ut.name, qk); } } } public boolean insideOfGameArea(int x, int y) { Insets insets = frame.getInsets(); x-= insets.left; y-= insets.top; Rectangle r = frame.panel.getBounds(); // if mouse was outside of playing area, return: return x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height; } }
13,381
35.763736
121
java
MicroRTS
MicroRTS-master/src/gui/PhysicalGameStateJFrame.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import javax.swing.JFrame; import rts.GameState; /** * * @author santi */ public class PhysicalGameStateJFrame extends JFrame { PhysicalGameStatePanel panel; public PhysicalGameStateJFrame(String title, int dx, int dy, PhysicalGameStatePanel a_panel) { super(title); panel = a_panel; getContentPane().add(panel); pack(); setResizable(false); setSize(dx,dy); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public PhysicalGameStatePanel getPanel() { return panel; } public void setStateCloning(GameState gs) { panel.setStateCloning(gs); } public void setStateDirect(GameState gs) { panel.setStateDirect(gs); } }
905
21.097561
98
java
MicroRTS
MicroRTS-master/src/gui/PhysicalGameStateMouseJFrame.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import java.awt.Dimension; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.BoxLayout; import javax.swing.JFrame; import rts.GameState; import util.Pair; /** * * @author santi */ public class PhysicalGameStateMouseJFrame extends JFrame { PhysicalGameStatePanel panel; MouseControllerPanel mousePanel; public PhysicalGameStateMouseJFrame(String title, int dx, int dy, PhysicalGameStatePanel a_panel) { super(title); panel = a_panel; mousePanel = new MouseControllerPanel(); panel.setPreferredSize(new Dimension(dx, dy-64)); mousePanel.setPreferredSize(new Dimension(dx, 64)); getContentPane().removeAll(); getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS)); getContentPane().add(panel); getContentPane().add(mousePanel); pack(); setSize(dx,dy); setResizable(false); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public PhysicalGameStatePanel getPanel() { return panel; } public MouseControllerPanel getMousePanel() { return mousePanel; } public void setStateDirect(GameState gs) { panel.setStateDirect(gs); } public Object getContentAtCoordinates(int x, int y) { Insets insets = getInsets(); x-=insets.left; y-=insets.top; Rectangle r = panel.getBounds(); if (x>=r.x && x<r.x+r.width && y>=r.y && y<r.y+r.height) { Pair<Integer,Integer> cell = panel.getContentAtCoordinates(x - r.x, y - r.y); return cell; } r = mousePanel.getBounds(); if (x>=r.x && x<r.x+r.width && y>=r.y && y<r.y+r.height) { String button = mousePanel.getContentAtCoordinates(x - r.x, y - r.y); return button; } return null; } }
2,115
26.480519
103
java
MicroRTS
MicroRTS-master/src/gui/PhysicalGameStatePanel.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleEvaluationFunction; import java.awt.BasicStroke; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.swing.JPanel; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.UnitAction; import rts.UnitActionAssignment; import rts.units.Unit; import util.Pair; /** * * @author santi */ public class PhysicalGameStatePanel extends JPanel { public static int COLORSCHEME_BLACK = 1; public static int COLORSCHEME_WHITE = 2; boolean fullObservability = true; int drawFromPerspectiveOfPlayer = -1; // if fullObservability is false, and this is 0 or 1, it only draws what the specified player can see GameState gs; // Units to be highlighted (this is used, for example, by the MouseController, // to give feedback to the human, on which units are selectable. List<Unit> toHighLight = new LinkedList<>(); EvaluationFunction evalFunction; // area to highlight: this can be used to highlight a rectangle of the game: int m_mouse_selection_x0 = -1; int m_mouse_selection_x1 = -1; int m_mouse_selection_y0 = -1; int m_mouse_selection_y1 = -1; // the state observed by each player: PartiallyObservableGameState pogs[] = new PartiallyObservableGameState[2]; // Coordinates where things were drawn the last time this was redrawn: int last_start_x = 0; int last_start_y = 0; int last_grid = 0; // the color scheme int colorScheme = COLORSCHEME_BLACK; static Color GRIDLINE; static Color PLAYER0UNIT_OUTLINE; static Color PLAYER0_PARTIAL_OBSERVABILITY; static Color PLAYER1UNIT_OUTLINE; static Color PLAYER1_PARTIAL_OBSERVABILITY; static Color PLAYERBOTH_OBSERVABILITY; static Color RESOURCE; static Color LIGHT; static Color RANGED; static Color HEAVY; static Color HPBAR; static Color HPBAR_LOST; public PhysicalGameStatePanel(GameState a_gs) { this(a_gs, new SimpleEvaluationFunction()); } public PhysicalGameStatePanel(PhysicalGameStatePanel pgsp) { this(pgsp.gs, pgsp.evalFunction); fullObservability = pgsp.fullObservability; drawFromPerspectiveOfPlayer = pgsp.drawFromPerspectiveOfPlayer; if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } } public PhysicalGameStatePanel(GameState a_gs, EvaluationFunction evalFunction) { gs = a_gs; if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } this.evalFunction = evalFunction; setColorScheme(COLORSCHEME_BLACK); } public PhysicalGameStatePanel(GameState a_gs, EvaluationFunction evalFunction, int cs) { gs = a_gs; if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } this.evalFunction = evalFunction; setColorScheme(cs); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs) { return newVisualizer(a_gs, 320, 320, false, new SimpleEvaluationFunction(), COLORSCHEME_BLACK); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, boolean a_showVisibility) { return newVisualizer(a_gs, 320, 320, a_showVisibility, new SimpleEvaluationFunction(), COLORSCHEME_BLACK); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, int dx, int dy) { return newVisualizer(a_gs, dx, dy, false, new SimpleEvaluationFunction(), COLORSCHEME_BLACK); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, int dx, int dy, boolean a_showVisibility) { return newVisualizer(a_gs, dx, dy, a_showVisibility, new SimpleEvaluationFunction(), COLORSCHEME_BLACK); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, int dx, int dy, boolean a_showVisibility, int cs) { return newVisualizer(a_gs, dx, dy, a_showVisibility, new SimpleEvaluationFunction(), cs); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, int dx, int dy, EvaluationFunction evalFunction) { return newVisualizer(a_gs, dx, dy, false, evalFunction, COLORSCHEME_BLACK); } public static PhysicalGameStateJFrame newVisualizer(GameState a_gs, int dx, int dy, boolean a_showVisibility, EvaluationFunction evalFunction, int cs) { PhysicalGameStatePanel ad = new PhysicalGameStatePanel(a_gs, evalFunction, cs); ad.fullObservability = !a_showVisibility; PhysicalGameStateJFrame frame = null; frame = new PhysicalGameStateJFrame("Game State Visualizer", dx, dy, ad); return frame; } public GameState getGameState() { return gs; } public void setColorScheme(int cs) { colorScheme = cs; if (colorScheme==COLORSCHEME_BLACK) { setBackground(Color.decode("#22272e")); // Github Dark // dark theme vars GRIDLINE = Color.decode("#adbbc7"); // soft gray PLAYER0UNIT_OUTLINE = Color.decode("#0C7BDC"); // soft blue PLAYER0_PARTIAL_OBSERVABILITY = Color.decode("#9CCAE4"); // softer blue PLAYER1UNIT_OUTLINE = Color.decode("#BF3682"); // soft red PLAYER1_PARTIAL_OBSERVABILITY = Color.decode("#C183A6"); // softer red PLAYERBOTH_OBSERVABILITY = Color.decode("#E69F00"); // softer purple RESOURCE = Color.decode("#C2DFAE"); // soft green LIGHT = Color.decode("#D55E00"); // soft orange RANGED = Color.decode("#0072B2"); // soft cyan HEAVY = Color.decode("#F0E442"); // soft yellow HPBAR = Color.decode("#C2DFAE"); // soft green HPBAR_LOST = Color.decode("#BF3682"); // soft red } else { setBackground(Color.WHITE); // White theme vars GRIDLINE = Color.decode("#000000"); // soft gray PLAYER0UNIT_OUTLINE = Color.decode("#0C7BDC"); // soft blue PLAYER0_PARTIAL_OBSERVABILITY = Color.decode("#9CCAE4"); // softer blue PLAYER1UNIT_OUTLINE = Color.decode("#BF3682"); // soft red PLAYER1_PARTIAL_OBSERVABILITY = Color.decode("#C183A6"); // softer red PLAYERBOTH_OBSERVABILITY = Color.decode("#E69F00"); // softer purple RESOURCE = Color.decode("#C2DFAE"); // soft green LIGHT = Color.decode("#D55E00"); // soft orange RANGED = Color.decode("#0072B2"); // soft cyan HEAVY = Color.decode("#F0E442"); // soft yellow HPBAR = Color.decode("#C2DFAE"); // soft green HPBAR_LOST = Color.decode("#BF3682"); // soft red } } public int getColorScheme() { return colorScheme; } public void setStateCloning(GameState a_gs) { gs = a_gs.clone(); if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } else { pogs[0] = null; pogs[1] = null; } } public void setStateDirect(GameState a_gs) { gs = a_gs; if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } else { pogs[0] = null; pogs[1] = null; } } public GameState getState() { return gs; } public void clearHighlights() { toHighLight.clear(); } public void highlight(Unit u) { toHighLight.add(u); } public Pair<Integer,Integer> getContentAtCoordinates(int x, int y) { // return the map coordiantes over which the coordinates are: // System.out.println(x + ", " + y + " -> last start: " + last_start_x + ", " + last_start_y); if (x<last_start_x) return null; if (y<last_start_y) return null; int cellx = (x - last_start_x)/last_grid; int celly = (y - last_start_y)/last_grid; if (cellx>=gs.getPhysicalGameState().getWidth()) return null; if (celly>=gs.getPhysicalGameState().getHeight()) return null; return new Pair<>(cellx, celly); } public Pair<Integer,Integer> getContentAtCoordinatesBounded(int x, int y) { // return the map coordiantes over which the coordinates are: // System.out.println(x + ", " + y + " -> last start: " + last_start_x + ", " + last_start_y); if (x<last_start_x) x = last_start_x; if (y<last_start_y) y = last_start_y; int cellx = (x - last_start_x)/last_grid; int celly = (y - last_start_y)/last_grid; if (cellx>=gs.getPhysicalGameState().getWidth()) cellx = gs.getPhysicalGameState().getWidth()-1; if (celly>=gs.getPhysicalGameState().getHeight()) celly = gs.getPhysicalGameState().getHeight()-1; return new Pair<>(cellx, celly); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; if (gs!=null) { synchronized(gs) { draw(g2d, this, this.getWidth(), this.getHeight(), gs, pogs, colorScheme, fullObservability, drawFromPerspectiveOfPlayer, evalFunction); } } if (m_mouse_selection_x0>=0) { g.setColor(Color.green); int x0 = Math.min(m_mouse_selection_x0, m_mouse_selection_x1); int x1 = Math.max(m_mouse_selection_x0, m_mouse_selection_x1); int y0 = Math.min(m_mouse_selection_y0, m_mouse_selection_y1); int y1 = Math.max(m_mouse_selection_y0, m_mouse_selection_y1); g.drawRect(x0, y0, x1 - x0, y1 - y0); } } public static void draw(Graphics2D g2d, PhysicalGameStatePanel panel, int dx,int dy, GameState gs, PartiallyObservableGameState pogs[], int colorScheme, boolean fullObservability, int drawFromPerspectiveOfPlayer, EvaluationFunction evalFunction) { if (gs==null) return; PhysicalGameState pgs = gs.getPhysicalGameState(); if (pgs==null) return; int gridx = (dx-64)/pgs.getWidth(); int gridy = (dy-64)/pgs.getHeight(); int grid = Math.min(gridx,gridy); int sizex = grid*pgs.getWidth(); int sizey = grid*pgs.getHeight(); float unitLineThickness = 1f; if (grid > 10) unitLineThickness = 1.8f; if (grid > 20) unitLineThickness = 2.3f; if (!fullObservability && pogs!=null && pogs[0]!=null && pogs[1]!=null) { if (pogs[0].getTime() != gs.getTime()) { // update pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } } if (colorScheme==COLORSCHEME_BLACK) g2d.setColor(Color.WHITE); if (colorScheme==COLORSCHEME_WHITE) g2d.setColor(Color.BLACK); int unitCount0 = 0; for (Unit unit : gs.getPhysicalGameState().getUnits()) { if (unit.getPlayer() == 0) { unitCount0++; } } int unitCount1 = 0; for (Unit unit : gs.getPhysicalGameState().getUnits()) { if (unit.getPlayer() == 1) { unitCount1++; } } float eval0 = (evalFunction!=null ? evalFunction.evaluate(0, 1, gs):0); float eval1 = (evalFunction!=null ? evalFunction.evaluate(1, 0, gs):0); String info = "T: " + gs.getTime() + ", P0: " + unitCount0 + " (" + eval0 + "), P1: " + unitCount1 + " (" + eval1 + ")"; g2d.drawString(info, 10, dy-15); // g.drawString(gs.getTime() + "", 10, getHeight()-15); AffineTransform t = g2d.getTransform(); if (panel!=null) { panel.last_start_x = dx/2 - sizex/2; panel.last_start_y = dy/2 - sizey/2; panel.last_grid = grid; g2d.translate(panel.last_start_x, panel.last_start_y); } else { int last_start_x = dx/2 - sizex/2; int last_start_y = dy/2 - sizey/2; g2d.translate(last_start_x, last_start_y); } Color playerColor = null; Color wallColor = new Color(0, 0.33f, 0); for(int j = 0;j<pgs.getWidth();j++) { for(int i = 0;i<pgs.getHeight();i++) { if (!fullObservability) { // show partial observability: if (drawFromPerspectiveOfPlayer>=0) { if (pogs[drawFromPerspectiveOfPlayer].observable(j, i)) { if (drawFromPerspectiveOfPlayer==0) { g2d.setColor(PLAYER0_PARTIAL_OBSERVABILITY); g2d.fillRect(j*grid, i*grid, grid, grid); } else { g2d.setColor(PLAYER1_PARTIAL_OBSERVABILITY); g2d.fillRect(j*grid, i*grid, grid, grid); } } } else { if (pogs[0].observable(j, i)) { if (pogs[1].observable(j, i)) { g2d.setColor(PLAYERBOTH_OBSERVABILITY); g2d.fillRect(j*grid, i*grid, grid, grid); } else { g2d.setColor(PLAYER0_PARTIAL_OBSERVABILITY); g2d.fillRect(j*grid, i*grid, grid, grid); } } else { if (pogs[1].observable(j, i)) { g2d.setColor(PLAYER1_PARTIAL_OBSERVABILITY); g2d.fillRect(j*grid, i*grid, grid, grid); } } } } if (pgs.getTerrain(j,i)==PhysicalGameState.TERRAIN_WALL) { g2d.setColor(wallColor); g2d.fillRect(j*grid, i*grid, grid, grid); } } } // draw grid: g2d.setColor(GRIDLINE); for(int i = 0;i<=pgs.getWidth();i++) g2d.drawLine(i*grid, 0, i*grid, pgs.getHeight()*grid); for(int i = 0;i<=pgs.getHeight();i++) g2d.drawLine(0, i*grid, pgs.getWidth()*grid, i*grid); // draw the units: // this list copy is to prevent a concurrent modification exception List<Unit> l = new LinkedList<>(pgs.getUnits()); for(Unit u:l) { int reduction = 0; if (!fullObservability && drawFromPerspectiveOfPlayer>=0 && !pogs[drawFromPerspectiveOfPlayer].observable(u.getX(), u.getY())) continue; // Draw the action: UnitActionAssignment uaa = gs.getActionAssignment(u); if (uaa!=null) { int offsx = 0; int offsy = 0; if (uaa.action.getType()==UnitAction.TYPE_ATTACK_LOCATION) { offsx = (uaa.action.getLocationX() - u.getX())*grid; offsy = (uaa.action.getLocationY() - u.getY())*grid; } else { if (uaa.action.getDirection()==UnitAction.DIRECTION_UP) offsy = -grid; if (uaa.action.getDirection()==UnitAction.DIRECTION_RIGHT) offsx = grid; if (uaa.action.getDirection()==UnitAction.DIRECTION_DOWN) offsy = grid; if (uaa.action.getDirection()==UnitAction.DIRECTION_LEFT) offsx = -grid; } switch(uaa.action.getType()) { case UnitAction.TYPE_MOVE: g2d.setColor(Color.GRAY); g2d.drawLine(u.getX()*grid+grid/2, u.getY()*grid+grid/2, u.getX()*grid+grid/2 + offsx, u.getY()*grid+grid/2 + offsy); break; case UnitAction.TYPE_ATTACK_LOCATION: g2d.setColor(PLAYER1UNIT_OUTLINE); g2d.drawLine(u.getX()*grid+grid/2, u.getY()*grid+grid/2, u.getX()*grid+grid/2 + offsx, u.getY()*grid+grid/2 + offsy); break; case UnitAction.TYPE_PRODUCE: g2d.setColor(PLAYER0UNIT_OUTLINE); g2d.drawLine(u.getX() * grid + grid / 2, u.getY() * grid + grid / 2, u.getX() * grid + grid / 2 + offsx, u.getY() * grid + grid / 2 + offsy); // draw building progress bar int ETA = uaa.time + uaa.action.ETA(uaa.unit) - gs.getTime(); g2d.setColor(PLAYER0UNIT_OUTLINE); g2d.fillRect(u.getX() * grid + offsx, u.getY() * grid + offsy, grid - (int) (grid * (((float) ETA) / uaa.action.ETA(uaa.unit))), (int) (grid / 5.0)); String txt = uaa.action.getUnitType().name; g2d.setColor(PLAYER0UNIT_OUTLINE); FontMetrics fm = g2d.getFontMetrics(g2d.getFont()); int width = fm.stringWidth(txt); g2d.drawString(txt, u.getX() * grid + grid / 2 - width / 2 + offsx, u.getY() * grid + grid / 2 + offsy); break; case UnitAction.TYPE_HARVEST: case UnitAction.TYPE_RETURN: if (colorScheme==COLORSCHEME_BLACK) g2d.setColor(Color.WHITE); if (colorScheme==COLORSCHEME_WHITE) g2d.setColor(Color.GREEN); g2d.drawLine(u.getX()*grid+grid/2, u.getY()*grid+grid/2, u.getX()*grid+grid/2 + offsx, u.getY()*grid+grid/2 + offsy); break; } } if (u.getPlayer()==0) { playerColor = PLAYER0UNIT_OUTLINE; } else if (u.getPlayer()==1) { playerColor = PLAYER1UNIT_OUTLINE; } else if (u.getPlayer()==-1) { playerColor = null; } if (u.getType().name.equals("Resource")) { g2d.setColor(RESOURCE); } if (u.getType().name.equals("Base")) { if (colorScheme==COLORSCHEME_BLACK) g2d.setColor(Color.white); if (colorScheme==COLORSCHEME_WHITE) g2d.setColor(Color.lightGray); } if (u.getType().name.equals("Barracks")) { if (colorScheme==COLORSCHEME_BLACK) g2d.setColor(Color.lightGray); if (colorScheme==COLORSCHEME_WHITE) g2d.setColor(Color.gray); } if (u.getType().name.equals("Worker")) { g2d.setColor(Color.gray); reduction = grid/4; } if (u.getType().name.equals("Light")) { g2d.setColor(LIGHT); reduction = grid/8; } if (u.getType().name.equals("Heavy")) g2d.setColor(HEAVY); if (u.getType().name.equals("Ranged")) { g2d.setColor(RANGED); reduction = grid/8; } if (!u.getType().canMove) { g2d.fillRect(u.getX()*grid+reduction, u.getY()*grid+reduction, grid-reduction*2, grid-reduction*2); g2d.setColor(playerColor); if (panel!=null && panel.toHighLight.contains(u)) g2d.setColor(Color.green); g2d.setStroke(new BasicStroke(unitLineThickness)); g2d.drawRect(u.getX()*grid+reduction, u.getY()*grid+reduction, grid-reduction*2, grid-reduction*2); g2d.setStroke(new BasicStroke(1)); } else { g2d.fillOval(u.getX()*grid+reduction, u.getY()*grid+reduction, grid-reduction*2, grid-reduction*2); g2d.setColor(playerColor); if (panel!=null && panel.toHighLight.contains(u)) g2d.setColor(Color.green); g2d.setStroke(new BasicStroke(unitLineThickness)); g2d.drawOval(u.getX()*grid+reduction, u.getY()*grid+reduction, grid-reduction*2, grid-reduction*2); g2d.setStroke(new BasicStroke(1)); } if (u.getType().isStockpile) { // print the player resources in the base: String txt = "" + pgs.getPlayer(u.getPlayer()).getResources(); g2d.setColor(Color.black); FontMetrics fm = g2d.getFontMetrics(g2d.getFont()); int width = fm.stringWidth(txt); g2d.drawString(txt, u.getX()*grid + grid/2 - width/2, u.getY()*grid + grid/2); } if (u.getResources()!=0) { String txt = "" + u.getResources(); g2d.setColor(Color.black); FontMetrics fm = g2d.getFontMetrics(g2d.getFont()); int width = fm.stringWidth(txt); g2d.drawString(txt, u.getX()*grid + grid/2 - width/2, u.getY()*grid + grid/2); } if (u.getHitPoints()<u.getMaxHitPoints()) { g2d.setColor(HPBAR_LOST); g2d.fillRect(u.getX() * grid, u.getY() * grid, grid, (int) (grid / 5.0)); g2d.setColor(HPBAR); g2d.fillRect(u.getX() * grid, u.getY() * grid, (int) (grid * (((float) u.getHitPoints()) / u.getMaxHitPoints())), (int) (grid / 5.0)); } } g2d.setTransform(t); } public void resizeGameState(int width, int height) { if (width>=1 && height>=1) { PhysicalGameState pgs = gs.getPhysicalGameState(); int newTerrain[] = new int[width*height]; for(int i = 0;i<width*height;i++) newTerrain[i] = PhysicalGameState.TERRAIN_NONE; for(int i = 0;i<height && i<pgs.getHeight();i++) { for(int j = 0;j<width && j<pgs.getWidth();j++) { newTerrain[j+i*width] = pgs.getTerrain(j, i); } } List<Unit> toDelete = new ArrayList<>(); for(Unit u:pgs.getUnits()) { if (u.getX()>=width || u.getY()>=height) toDelete.add(u); } for(Unit u:toDelete) gs.removeUnit(u); pgs.setTerrain(newTerrain); pgs.setWidth(width); pgs.setHeight(height); pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } } public void setFullObservability(boolean fo) { fullObservability = fo; } public void setDrawFromPerspectiveOfPlayer(int p) { drawFromPerspectiveOfPlayer = p; } public void gameStateUpdated() { if (gs!=null) { pogs[0] = new PartiallyObservableGameState(gs, 0); pogs[1] = new PartiallyObservableGameState(gs, 1); } else { pogs[0] = null; pogs[1] = null; } } }
23,621
40.225131
165
java
MicroRTS
MicroRTS-master/src/gui/TraceVisualizer.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import gui.PhysicalGameStatePanel; import java.awt.Color; import java.awt.Dimension; import java.util.LinkedList; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import rts.*; import rts.units.Unit; import util.Pair; /** * * @author santi */ public class TraceVisualizer extends JPanel implements ListSelectionListener { int current_step = 0; Trace trace; JPanel statePanel; JList Selector; List<GameState> states = new LinkedList<>(); public static JFrame newWindow(String name,int dx,int dy,Trace t, int subjectID) throws Exception { TraceVisualizer ad = new TraceVisualizer(t, dx, dy, subjectID); JFrame frame = new JFrame(name); frame.getContentPane().add(ad); frame.pack(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); return frame; } public TraceVisualizer(Trace t, int dx, int dy, int subject) throws Exception { current_step = 0; trace = t; for(TraceEntry te:trace.getEntries()) { states.add(trace.getGameStateAtCycle(te.getTime())); } setPreferredSize(new Dimension(dx,dy)); setSize(dx,dy); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } setBackground(Color.WHITE); removeAll(); setLayout(new BoxLayout(this,BoxLayout.X_AXIS)); statePanel = new PhysicalGameStatePanel(new GameState(t.getEntries().get(0).getPhysicalGameState(), t.getUnitTypeTable())); //, 320, 320); statePanel.setPreferredSize(new Dimension((int)(dx*0.6),dy)); add(statePanel); String []actionList = new String [t.getEntries().size()]; Selector = new JList (); JScrollPane ListScrollPane = new JScrollPane(Selector); for(int i = 0;i<t.getEntries().size();i++) { if (!t.getEntries().get(i).getActions().isEmpty()) { StringBuilder tmp = new StringBuilder(); for(Pair<Unit,UnitAction> uap:t.getEntries().get(i).getActions()) { tmp.append("(").append(uap.m_a.getID()).append(", ").append(uap.m_b.getActionName()).append("), "); } actionList[i] = tmp.toString(); } else { actionList[i] = "-"; } } Selector.setListData(actionList); Selector.addListSelectionListener (this); Selector.setSelectedIndex (0); Selector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Selector.setPreferredSize(new Dimension(100,dy*2)); // ListScrollPane.setPreferredSize(new Dimension(100,dy*2)); add(ListScrollPane); } public void valueChanged(ListSelectionEvent e) { int selection = Selector.getSelectedIndex(); ((PhysicalGameStatePanel)statePanel).setStateDirect(states.get(selection)); this.repaint(); } }
3,196
30.343137
146
java
MicroRTS
MicroRTS-master/src/gui/frontend/FEStateMouseListener.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import gui.*; import java.awt.event.*; import rts.GameState; import rts.units.UnitTypeTable; import util.Pair; /** * * @author santi */ public class FEStateMouseListener implements MouseListener, MouseMotionListener { PhysicalGameStatePanel panel; UnitTypeTable utt; public FEStateMouseListener(PhysicalGameStatePanel a_panel, UnitTypeTable a_utt) { panel = a_panel; utt = a_utt; } public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); Pair<Integer,Integer> coordinates = null; GameState gs = panel.getState(); if (gs==null) return; if (e.getButton()==MouseEvent.BUTTON1) { Object tmp = panel.getContentAtCoordinates(x,y); if (tmp!=null) { if (tmp instanceof Pair) { coordinates = (Pair<Integer,Integer>)tmp; PopUpStateEditorMenu menu = new PopUpStateEditorMenu(gs, utt, coordinates.m_a, coordinates.m_b, panel); menu.show(e.getComponent(), e.getX(), e.getY()); } } } } public void setUnitTypeTable(UnitTypeTable a_utt) { utt = a_utt; } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } }
1,767
23.901408
123
java
MicroRTS
MicroRTS-master/src/gui/frontend/FEStatePane.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import ai.BranchingFactorCalculatorBigInteger; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ContinuingAI; import ai.core.PseudoContinuingAI; import ai.PassiveAI; import ai.RandomAI; import ai.RandomBiasedAI; import ai.abstraction.HeavyDefense; import ai.abstraction.HeavyRush; import ai.abstraction.LightDefense; import ai.abstraction.LightRush; import ai.abstraction.RangedDefense; import ai.abstraction.RangedRush; import ai.abstraction.WorkerDefense; import ai.abstraction.WorkerRush; import ai.abstraction.WorkerRushPlusPlus; import ai.abstraction.cRush.CRush_V1; import ai.abstraction.cRush.CRush_V2; import ai.abstraction.partialobservability.POHeavyRush; import ai.abstraction.partialobservability.POLightRush; import ai.abstraction.partialobservability.PORangedRush; import ai.abstraction.partialobservability.POWorkerRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.BFSPathFinding; import ai.abstraction.pathfinding.FloodFillPathFinding; import ai.abstraction.pathfinding.GreedyPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.ahtn.AHTNAI; import ai.core.ParameterSpecification; import ai.evaluation.EvaluationFunction; import ai.evaluation.EvaluationFunctionForwarding; import ai.evaluation.SimpleEvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction2; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.informedmcts.InformedNaiveMCTS; import ai.mcts.mlps.MLPSMCTS; import ai.mcts.naivemcts.NaiveMCTS; import ai.mcts.uct.UCT; import ai.mcts.uct.UCTFirstPlayUrgency; import ai.mcts.uct.UCTUnitActions; import ai.minimax.ABCD.IDABCD; import ai.minimax.RTMiniMax.IDRTMinimax; import ai.minimax.RTMiniMax.IDRTMinimaxRandomized; import ai.montecarlo.MonteCarlo; import ai.montecarlo.lsi.LSI; import ai.portfolio.PortfolioAI; import ai.portfolio.portfoliogreedysearch.PGSAI; import ai.puppet.PuppetSearchMCTS; import ai.stochastic.UnitActionProbabilityDistribution; import gui.MouseController; import gui.PhysicalGameStateMouseJFrame; import gui.PhysicalGameStatePanel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.SwingConstants; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.PlayerActionGenerator; import rts.Trace; import rts.TraceEntry; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; import tests.MapGenerator; import util.Pair; import util.XMLWriter; import ai.core.InterruptibleAI; import ai.evaluation.SimpleOptEvaluationFunction; import ai.mcts.believestatemcts.BS3_NaiveMCTS; import ai.mcts.uct.DownsamplingUCT; import ai.scv.SCV; /** * * @author santi */ public class FEStatePane extends JPanel { PhysicalGameStatePanel statePanel; JTextArea textArea; UnitTypeTable currentUtt; JFileChooser fileChooser = new JFileChooser(); EvaluationFunction efs[] = {new SimpleEvaluationFunction(), new SimpleSqrtEvaluationFunction(), new SimpleSqrtEvaluationFunction2(), new SimpleSqrtEvaluationFunction3(), new EvaluationFunctionForwarding(new SimpleEvaluationFunction()), new SimpleOptEvaluationFunction()}; public static Class AIs[] = {PassiveAI.class, MouseController.class, RandomAI.class, RandomBiasedAI.class, WorkerRush.class, LightRush.class, HeavyRush.class, RangedRush.class, WorkerDefense.class, LightDefense.class, HeavyDefense.class, RangedDefense.class, POWorkerRush.class, POLightRush.class, POHeavyRush.class, PORangedRush.class, WorkerRushPlusPlus.class, CRush_V1.class, CRush_V2.class, PortfolioAI.class, PGSAI.class, IDRTMinimax.class, IDRTMinimaxRandomized.class, IDABCD.class, MonteCarlo.class, LSI.class, UCT.class, UCTUnitActions.class, UCTFirstPlayUrgency.class, DownsamplingUCT.class, NaiveMCTS.class, BS3_NaiveMCTS.class, MLPSMCTS.class, AHTNAI.class, InformedNaiveMCTS.class, PuppetSearchMCTS.class, SCV.class }; Class PlayoutAIs[] = { RandomAI.class, RandomBiasedAI.class, WorkerRush.class, LightRush.class, HeavyRush.class, RangedRush.class, }; PathFinding pathFinders[] = {new AStarPathFinding(), new BFSPathFinding(), new GreedyPathFinding(), new FloodFillPathFinding()}; public static UnitTypeTable unitTypeTables[] = {new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH), new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING), new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM), new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL_FINETUNED, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH), new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL_FINETUNED, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING), new UnitTypeTable(UnitTypeTable.VERSION_ORIGINAL_FINETUNED, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM), new UnitTypeTable(UnitTypeTable.VERSION_NON_DETERMINISTIC, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH), new UnitTypeTable(UnitTypeTable.VERSION_NON_DETERMINISTIC, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING), new UnitTypeTable(UnitTypeTable.VERSION_NON_DETERMINISTIC, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM), }; public static String unitTypeTableNames[] = {"Original-Both", "Original-Alternating", "Original-Random", "Finetuned-Both", "Finetuned-Alternating", "Finetuned-Random", "Nondeterministic-Both", "Nondeterministic-Alternating", "Nondeterministic-Random"}; JFormattedTextField mapWidthField; JFormattedTextField mapHeightField; JFormattedTextField maxCyclesField; JFormattedTextField defaultDelayField; JCheckBox fullObservabilityBox; JComboBox unitTypeTableBox; JCheckBox saveTraceBox; JCheckBox slowDownBox; JComboBox aiComboBox[] = {null,null}; JCheckBox continuingBox[] = {null,null}; JPanel AIOptionsPanel[] = {null, null}; HashMap AIOptionsPanelComponents[] = {new HashMap<String, JComponent>(), new HashMap<String, JComponent>()}; FEStateMouseListener mouseListener; public FEStatePane() throws Exception { currentUtt = new UnitTypeTable(); setLayout(new BorderLayout()); JPanel p1 = new JPanel(); p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS)); { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); { JButton b = new JButton("Clear"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GameState gs = statePanel.getState(); gs.getUnitActions().clear(); PhysicalGameState pgs = gs.getPhysicalGameState(); for(int i = 0;i<pgs.getHeight();i++) { for(int j = 0;j<pgs.getWidth();j++) { pgs.setTerrain(j,i,PhysicalGameState.TERRAIN_NONE); } } pgs.getUnits().clear(); statePanel.repaint(); } }); ptmp.add(b); } { JButton b = new JButton("Load"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { PhysicalGameState pgs = PhysicalGameState.load(file.getAbsolutePath(), currentUtt); GameState gs = new GameState(pgs, currentUtt); statePanel.setStateDirect(gs); statePanel.repaint(); mapWidthField.setText(pgs.getWidth()+""); mapHeightField.setText(pgs.getHeight()+""); } catch (Exception ex) { ex.printStackTrace(); } } } }); ptmp.add(b); } { JButton b = new JButton("Save"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (statePanel.getGameState()!=null) { int returnVal = fileChooser.showSaveDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { XMLWriter xml = new XMLWriter(new FileWriter(file.getAbsolutePath())); statePanel.getGameState().getPhysicalGameState().toxml(xml); xml.flush(); } catch (Exception ex) { ex.printStackTrace(); } } } } }); ptmp.add(b); } p1.add(ptmp); } { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); mapWidthField = addTextField(ptmp,"Width:", "8", 4); mapWidthField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int newWidth = Integer.parseInt(mapWidthField.getText()); statePanel.resizeGameState(newWidth, statePanel.getGameState().getPhysicalGameState().getHeight()); statePanel.repaint(); } catch(Exception ex) { } } }); mapHeightField = addTextField(ptmp,"Height:", "8", 4); mapHeightField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int newHeight = Integer.parseInt(mapHeightField.getText()); statePanel.resizeGameState(statePanel.getGameState().getPhysicalGameState().getWidth(), newHeight); statePanel.repaint(); } catch(Exception ex) { } } }); p1.add(ptmp); } { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); { JButton b = new JButton("Move Player 0"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AI ai = createAI(aiComboBox[0].getSelectedIndex(), 0, currentUtt); if (ai instanceof MouseController) { textArea.setText("Mouse controller is not allowed for this function."); return; } try { long start = System.currentTimeMillis(); ai.reset(); PlayerAction a = ai.getAction(0, statePanel.getGameState()); long end = System.currentTimeMillis(); textArea.setText("Action generated with " + ai.getClass().getSimpleName() + " in " + (end-start) + "ms\n"); textArea.append(ai.statisticsString() + "\n"); textArea.append("Action:\n"); for(Pair<Unit,UnitAction> tmp:a.getActions()) { textArea.append(" " + tmp.m_a + ": " + tmp.m_b + "\n"); } } catch (Exception ex) { ex.printStackTrace(); } } }); ptmp.add(b); } { JButton b = new JButton("Move Player 1"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AI ai = createAI(aiComboBox[1].getSelectedIndex(), 1, currentUtt); if (ai instanceof MouseController) { textArea.setText("Mouse controller is not allowed for this function."); return; } try { long start = System.currentTimeMillis(); ai.reset(); PlayerAction a = ai.getAction(0, statePanel.getGameState()); long end = System.currentTimeMillis(); textArea.setText("Action generated with " + ai.getClass().getSimpleName() + " in " + (end-start) + "ms\n"); textArea.append(ai.statisticsString() + "\n"); textArea.append("Action:\n"); for(Pair<Unit,UnitAction> tmp:a.getActions()) { textArea.append(" " + tmp.m_a + ": " + tmp.m_b + "\n"); } } catch (Exception ex) { ex.printStackTrace(); } } }); ptmp.add(b); } { JButton b = new JButton("Analyze"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (statePanel.getGameState()==null) { textArea.setText("Load a game state first"); return; } try { textArea.setText(""); // Evaluation functions: textArea.append("Evaluation functions:\n"); for(EvaluationFunction ef:efs) { textArea.append(" - " + ef.getClass().getSimpleName() + ": " + ef.evaluate(0, 1, statePanel.getGameState()) + ", " + ef.evaluate(1, 0, statePanel.getGameState()) + "\n"); } textArea.append("\n"); // units: { int n0 = 0, n1 = 0; for(Unit u:statePanel.getGameState().getUnits()) { if (u.getPlayer()==0) n0++; if (u.getPlayer()==1) n1++; } textArea.append("Player 0 has " + n0 + " units\n"); textArea.append("Player 1 has " + n1 + " units\n\n"); } // Branching: // textArea.append("Braching Factor (long, might overflow):\n"); // textArea.append(" - player 0: " + BranchingFactorCalculatorLong.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 0) + "\n"); // textArea.append(" - player 1: " + BranchingFactorCalculatorLong.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 1) + "\n"); // textArea.append("\n"); // textArea.append("Braching Factor (double):\n"); // textArea.append(" - player 0: " + BranchingFactorCalculatorDouble.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 0) + "\n"); // textArea.append(" - player 1: " + BranchingFactorCalculatorDouble.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 1) + "\n"); // textArea.append("\n"); textArea.append("Braching Factor (BigInteger):\n"); textArea.append(" - player 0: " + BranchingFactorCalculatorBigInteger.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 0) + "\n"); textArea.append(" - player 1: " + BranchingFactorCalculatorBigInteger.branchingFactorByResourceUsageSeparatingFast(statePanel.getGameState(), 1) + "\n"); textArea.append("\n"); // Branching: textArea.append("Unit moves:\n"); textArea.append(" - player 0:\n"); if (statePanel.getGameState().canExecuteAnyAction(0)) { PlayerActionGenerator pag0 = new PlayerActionGenerator(statePanel.getGameState(), 0); for(Pair<Unit,List<UnitAction>> tmp:pag0.getChoices()) { textArea.append(" " + tmp.m_a + " has " + tmp.m_b.size() + " actions: " + tmp.m_b + "\n"); } textArea.append("\n"); } textArea.append(" - player 1:\n"); if (statePanel.getGameState().canExecuteAnyAction(1)) { PlayerActionGenerator pag1 = new PlayerActionGenerator(statePanel.getGameState(), 1); for(Pair<Unit,List<UnitAction>> tmp:pag1.getChoices()) { textArea.append(" " + tmp.m_a + " has " + tmp.m_b.size() + " actions: " + tmp.m_b + "\n"); } textArea.append("\n"); } } catch (Exception ex) { ex.printStackTrace(); } } }); ptmp.add(b); } p1.add(ptmp); } { String colorSchemes[] = {"Color Scheme Black","Color Scheme White"}; JComboBox b = new JComboBox(colorSchemes); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox)e.getSource(); if (combo.getSelectedIndex()==0) { statePanel.setColorScheme(PhysicalGameStatePanel.COLORSCHEME_BLACK); } if (combo.getSelectedIndex()==1) { statePanel.setColorScheme(PhysicalGameStatePanel.COLORSCHEME_WHITE); } statePanel.repaint(); } }); b.setMaximumSize(new Dimension(300,24)); p1.add(b); } // p1.add(new JSeparator(SwingConstants.HORIZONTAL)); { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); maxCyclesField = addTextField(ptmp,"Max Cycles:", "3000", 5); defaultDelayField = addTextField(ptmp,"Default Delay:", "10", 5); p1.add(ptmp); } { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); { fullObservabilityBox = new JCheckBox("Full Obsservability"); fullObservabilityBox.setSelected(true); fullObservabilityBox.setAlignmentX(Component.CENTER_ALIGNMENT); fullObservabilityBox.setAlignmentY(Component.TOP_ALIGNMENT); fullObservabilityBox.setMaximumSize(new Dimension(120,20)); fullObservabilityBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statePanel.setFullObservability(fullObservabilityBox.isSelected()); statePanel.repaint(); } }); ptmp.add(fullObservabilityBox); } { slowDownBox = new JCheckBox("Slow Down"); slowDownBox.setAlignmentX(Component.CENTER_ALIGNMENT); slowDownBox.setAlignmentY(Component.TOP_ALIGNMENT); slowDownBox.setMaximumSize(new Dimension(120,20)); slowDownBox.setSelected(true); ptmp.add(slowDownBox); } p1.add(ptmp); } { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel("UnitTypeTable")); unitTypeTableBox = new JComboBox(unitTypeTableNames); unitTypeTableBox.setAlignmentX(Component.CENTER_ALIGNMENT); unitTypeTableBox.setAlignmentY(Component.CENTER_ALIGNMENT); unitTypeTableBox.setMaximumSize(new Dimension(240,20)); unitTypeTableBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = unitTypeTableBox.getSelectedIndex(); UnitTypeTable new_utt = unitTypeTables[idx]; GameState gs = statePanel.getGameState().cloneChangingUTT(new_utt); if (gs!=null) { statePanel.setStateDirect(gs); currentUtt = new_utt; mouseListener.utt = new_utt; } else { System.err.println("Could not change unit type table!"); } } }); ptmp.add(unitTypeTableBox); p1.add(ptmp); } { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); { JButton b = new JButton("Start"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.setMaximumSize(new Dimension(120,20)); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Runnable r = new Runnable() { public void run() { try { AI ai1 = createAI(aiComboBox[0].getSelectedIndex(), 0, currentUtt); AI ai2 = createAI(aiComboBox[1].getSelectedIndex(), 1, currentUtt); int PERIOD1 = Integer.parseInt(defaultDelayField.getText()); int PERIOD2 = Integer.parseInt(defaultDelayField.getText()); JFormattedTextField t1 = (JFormattedTextField)AIOptionsPanelComponents[0].get("TimeBudget"); JFormattedTextField t2 = (JFormattedTextField)AIOptionsPanelComponents[1].get("TimeBudget"); if (t1!=null) PERIOD1 = Integer.parseInt(t1.getText()); if (t2!=null) PERIOD2 = Integer.parseInt(t2.getText()); int PERIOD = PERIOD1 + PERIOD2; if (!slowDownBox.isSelected()) { PERIOD = 1; } int MAXCYCLES = Integer.parseInt(maxCyclesField.getText()); GameState gs = statePanel.getState().clone(); ai1.preGameAnalysis(gs, -1); ai2.preGameAnalysis(gs, -1); boolean gameover = false; JFrame w = null; boolean isMouseController = false; if (ai1 instanceof MouseController) isMouseController = true; if (ai2 instanceof MouseController) isMouseController = true; if ((ai1 instanceof PseudoContinuingAI) && (((PseudoContinuingAI)ai1).getbaseAI() instanceof MouseController)) isMouseController = true; if ((ai2 instanceof PseudoContinuingAI) && (((PseudoContinuingAI)ai2).getbaseAI() instanceof MouseController)) isMouseController = true; if (isMouseController) { PhysicalGameStatePanel pgsp = new PhysicalGameStatePanel(statePanel); pgsp.setStateDirect(gs); w = new PhysicalGameStateMouseJFrame("Game State Visualizer (Mouse)",640,640,pgsp); boolean mousep1 = false; boolean mousep2 = false; if (ai1 instanceof MouseController) { ((MouseController)ai1).setFrame((PhysicalGameStateMouseJFrame)w); mousep1 = true; } else if ((ai1 instanceof PseudoContinuingAI) && (((PseudoContinuingAI)ai1).getbaseAI() instanceof MouseController)) { ((MouseController)((PseudoContinuingAI)ai1).getbaseAI()).setFrame((PhysicalGameStateMouseJFrame)w); mousep1 = true; } if (ai2 instanceof MouseController) { ((MouseController)ai2).setFrame((PhysicalGameStateMouseJFrame)w); mousep2 = true; } else if ((ai2 instanceof PseudoContinuingAI) && (((PseudoContinuingAI)ai2).getbaseAI() instanceof MouseController)) { ((MouseController)((PseudoContinuingAI)ai2).getbaseAI()).setFrame((PhysicalGameStateMouseJFrame)w); mousep2 = true; } if (mousep1 && !mousep2) pgsp.setDrawFromPerspectiveOfPlayer(0); if (!mousep1 && mousep2) pgsp.setDrawFromPerspectiveOfPlayer(1); } else { w = PhysicalGameStatePanel.newVisualizer(gs,640,640,!fullObservabilityBox.isSelected(),statePanel.getColorScheme()); } Trace trace = null; if (saveTraceBox.isSelected()) { trace = new Trace(currentUtt); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); } long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do{ if (System.currentTimeMillis()>=nextTimeToUpdate) { // System.out.println("----------------------------------------"); // System.out.println(gs); PlayerAction pa1 = null; PlayerAction pa2 = null; if (fullObservabilityBox.isSelected()) { pa1 = ai1.getAction(0, gs); pa2 = ai2.getAction(1, gs); } else { pa1 = ai1.getAction(0, new PartiallyObservableGameState(gs,0)); pa2 = ai2.getAction(1, new PartiallyObservableGameState(gs,1)); } if (trace!=null && (!pa1.isEmpty() || !pa2.isEmpty())) { // System.out.println("- (for trace) ---------------------------------------"); // System.out.println(gs); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } synchronized(gs) { gs.issueSafe(pa1); gs.issueSafe(pa2); } // simulate: synchronized(gs) { gameover = gs.cycle(); } w.repaint(); nextTimeToUpdate+=PERIOD; } else { Thread.sleep(1); } if (!w.isVisible()) break; // if the user has closed the window }while(!gameover && gs.getTime()<MAXCYCLES); if (trace!=null) { TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); String traceFileName = FEStatePane.nextTraceName(); // System.out.println("Trace saved as " + traceFileName); XMLWriter xml = new XMLWriter(new FileWriter(traceFileName)); trace.toxml(xml); xml.flush(); } } catch(Exception ex) { ex.printStackTrace(); } } }; (new Thread(r)).start(); } }); ptmp.add(b); } { saveTraceBox = new JCheckBox("Save Trace"); saveTraceBox.setAlignmentX(Component.CENTER_ALIGNMENT); saveTraceBox.setAlignmentY(Component.TOP_ALIGNMENT); saveTraceBox.setMaximumSize(new Dimension(120,20)); ptmp.add(saveTraceBox); } p1.add(ptmp); } for(int player = 0;player<2;player++) { p1.add(new JSeparator(SwingConstants.HORIZONTAL)); { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); JLabel l1 = new JLabel("Player "+player+":"); l1.setAlignmentX(Component.CENTER_ALIGNMENT); l1.setAlignmentY(Component.TOP_ALIGNMENT); ptmp.add(l1); String AINames[] = new String[AIs.length]; for(int i = 0;i<AIs.length;i++) { AINames[i] = AIs[i].getSimpleName(); } aiComboBox[player] = new JComboBox(AINames); aiComboBox[player].setAlignmentX(Component.CENTER_ALIGNMENT); aiComboBox[player].setAlignmentY(Component.TOP_ALIGNMENT); aiComboBox[player].setMaximumSize(new Dimension(300,24)); ptmp.add(aiComboBox[player]); p1.add(ptmp); } continuingBox[player] = new JCheckBox("Continuing"); continuingBox[player].setAlignmentX(Component.CENTER_ALIGNMENT); continuingBox[player].setAlignmentY(Component.TOP_ALIGNMENT); continuingBox[player].setMaximumSize(new Dimension(120,20)); continuingBox[player].setSelected(true); p1.add(continuingBox[player]); AIOptionsPanel[player] = new JPanel(); AIOptionsPanel[player].setLayout(new BoxLayout(AIOptionsPanel[player], BoxLayout.Y_AXIS)); p1.add(AIOptionsPanel[player]); updateAIOptions(AIOptionsPanel[player], player); } aiComboBox[0].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { updateAIOptions(AIOptionsPanel[0], 0); }catch(Exception ex) { ex.printStackTrace(); } } }); aiComboBox[1].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { updateAIOptions(AIOptionsPanel[1], 1); }catch(Exception ex) { ex.printStackTrace(); } } }); // p1.add(Box.createVerticalGlue()); MapGenerator mg = new MapGenerator(currentUtt); GameState initialGs = new GameState(mg.bases8x8(), currentUtt); JPanel p2 = new JPanel(); p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS)); statePanel = new PhysicalGameStatePanel(initialGs); statePanel.setPreferredSize(new Dimension(512, 512)); p2.add(statePanel); textArea = new JTextArea(5, 20); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setEditable(false); scrollPane.setPreferredSize(new Dimension(512, 192)); p2.add(scrollPane, BorderLayout.CENTER); add(p1, BorderLayout.WEST); add(p2, BorderLayout.EAST); mouseListener = new FEStateMouseListener(statePanel, currentUtt); statePanel.addMouseListener(mouseListener); } public void setState(GameState gs) { statePanel.setStateDirect(gs); statePanel.repaint(); mapWidthField.setText(gs.getPhysicalGameState().getWidth()+""); mapHeightField.setText(gs.getPhysicalGameState().getHeight()+""); } private static String nextTraceName() { int idx = 1; do { String name = "trace" + idx + ".xml"; File f = new File(name); if (!f.exists()) return name; idx++; }while(true); } public static JFormattedTextField addTextField(JPanel p, String name, String defaultValue, int columns) { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(name)); JFormattedTextField f = new JFormattedTextField(); f.setValue(defaultValue); // f.setColumns(columns); f.setMaximumSize(new Dimension(80,20)); ptmp.add(f); p.add(ptmp); return f; } public AI createAI(int idx, int player, UnitTypeTable utt) { try { AI ai = createAIInternal(idx, player, utt); // set parameters: List<ParameterSpecification> parameters = ai.getParameters(); for(ParameterSpecification p:parameters) { if (p.type == int.class) { JFormattedTextField f = (JFormattedTextField)AIOptionsPanelComponents[player].get(p.name); int v = Integer.parseInt(f.getText()); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, v); } else if (p.type == long.class) { JFormattedTextField f = (JFormattedTextField)AIOptionsPanelComponents[player].get(p.name); long v = Long.parseLong(f.getText()); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, v); } else if (p.type == float.class) { JFormattedTextField f = (JFormattedTextField)AIOptionsPanelComponents[player].get(p.name); float v = Float.parseFloat(f.getText()); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, v); } else if (p.type == double.class) { JFormattedTextField f = (JFormattedTextField)AIOptionsPanelComponents[player].get(p.name); double v = Double.parseDouble(f.getText()); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, v); } else if (p.type == String.class) { JFormattedTextField f = (JFormattedTextField)AIOptionsPanelComponents[player].get(p.name); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, f.getText()); } else if (p.type == boolean.class) { JCheckBox f = (JCheckBox)AIOptionsPanelComponents[player].get(p.name); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, f.isSelected()); } else { JComboBox f = (JComboBox)AIOptionsPanelComponents[player].get(p.name); Method setter = ai.getClass().getMethod("set" + p.name, p.type); setter.invoke(ai, f.getSelectedItem()); } } if (continuingBox[player].isSelected()) { // If the user wants a "continuous" AI, check if we can wrap it around a continuing decorator: if (ai instanceof AIWithComputationBudget) { if (ai instanceof InterruptibleAI) { ai = new ContinuingAI(ai); } else { ai = new PseudoContinuingAI((AIWithComputationBudget)ai); } } } return ai; }catch(Exception e) { e.printStackTrace(); return null; } } public AI createAIInternal(int idx, int player, UnitTypeTable utt) throws Exception { if (AIs[idx]==MouseController.class) { return new MouseController(null); } else { Constructor cons = AIs[idx].getConstructor(UnitTypeTable.class); AI AI_instance = (AI)cons.newInstance(utt); return AI_instance; } } private void updateAIOptions(JPanel jPanel, int player) throws Exception { // clear previous components: HashMap<String, JComponent> components = AIOptionsPanelComponents[player]; jPanel.removeAll(); components.clear(); AI AIInstance = createAIInternal(aiComboBox[player].getSelectedIndex(), 0, currentUtt); List<ParameterSpecification> parameters = AIInstance.getParameters(); for(ParameterSpecification p:parameters) { if (p.type == int.class || p.type == long.class || p.type == float.class || p.type == double.class || p.type == String.class) { JComponent c = addTextField(jPanel,p.name, p.defaultValue.toString(), p.defaultValue.toString().length()+1); components.put(p.name, c); } else if (p.type == boolean.class) { JCheckBox c = new JCheckBox(p.name); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(120,20)); c.setSelected((Boolean)p.defaultValue); jPanel.add(c); components.put(p.name, c); } else if (p.type == PathFinding.class) { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(p.name)); int defaultValue = 0; PathFinding PFSNames[] = new PathFinding[pathFinders.length]; for(int i = 0;i<pathFinders.length;i++) { PFSNames[i] = pathFinders[i]; if (pathFinders[i].getClass() == p.defaultValue.getClass()) defaultValue = i; } JComboBox c = new JComboBox(PFSNames); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(300,24)); c.setSelectedIndex(defaultValue); ptmp.add(c); jPanel.add(ptmp); components.put(p.name, c); } else if (p.type == EvaluationFunction.class) { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(p.name)); int defaultValue = 0; EvaluationFunction EFSNames[] = new EvaluationFunction[efs.length]; for(int i = 0;i<efs.length;i++) { EFSNames[i] = efs[i]; if (efs[i].getClass() == p.defaultValue.getClass()) defaultValue = i; } JComboBox c = new JComboBox(EFSNames); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(300,24)); c.setSelectedIndex(defaultValue); ptmp.add(c); jPanel.add(ptmp); components.put(p.name, c); } else if (p.type == AI.class) { // we are assuming this is a simple playout AI (so, a smaller list is used here): JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(p.name)); int defaultValue = 0; AI AINames[] = null; if (p.possibleValues==null) { AINames= new AI[PlayoutAIs.length]; for(int i = 0;i<PlayoutAIs.length;i++) { AINames[i] = (AI)PlayoutAIs[i].getConstructor(UnitTypeTable.class).newInstance(currentUtt); if (PlayoutAIs[i] == p.defaultValue.getClass()) defaultValue = i; } } else { AINames = new AI[p.possibleValues.size()]; for(int i = 0;i<p.possibleValues.size();i++) { AINames[i] = (AI)p.possibleValues.get(i); if (p.possibleValues.get(i) == p.defaultValue) defaultValue = i; } } JComboBox c = new JComboBox(AINames); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(300,24)); c.setSelectedIndex(defaultValue); ptmp.add(c); jPanel.add(ptmp); components.put(p.name, c); } else if (p.type == UnitActionProbabilityDistribution.class) { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(p.name)); int defaultValue = 0; UnitActionProbabilityDistribution names[] = null; names= new UnitActionProbabilityDistribution[p.possibleValues.size()]; for(int i = 0;i<p.possibleValues.size();i++) { names[i] = (UnitActionProbabilityDistribution)p.possibleValues.get(i); if (p.possibleValues.get(i) == p.defaultValue) defaultValue = i; } JComboBox c = new JComboBox(names); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(300,24)); c.setSelectedIndex(defaultValue); ptmp.add(c); jPanel.add(ptmp); components.put(p.name, c); } else if (p.possibleValues!=null) { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel(p.name)); int defaultValue = 0; Object []options = new Object[p.possibleValues.size()]; for(int i = 0;i<p.possibleValues.size();i++) { options[i] = p.possibleValues.get(i); if (p.possibleValues.get(i).equals(p.defaultValue)) defaultValue = i; } JComboBox c = new JComboBox(options); c.setAlignmentX(Component.CENTER_ALIGNMENT); c.setAlignmentY(Component.TOP_ALIGNMENT); c.setMaximumSize(new Dimension(300,24)); c.setSelectedIndex(defaultValue); ptmp.add(c); jPanel.add(ptmp); components.put(p.name, c); } else { throw new Exception("Cannot create GUI component for class" + p.type.getName()); } } jPanel.revalidate(); } }
51,111
48.051823
203
java
MicroRTS
MicroRTS-master/src/gui/frontend/FETournamentPane.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import ai.core.AI; import gui.JTextAreaWriter; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.text.DefaultCaret; import rts.units.UnitTypeTable; import tournaments.FixedOpponentsTournament; import tournaments.LoadTournamentAIs; import tournaments.RoundRobinTournament; /** * * @author santi */ public class FETournamentPane extends JPanel { private static final String TOURNAMENT_ROUNDROBIN = "Round Robin"; private static final String TOURNAMENT_FIXED_OPPONENTS = "Fixed Opponents"; private JComboBox tournamentTypeComboBox; private DefaultListModel availableAIsListModel; private JList availableAIsList; private DefaultListModel selectedAIsListModel; private JList selectedAIsList; private DefaultListModel opponentAIsListModel; private JList opponentAIsList; private JButton opponentAddButton; private JButton opponentRemoveButton; private JFileChooser mapFileChooser = new JFileChooser(); private JList mapList; private DefaultListModel mapListModel; private JFormattedTextField iterationsField; private JFormattedTextField maxGameLengthField; private JFormattedTextField timeBudgetField; private JFormattedTextField iterationsBudgetField; private JFormattedTextField preAnalysisTimeField; private JComboBox unitTypeTableBox; private JCheckBox fullObservabilityCheckBox; private JCheckBox selfMatchesCheckBox; private JCheckBox timeoutCheckBox; private JCheckBox gcCheckBox; private JCheckBox tracesCheckBox; private JTextArea tournamentProgressTextArea; private JFileChooser fileChooser = new JFileChooser(); public FETournamentPane() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); { String tournamentTypes[] = {TOURNAMENT_ROUNDROBIN, TOURNAMENT_FIXED_OPPONENTS}; tournamentTypeComboBox = new JComboBox(tournamentTypes); tournamentTypeComboBox.setAlignmentX(Component.CENTER_ALIGNMENT); tournamentTypeComboBox.setAlignmentY(Component.TOP_ALIGNMENT); tournamentTypeComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox)e.getSource(); if (combo.getSelectedIndex()==1) { opponentAIsList.setEnabled(true); opponentAddButton.setEnabled(true); opponentRemoveButton.setEnabled(true); } else { opponentAIsList.setEnabled(false); opponentAddButton.setEnabled(false); opponentRemoveButton.setEnabled(false); } } }); tournamentTypeComboBox.setMaximumSize(new Dimension(300,24)); add(tournamentTypeComboBox); } { JPanel p1 = new JPanel(); p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS)); { JPanel p1left = new JPanel(); p1left.setLayout(new BoxLayout(p1left, BoxLayout.Y_AXIS)); p1left.add(new JLabel("Available AIs")); availableAIsListModel = new DefaultListModel(); for(int i = 0;i<FEStatePane.AIs.length;i++) { availableAIsListModel.addElement(FEStatePane.AIs[i]); } availableAIsList = new JList(availableAIsListModel); availableAIsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); availableAIsList.setLayoutOrientation(JList.VERTICAL); availableAIsList.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(availableAIsList); listScroller.setPreferredSize(new Dimension(200, 200)); p1left.add(listScroller); JButton loadJAR = new JButton("Load Specific JAR"); loadJAR.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fileChooser.showOpenDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { List<Class> cl = LoadTournamentAIs.loadTournamentAIsFromJAR(file.getAbsolutePath()); for(Class c:cl) { boolean exists = false; for(int i = 0;i<availableAIsListModel.size();i++) { Class c2 = (Class)availableAIsListModel.get(i); if (c2.getName().equals(c.getName())) { exists = true; break; } } if (!exists) availableAIsListModel.addElement(c); } } catch (Exception ex) { ex.printStackTrace(); } } } }); p1left.add(loadJAR); JButton loadJARFolder = new JButton("Load All JARS from Folder"); loadJARFolder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fileChooser.showOpenDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { List<Class> cl = LoadTournamentAIs.loadTournamentAIsFromFolder(file.getAbsolutePath()); for(Class c:cl) { boolean exists = false; for(int i = 0;i<availableAIsListModel.size();i++) { Class c2 = (Class)availableAIsListModel.get(i); if (c2.getName().equals(c.getName())) { exists = true; break; } } if (!exists) availableAIsListModel.addElement(c); } } catch (Exception ex) { ex.printStackTrace(); } } } }); p1left.add(loadJARFolder); p1.add(p1left); } { JPanel p1center = new JPanel(); p1center.setLayout(new BoxLayout(p1center, BoxLayout.Y_AXIS)); p1center.add(new JLabel("Selected AIs")); selectedAIsListModel = new DefaultListModel(); selectedAIsList = new JList(selectedAIsListModel); selectedAIsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selectedAIsList.setLayoutOrientation(JList.VERTICAL); selectedAIsList.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(selectedAIsList); listScroller.setPreferredSize(new Dimension(200, 200)); p1center.add(listScroller); JButton add = new JButton("+"); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected[] = availableAIsList.getSelectedIndices(); for(int idx:selected) { selectedAIsListModel.addElement(availableAIsList.getModel().getElementAt(idx)); } } }); p1center.add(add); JButton remove = new JButton("-"); remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selectedIndex = selectedAIsList.getSelectedIndex(); if (selectedIndex>=0) selectedAIsListModel.remove(selectedIndex); } }); p1center.add(remove); p1.add(p1center); } { JPanel p1right = new JPanel(); p1right.setLayout(new BoxLayout(p1right, BoxLayout.Y_AXIS)); p1right.add(new JLabel("Opponent AIs")); opponentAIsListModel = new DefaultListModel(); opponentAIsList = new JList(opponentAIsListModel); opponentAIsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); opponentAIsList.setLayoutOrientation(JList.VERTICAL); opponentAIsList.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(opponentAIsList); listScroller.setPreferredSize(new Dimension(200, 200)); p1right.add(listScroller); opponentAddButton = new JButton("+"); opponentAddButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected[] = availableAIsList.getSelectedIndices(); for(int idx:selected) { opponentAIsListModel.addElement(availableAIsList.getModel().getElementAt(idx)); } } }); p1right.add(opponentAddButton); opponentRemoveButton = new JButton("-"); opponentRemoveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selectedIndex = opponentAIsList.getSelectedIndex(); if (selectedIndex>=0) opponentAIsListModel.remove(selectedIndex); } }); p1right.add(opponentRemoveButton); p1.add(p1right); opponentAIsList.setEnabled(false); opponentAddButton.setEnabled(false); opponentRemoveButton.setEnabled(false); } add(p1); } add(new JSeparator(SwingConstants.HORIZONTAL)); { JPanel p2 = new JPanel(); p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS)); { JPanel p2maps = new JPanel(); p2maps.setLayout(new BoxLayout(p2maps, BoxLayout.Y_AXIS)); p2maps.add(new JLabel("Maps")); mapListModel = new DefaultListModel(); mapList = new JList(mapListModel); mapList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mapList.setLayoutOrientation(JList.VERTICAL); mapList.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(mapList); listScroller.setPreferredSize(new Dimension(200, 100)); p2maps.add(listScroller); JButton add = new JButton("+"); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = mapFileChooser.showOpenDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = mapFileChooser.getSelectedFile(); try { mapListModel.addElement(file.getPath()); } catch (Exception ex) { ex.printStackTrace(); } } } }); p2maps.add(add); JButton remove = new JButton("-"); remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected = mapList.getSelectedIndex(); if (selected>=0) { mapListModel.remove(selected); } } }); p2maps.add(remove); p2.add(p2maps); } p2.add(new JSeparator(SwingConstants.VERTICAL)); { JPanel p2left = new JPanel(); p2left.setLayout(new BoxLayout(p2left, BoxLayout.Y_AXIS)); // N, maxgame length, time budget, iterations budget iterationsField = FEStatePane.addTextField(p2left,"Iterations:", "10", 4); maxGameLengthField = FEStatePane.addTextField(p2left,"Max Game Length:", "3000", 4); timeBudgetField = FEStatePane.addTextField(p2left,"Time Budget:", "100", 5); iterationsBudgetField = FEStatePane.addTextField(p2left,"Iterations Budget:", "-1", 8); preAnalysisTimeField = FEStatePane.addTextField(p2left,"pre-Analisys time budget:", "1000", 8); p2left.setMaximumSize(new Dimension(1000,1000)); // something sufficiently big for all these options p2.add(p2left); } p2.add(new JSeparator(SwingConstants.VERTICAL)); { JPanel p2right = new JPanel(); p2right.setLayout(new BoxLayout(p2right, BoxLayout.Y_AXIS)); { JPanel ptmp = new JPanel(); ptmp.setLayout(new BoxLayout(ptmp, BoxLayout.X_AXIS)); ptmp.add(new JLabel("UnitTypeTable")); unitTypeTableBox = new JComboBox(FEStatePane.unitTypeTableNames); unitTypeTableBox.setAlignmentX(Component.CENTER_ALIGNMENT); unitTypeTableBox.setAlignmentY(Component.CENTER_ALIGNMENT); unitTypeTableBox.setMaximumSize(new Dimension(160,20)); ptmp.add(unitTypeTableBox); p2right.setMaximumSize(new Dimension(1000,1000)); // something sufficiently big for all these options p2right.add(ptmp); } fullObservabilityCheckBox = new JCheckBox("Full Obsservability"); fullObservabilityCheckBox.setSelected(true); p2right.add(fullObservabilityCheckBox); selfMatchesCheckBox = new JCheckBox("Include self-play matches"); selfMatchesCheckBox.setSelected(false); p2right.add(selfMatchesCheckBox); timeoutCheckBox = new JCheckBox("Game over if AI times out"); timeoutCheckBox.setSelected(true); p2right.add(timeoutCheckBox); gcCheckBox = new JCheckBox("Call garbage collector right before each AI call"); gcCheckBox.setSelected(false); p2right.add(gcCheckBox); tracesCheckBox = new JCheckBox("Save game traces"); tracesCheckBox.setSelected(false); p2right.add(tracesCheckBox); // preGameAnalysisCheckBox = new JCheckBox("Give time to the AIs before game starts to analyze initial game state"); // preGameAnalysisCheckBox.setSelected(false); // p2right.add(preGameAnalysisCheckBox); p2.add(p2right); } add(p2); } JButton run = new JButton("Run Tournament"); add(run); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // get all the necessary info: UnitTypeTable utt = FEStatePane.unitTypeTables[unitTypeTableBox.getSelectedIndex()]; String tournamentType = (String)tournamentTypeComboBox.getSelectedItem(); List<AI> selectedAIs = new ArrayList<>(); List<AI> opponentAIs = new ArrayList<>(); List<String> maps = new ArrayList<>(); for(int i = 0;i<selectedAIsListModel.getSize();i++) { Class c = (Class)selectedAIsListModel.get(i); Constructor cons = c.getConstructor(UnitTypeTable.class); selectedAIs.add((AI)cons.newInstance(utt)); } for(int i = 0;i<opponentAIsListModel.getSize();i++) { Class c = (Class)opponentAIsListModel.get(i); Constructor cons = c.getConstructor(UnitTypeTable.class); opponentAIs.add((AI)cons.newInstance(utt)); } for(int i = 0;i<mapListModel.getSize();i++) { String mapname = (String)mapListModel.getElementAt(i); maps.add(mapname); } int iterations = Integer.parseInt(iterationsField.getText()); int maxGameLength = Integer.parseInt(maxGameLengthField.getText()); int timeBudget = Integer.parseInt(timeBudgetField.getText()); int iterationsBudget = Integer.parseInt(iterationsBudgetField.getText()); int preAnalysisBudget = Integer.parseInt(preAnalysisTimeField.getText()); boolean fullObservability = fullObservabilityCheckBox.isSelected(); boolean selfMatches = selfMatchesCheckBox.isSelected(); boolean timeOutCheck = timeoutCheckBox.isSelected(); boolean gcCheck = gcCheckBox.isSelected(); boolean preGameAnalysis = preAnalysisBudget > 0; String prefix = "tournament_"; int idx = 0; // String sufix = ".tsv"; File file; do { idx++; file = new File(prefix + idx); }while(file.exists()); file.mkdir(); String tournamentfolder = file.getName(); final File fileToUse = new File(tournamentfolder + "/tournament.csv"); final String tracesFolder = (tracesCheckBox.isSelected() ? tournamentfolder + "/traces":null); if (tournamentType.equals(TOURNAMENT_ROUNDROBIN)) { if (selectedAIs.size()<2) { tournamentProgressTextArea.append("Select at least two AIs\n"); } else if (maps.isEmpty()) { tournamentProgressTextArea.append("Select at least one map\n"); } else { try { Runnable r = new Runnable() { public void run() { try { Writer writer = new FileWriter(fileToUse); Writer writerProgress = new JTextAreaWriter(tournamentProgressTextArea); new RoundRobinTournament(selectedAIs).runTournament(-1, maps, iterations, maxGameLength, timeBudget, iterationsBudget, preAnalysisBudget, 1000, // 1000 is just to give 1 second to the AIs to load their read/write folder saved content fullObservability, selfMatches, timeOutCheck, gcCheck, preGameAnalysis, utt, tracesFolder, writer, writerProgress, tournamentfolder); writer.close(); } catch(Exception e2) { e2.printStackTrace(); } } }; (new Thread(r)).start(); } catch(Exception e3) { e3.printStackTrace(); } } } else if (tournamentType.equals(TOURNAMENT_FIXED_OPPONENTS)) { if (selectedAIs.isEmpty()) { tournamentProgressTextArea.append("Select at least one AI\n"); } else if (opponentAIs.isEmpty()) { tournamentProgressTextArea.append("Select at least one opponent AI\n"); } else if (maps.isEmpty()) { tournamentProgressTextArea.append("Select at least one map\n"); } else { try { Runnable r = new Runnable() { public void run() { try { Writer writer = new FileWriter(fileToUse); Writer writerProgress = new JTextAreaWriter(tournamentProgressTextArea); new FixedOpponentsTournament(selectedAIs, opponentAIs).runTournament(maps, iterations, maxGameLength, timeBudget, iterationsBudget, preAnalysisBudget, 1000, // 1000 is just to give 1 second to the AIs to load their read/write folder saved content fullObservability, timeOutCheck, gcCheck, preGameAnalysis, utt, tracesFolder, writer, writerProgress, tournamentfolder); writer.close(); } catch(Exception e2) { e2.printStackTrace(); } } }; (new Thread(r)).start(); } catch(Exception e3) { e3.printStackTrace(); } } } }catch(Exception ex) { ex.printStackTrace(); } } }); tournamentProgressTextArea = new JTextArea(5, 20); JScrollPane scrollPane = new JScrollPane(tournamentProgressTextArea); tournamentProgressTextArea.setEditable(false); scrollPane.setPreferredSize(new Dimension(512, 192)); add(scrollPane); DefaultCaret caret = (DefaultCaret)tournamentProgressTextArea.getCaret(); //autoscroll the progress Text Area caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); } }
25,838
50.472112
193
java
MicroRTS
MicroRTS-master/src/gui/frontend/FETracePane.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import gui.PhysicalGameStatePanel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.util.zip.ZipInputStream; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JPanel; import org.jdom.input.SAXBuilder; import rts.GameState; import rts.Trace; import rts.TraceEntry; import util.XMLWriter; /** * * @author santi */ public class FETracePane extends JPanel { Trace currentTrace; int currentGameCycle = 0; PhysicalGameStatePanel statePanel; JFileChooser fileChooser = new JFileChooser(); FEStatePane stateTab; public FETracePane(FEStatePane a_stateTab) { stateTab = a_stateTab; setLayout(new BorderLayout()); JPanel p1 = new JPanel(); p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS)); JPanel p1west = new JPanel(); p1west.setLayout(new BoxLayout(p1west, BoxLayout.Y_AXIS)); { JButton b = new JButton("Load Trace"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { if (file.getAbsolutePath().endsWith(".zip")) { ZipInputStream zip = new ZipInputStream(new FileInputStream(file)); zip.getNextEntry(); // note: this assumes the zip file contains a single trace! currentTrace = new Trace(new SAXBuilder().build(zip).getRootElement()); } else { currentTrace = new Trace(new SAXBuilder().build(file.getAbsolutePath()).getRootElement()); } currentGameCycle = 0; statePanel.setStateDirect(currentTrace.getGameStateAtCycle(currentGameCycle)); statePanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } }); p1west.add(b); } { JButton b = new JButton("Save State"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showSaveDialog((Component)null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { XMLWriter xml = new XMLWriter(new FileWriter(file.getAbsolutePath())); statePanel.getState().getPhysicalGameState().toxml(xml); xml.flush(); } catch (Exception ex) { ex.printStackTrace(); } } } }); p1west.add(b); } { JButton b = new JButton("Copy to state tab"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stateTab.setState(statePanel.getState().clone()); } }); p1west.add(b); } JPanel p1east = new JPanel(); p1east.setLayout(new BoxLayout(p1east, BoxLayout.Y_AXIS)); { JButton b = new JButton("+1 Frame"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!statePanel.getState().gameover()) { currentGameCycle++; GameState tmp_gs = currentTrace.getGameStateAtCycle(currentGameCycle); statePanel.setStateDirect(tmp_gs); statePanel.repaint(); } } }); p1east.add(b); } { JButton b = new JButton("-1 Frame"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentGameCycle>0) { currentGameCycle--; statePanel.setStateDirect(currentTrace.getGameStateAtCycle(currentGameCycle)); statePanel.repaint(); } } }); p1east.add(b); } { JButton b = new JButton("+1 Action"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for(TraceEntry te:currentTrace.getEntries()) { if (te.getTime()>currentGameCycle) { currentGameCycle = te.getTime(); statePanel.setStateDirect(currentTrace.getGameStateAtCycle(currentGameCycle)); statePanel.repaint(); break; } } } }); p1east.add(b); } { JButton b = new JButton("-1 Action"); b.setAlignmentX(Component.CENTER_ALIGNMENT); b.setAlignmentY(Component.TOP_ALIGNMENT); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { TraceEntry target = null; for(TraceEntry te:currentTrace.getEntries()) { if (te.getTime()<currentGameCycle) { if (target==null || te.getTime()>target.getTime()) { target = te; } } } if (target!=null) { currentGameCycle = target.getTime(); statePanel.setStateDirect(currentTrace.getGameStateAtCycle(currentGameCycle)); statePanel.repaint(); } } }); p1east.add(b); } p1.add(p1west); p1.add(p1east); JPanel p2 = new JPanel(); p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS)); statePanel = new PhysicalGameStatePanel((GameState)null); statePanel.setPreferredSize(new Dimension(512, 512)); p2.add(statePanel); add(p1, BorderLayout.NORTH); add(p2, BorderLayout.SOUTH); } }
8,042
37.483254
122
java
MicroRTS
MicroRTS-master/src/gui/frontend/FrontEnd.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; /** * * @author santi */ public class FrontEnd extends JPanel { public FrontEnd() throws Exception { super(new GridLayout(1, 1)); JTabbedPane tabbedPane = new JTabbedPane(); FEStatePane panel1 = new FEStatePane(); tabbedPane.addTab("States", null, panel1, "Load/save states and play games."); JComponent panel2 = new FETracePane(panel1); tabbedPane.addTab("Traces", null, panel2, "Load/save and view replays."); JComponent panel3 = new FETournamentPane(); tabbedPane.addTab("Tournaments", null, panel3, "Run tournaments."); //Add the tabbed pane to this panel. add(tabbedPane); //The following line enables to use scrolling tabs. tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); } protected JComponent makeTextPanel(String text) { JPanel panel = new JPanel(false); JLabel filler = new JLabel(text); filler.setHorizontalAlignment(JLabel.CENTER); panel.setLayout(new GridLayout(1, 1)); panel.add(filler); return panel; } public static void main(String args[]) throws Exception { JFrame frame = new JFrame("microRTS Front End"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new FrontEnd(), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
1,895
30.081967
86
java
MicroRTS
MicroRTS-master/src/gui/frontend/PopUpStateEditorMenu.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.frontend; import gui.PhysicalGameStatePanel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /** * * @author santi */ public class PopUpStateEditorMenu extends JPopupMenu { public PopUpStateEditorMenu(GameState gs, UnitTypeTable utt, int x, int y, PhysicalGameStatePanel panel) { PhysicalGameState pgs = gs.getPhysicalGameState(); Unit u = pgs.getUnitAt(x, y); if (u==null) { if (pgs.getTerrain(x, y)==PhysicalGameState.TERRAIN_NONE) { JMenuItem i1 = new JMenuItem("Set wall"); i1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.setTerrain(x, y, PhysicalGameState.TERRAIN_WALL); panel.gameStateUpdated(); panel.repaint(); } }); add(i1); // add units: for(UnitType ut:utt.getUnitTypes()) { if (ut.isResource) { JMenuItem i2 = new JMenuItem("Add " + ut.name + ""); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.addUnit(new Unit(-1, ut, x, y, 10)); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } else { JMenuItem i2 = new JMenuItem("Add " + ut.name + " (player 0)"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.addUnit(new Unit(0, ut, x, y, 0)); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); JMenuItem i3 = new JMenuItem("Add " + ut.name + " (player 1)"); i3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.addUnit(new Unit(1, ut, x, y, 0)); panel.gameStateUpdated(); panel.repaint(); } }); add(i3); } } } else { JMenuItem i1 = new JMenuItem("Set walkable"); i1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.setTerrain(x, y, PhysicalGameState.TERRAIN_NONE); panel.gameStateUpdated(); panel.repaint(); } }); add(i1); } } else { JMenuItem i1 = new JMenuItem("Remove " + u.getType().name); i1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { pgs.removeUnit(u); panel.gameStateUpdated(); panel.repaint(); } }); add(i1); if (u.getType().isResource || u.getType().canHarvest) { if (u.getResources()>0) { JMenuItem i2 = new JMenuItem("-1 resource"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { u.setResources(u.getResources()-1); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } if (u.getType().isResource || u.getResources()==0) { JMenuItem i2 = new JMenuItem("+1 resource"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { u.setResources(u.getResources()+1); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } if (u.getResources()>9) { JMenuItem i2 = new JMenuItem("-10 resource"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { u.setResources(u.getResources()-10); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } if (u.getType().isResource) { JMenuItem i2 = new JMenuItem("+10 resource"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { u.setResources(u.getResources()+10); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } } if (gs.getUnitAction(u)==null) { if (u.getPlayer()!=-1) { List<UnitAction> actions = u.getUnitActions(gs, 10); for(UnitAction ua:actions) { JMenuItem i2 = new JMenuItem(ua.toString()); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { PlayerAction pa = new PlayerAction(); pa.addUnitAction(u, ua); gs.issue(pa); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } } } else { JMenuItem i2 = new JMenuItem("Cancel action"); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { gs.getUnitActions().remove(u); panel.gameStateUpdated(); panel.repaint(); } }); add(i2); } } } }
7,721
43.125714
110
java
MicroRTS
MicroRTS-master/src/rts/Game.java
package rts; import ai.core.AI; import gui.PhysicalGameStatePanel; import java.lang.reflect.Constructor; import javax.swing.JFrame; import rts.units.UnitTypeTable; /** * Class responsible for creating all objects necessary for a single game and * run the main loop of the game until completion. * @author douglasrizzo */ public class Game { private UnitTypeTable utt; protected rts.GameState gs; protected AI ai1, ai2; private boolean partiallyObservable, headless; private int maxCycles, updateInterval; /** * Create a game from a GameSettings object. * * @param gameSettings a GameSettings object, created either by reading a config file or * through command-ine arguments * @throws Exception when reading the XML file for the map or instantiating AIs from class names */ public Game(GameSettings gameSettings) throws Exception { this(new UnitTypeTable(gameSettings.getUTTVersion(), gameSettings.getConflictPolicy()), gameSettings.getMapLocation(), gameSettings.isHeadless(), gameSettings.isPartiallyObservable(), gameSettings.getMaxCycles(), gameSettings.getUpdateInterval(), gameSettings.getAI1(), gameSettings.getAI2()); } public Game(UnitTypeTable utt, String mapLocation, boolean headless, boolean partiallyObservable, int maxCycles, int updateInterval, String ai1, String ai2) throws Exception { this(utt, mapLocation, headless, partiallyObservable, maxCycles, updateInterval); Constructor cons1 = Class.forName(ai1) .getConstructor(UnitTypeTable.class); Constructor cons2 = Class.forName(ai2) .getConstructor(UnitTypeTable.class); this.ai1 = (AI) cons1.newInstance(utt); this.ai2 = (AI) cons2.newInstance(utt); } public Game(UnitTypeTable utt, String mapLocation, boolean headless, boolean partiallyObservable, int maxCycles, int updateInterval, AI ai1, AI ai2) throws Exception { this(utt, mapLocation, headless, partiallyObservable, maxCycles, updateInterval); this.ai1 = ai1; this.ai2 = ai2; } private Game(UnitTypeTable utt, String mapLocation, boolean headless, boolean partiallyObservable, int maxCycles, int updateInterval) throws Exception { PhysicalGameState pgs = PhysicalGameState.load(mapLocation, utt); gs = new GameState(pgs, utt); this.partiallyObservable = partiallyObservable; this.headless = headless; this.maxCycles = maxCycles; this.updateInterval = updateInterval; } /** * Create a game from a GameSettings object, but also receiving AI players as parameters * @param gameSettings a GameSettings object, created either by reading a config file or * through command-ine arguments * @param player_one AI for player one * @param player_two AI for player two * @throws Exception when reading the XML file for the map */ public Game(GameSettings gameSettings, AI player_one, AI player_two) throws Exception { UnitTypeTable utt = new UnitTypeTable(gameSettings.getUTTVersion(), gameSettings.getConflictPolicy()); PhysicalGameState pgs = PhysicalGameState.load(gameSettings.getMapLocation(), utt); gs = new GameState(pgs, utt); partiallyObservable = gameSettings.isPartiallyObservable(); headless = gameSettings.isHeadless(); maxCycles = gameSettings.getMaxCycles(); updateInterval = gameSettings.getUpdateInterval(); ai1 = player_one; ai2 = player_two; } /** * run the main loop of the game * @throws Exception */ public void start() throws Exception { // Setup UI JFrame w = headless ? null : PhysicalGameStatePanel .newVisualizer(gs, 640, 640, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); start(w); } /** * run the main loop of the game * @param w a window where the game will be displayed * @throws Exception */ public void start(JFrame w) throws Exception { // Reset all players ai1.reset(); ai2.reset(); // pre-game analysis ai1.preGameAnalysis(gs, 0); ai2.preGameAnalysis(gs, 0); boolean gameover = false; while (!gameover && gs.getTime() < maxCycles) { long timeToNextUpdate = System.currentTimeMillis() + updateInterval; rts.GameState playerOneGameState = partiallyObservable ? new PartiallyObservableGameState(gs, 0) : gs; rts.GameState playerTwoGameState = partiallyObservable ? new PartiallyObservableGameState(gs, 1) : gs; rts.PlayerAction pa1 = ai1.getAction(0, playerOneGameState); rts.PlayerAction pa2 = ai2.getAction(1, playerTwoGameState); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate gameover = gs.cycle(); // if not headless mode, wait and repaint the window if (w != null) { if (!w.isVisible()) break; // only wait if the AIs have not already consumed more time than the predetermined interval long waitTime = timeToNextUpdate - System.currentTimeMillis(); if (waitTime >=0) { try { Thread.sleep(waitTime); } catch (Exception e) { e.printStackTrace(); } } // repaint the window after (or regardless of) wait time w.repaint(); } } ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); } }
5,922
34.89697
117
java
MicroRTS
MicroRTS-master/src/rts/GameSettings.java
package rts; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GameSettings { static String getHelpMessage() { return "-f: path to config file\n" + "-s: server IP address\n" + "-p: server port\n" + "-l: launch mode (STANDALONE, GUI, SERVER, CLIENT)\n" + "--serialization: serialization type (1 for XML, 2 for JSON)\n" + "-m: path for the map file\n" + "-c: max cycles\n" + "-i: update interval between each tick, in milliseconds\n" + "--headless: 1 or true, 0 or false\n" + "--partially_observable: 1 or true, 0 or false\n" + "-u: unit type table version\n" + "--conflict_policy: which conflict policy to use\n" + "--ai1: name of the class to be instantiated for player 1\n" + "--ai2: name of the class to be instantiated for player 2"; } public enum LaunchMode { STANDALONE, HUMAN, GUI, SERVER, CLIENT } // Networking private String serverAddress = "localhost"; private int serverPort = 9898; private LaunchMode launchMode = LaunchMode.GUI; private int serializationType = 2; // Default is JSON // Maps private String mapLocation = ""; // Game settings private int maxCycles = 5000; private int updateInterval = 20; private boolean partiallyObservable = false; private int uttVersion = 1; private int conflictPolicy = 1; private boolean includeConstantsInState = true, compressTerrain = false; private boolean headless = false; // Opponents: private String AI2 = "ai.RandomAI"; private String AI1 = "ai.RandomAI"; public GameSettings(LaunchMode launchMode, String serverAddress, int serverPort, int serializationType, String mapLocation, int maxCycles, int updateInterval, boolean partiallyObservable, int uttVersion, int confictPolicy, boolean includeConstantsInState, boolean compressTerrain, boolean headless, String AI1, String AI2) { this.launchMode = launchMode; this.serverAddress = serverAddress; this.serverPort = serverPort; this.serializationType = serializationType; this.mapLocation = mapLocation; this.maxCycles = maxCycles; this.updateInterval = updateInterval; this.partiallyObservable = partiallyObservable; this.uttVersion = uttVersion; this.conflictPolicy = confictPolicy; this.includeConstantsInState = includeConstantsInState; this.compressTerrain = compressTerrain; this.headless = headless; this.AI1 = AI1; this.AI2 = AI2; } public String getServerAddress() { return serverAddress; } public int getServerPort() { return serverPort; } public int getSerializationType() { return serializationType; } public String getMapLocation() { return mapLocation; } public int getMaxCycles() { return maxCycles; } public int getUpdateInterval() { return updateInterval; } public boolean isPartiallyObservable() { return partiallyObservable; } public int getUTTVersion() { return uttVersion; } public int getConflictPolicy() { return conflictPolicy; } public LaunchMode getLaunchMode() { return launchMode; } public String getAI1() { return AI1; } public String getAI2() { return AI2; } public boolean isIncludeConstantsInState() { return includeConstantsInState; } public boolean isCompressTerrain() { return compressTerrain; } public boolean isHeadless() { return headless; } /** * Create a GameSettings object from a list of command-line arguments * @param args a String array containing command-line arguments */ public GameSettings(String[] args) { overrideFromArgs(args); } /** * Use a list of command-line arguments to replace the attribute values of the current * GameSettings * * -s: server IP address * -p: server port * -l: launch mode (see @launchMode) * --serialization: serialization type (1 for XML, 2 for JSON) * -m: path for the map file * -c: max cycles * -i: update interval between each tick, in milliseconds * --headless: headless: 1 or true, 0 or false * --partially_observable: 1 or true, 0 or false * -u: unit type table version * --conflict_policy: which conflict policy to use * --ai1: name of the class to be instantiated for player 1 * --ai2: name of the class to be instantiated for player 2 * * @param args a String array containing command-line arguments * @return */ public GameSettings overrideFromArgs(String[] args) { for (int i = args.length; i > 0; i--) { switch (args[i - 1]) { case "-s": serverAddress = args[i]; break; case "-p": serverPort = Integer.parseInt(args[i]); break; case "-l": launchMode = LaunchMode.valueOf(args[i]); break; case "--serialization": serializationType = Integer.parseInt(args[i]); break; case "-m": mapLocation = args[i]; break; case "-c": maxCycles = Integer.parseInt(args[i]); break; case "-i": updateInterval = Integer.parseInt(args[i]); break; case "--headless": headless = args[i].equals("1") || Boolean.parseBoolean(args[i]); break; case "--partially_observable": partiallyObservable = args[i].equals("1") || Boolean.parseBoolean(args[i]); break; case "-u": uttVersion = Integer.parseInt(args[i]); break; case "--conflict_policy": conflictPolicy = Integer.parseInt(args[i]); break; case "--ai1": AI1 = args[i]; break; case "--ai2": AI2 = args[i]; break; default: break; } } return this; } /** * Fetches the default configuration file which will be located in the root direction called * "config.properties". */ public static Properties fetchDefaultConfig() throws IOException { Properties prop = new Properties(); InputStream is = GameSettings.class.getResourceAsStream("/config.properties"); if (is == null) is = new FileInputStream("resources/config.properties"); prop.load(is); return prop; } /** * Fetches the configuration file which will be located in the path on propertiesFile. */ public static Properties fetchConfig(String propertiesFile) throws IOException { Properties prop = new Properties(); InputStream is = GameSettings.class.getResourceAsStream(propertiesFile); if (is == null) is = new FileInputStream(propertiesFile); prop.load(is); return prop; } /** * Generates game settings based on the provided configuration file. */ public static GameSettings loadFromConfig(Properties prop) { assert !prop.isEmpty(); String serverAddress = prop.getProperty("server_address", "localhost"); int serverPort = readIntegerProperty(prop, "server_port", 9898); int serializationType = readIntegerProperty(prop, "serialization_type", 2); String mapLocation = prop.getProperty("map_location"); int maxCycles = readIntegerProperty(prop, "max_cycles", 5000); int updateInterval = readIntegerProperty(prop, "update_interval", 20); boolean partiallyObservable = Boolean.parseBoolean(prop.getProperty("partially_observable")); int uttVersion = readIntegerProperty(prop, "UTT_version", 2); int conflictPolicy = readIntegerProperty(prop, "conflict_policy", 1); LaunchMode launchMode = LaunchMode.valueOf(prop.getProperty("launch_mode", "GUI")); boolean includeConstantsInState = Boolean.parseBoolean(prop.getProperty("constants_in_state", "true")); boolean compressTerrain = Boolean.parseBoolean(prop.getProperty("compress_terrain", "false")); boolean headless = Boolean.parseBoolean(prop.getProperty("headless", "false")); String AI1 = prop.getProperty("AI1", "ai.RandomAI"); String AI2 = prop.getProperty("AI2", "ai.RandomAI"); return new GameSettings(launchMode, serverAddress, serverPort, serializationType, mapLocation, maxCycles, updateInterval, partiallyObservable, uttVersion, conflictPolicy, includeConstantsInState, compressTerrain, headless, AI1, AI2); } public static int readIntegerProperty(Properties prop, String name, int defaultValue) { String stringValue = prop.getProperty(name); if (stringValue == null) return defaultValue; return Integer.parseInt(stringValue); } @Override public String toString() { return "----------Game Settings----------\n" + "Running as Server: " + getLaunchMode().toString() + "\n" + "Server Address: " + getServerAddress() + "\n" + "Server Port: " + getServerPort() + "\n" + "Serialization Type: " + getSerializationType() + "\n" + "Map Location: " + getMapLocation() + "\n" + "Max Cycles: " + getMaxCycles() + "\n" + "Partially Observable: " + isPartiallyObservable() + "\n" + "Rules Version: " + getUTTVersion() + "\n" + "Conflict Policy: " + getConflictPolicy() + "\n" + "AI1: " + getAI1() + "\n" + "AI2: " + getAI2() + "\n" + "------------------------------------------------"; } }
10,510
34.510135
111
java
MicroRTS
MicroRTS-master/src/rts/GameState.java
package rts; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * A fully-observable game state * @author santi */ public class GameState { public static final boolean REPORT_ILLEGAL_ACTIONS = false; static Random r = new Random(); // only used if the action conflict resolution strategy is set to random protected int unitCancelationCounter = 0; // only used if the action conflict resolution strategy is set to alternating protected int time = 0; protected PhysicalGameState pgs; protected HashMap<Unit,UnitActionAssignment> unitActions = new LinkedHashMap<>(); protected UnitTypeTable utt; protected int [][][][] vectorObservation; public static final int numVectorObservationFeatureMaps = 5; /** * Initializes the GameState with a PhysicalGameState and a UnitTypeTable * @param a_pgs * @param a_utt */ public GameState(PhysicalGameState a_pgs, UnitTypeTable a_utt) { pgs = a_pgs; utt = a_utt; } /** * Current game timestep (frames since beginning) * @return */ public int getTime() { return time; } /** * Removes a unit from the game * @param u */ public void removeUnit(Unit u) { pgs.removeUnit(u); unitActions.remove(u); } /** * @see PhysicalGameState#getPlayer(int) * @param ID * @return */ public Player getPlayer(int ID) { return pgs.getPlayer(ID); } /** * @see PhysicalGameState#getUnit(long) * @param ID * @return */ public Unit getUnit(long ID) { return pgs.getUnit(ID); } /** * @see PhysicalGameState#getUnits() * @return */ public List<Unit> getUnits() { return pgs.getUnits(); } /** * Returns a map with the units and the actions assigned to them * @return */ public HashMap<Unit,UnitActionAssignment> getUnitActions() { return unitActions; } public UnitTypeTable getUnitTypeTable() { return utt; } /** * Returns the action of a unit * @param u * @return */ public UnitAction getUnitAction(Unit u) { UnitActionAssignment uaa = unitActions.get(u); if (uaa==null) return null; return uaa.action; } /** * Returns the action assigned to a unit * @param u * @return */ public UnitActionAssignment getActionAssignment(Unit u) { return unitActions.get(u); } /** * Indicates whether all units owned by the players have a valid action or not * @return */ public boolean isComplete() { for(Unit u : pgs.units) { if (u.getPlayer() != -1) { UnitActionAssignment uaa = unitActions.get(u); if (uaa == null) return false; if (uaa.action == null) return false; } } return true; } /** * @see PhysicalGameState#winner() * @return */ public int winner() { return pgs.winner(); } /** * @see PhysicalGameState#gameover() * @return */ public boolean gameover() { return pgs.gameover(); } /** * Returns the {@link PhysicalGameState} associated with this state * @return */ public PhysicalGameState getPhysicalGameState() { return pgs; } /** * Returns true if there is no unit in the specified position and no unit is executing * an action that will use that position * @param x coordinate of the position * @param y coordinate of the position * @return */ public boolean free(int x, int y) { if (pgs.getTerrain(x, y)!=PhysicalGameState.TERRAIN_NONE) return false; for(Unit u:pgs.units) { if (u.getX()==x && u.getY()==y) return false; } for(UnitActionAssignment ua:unitActions.values()) { if (ua.action.type==UnitAction.TYPE_MOVE || ua.action.type==UnitAction.TYPE_PRODUCE) { Unit u = ua.unit; if (ua.action.getDirection()==UnitAction.DIRECTION_UP && u.getX()==x && u.getY()==y+1) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_RIGHT && u.getX()==x-1 && u.getY()==y) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_DOWN && u.getX()==x && u.getY()==y-1) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_LEFT && u.getX()==x+1 && u.getY()==y) return false; } } return true; } /** * Returns a boolean array with true if there is no unit in * the specified position and no unit is executing an action that will use that position * @return */ public boolean[][] getAllFree() { boolean free[][]=pgs.getAllFree(); for(UnitActionAssignment ua:unitActions.values()) { if (ua.action.type==UnitAction.TYPE_MOVE || ua.action.type==UnitAction.TYPE_PRODUCE) { Unit u = ua.unit; if (ua.action.getDirection()==UnitAction.DIRECTION_UP ) free[u.getX()][u.getY()-1]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_RIGHT) free[u.getX()+1][u.getY()]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_DOWN ) free[u.getX()][u.getY()+1]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_LEFT) free[u.getX()-1][u.getY()]=false; } } return free; } /** * Returns whether the cell is observable. * For fully observable game states, all the cells are observable. * @param x * @param y * @return */ public boolean observable(int x, int y) { return true; } /** * Issues a player action * @param pa * @return "true" is any action different from NONE was issued */ public boolean issue(PlayerAction pa) { boolean returnValue = false; for(Pair<Unit,UnitAction> p:pa.actions) { // if (p.m_a==null) { // System.err.println("Issuing an action to a null unit!!!"); // System.exit(1); // } // if (unitActions.get(p.m_a)!=null) { // System.err.println("Issuing an action to a unit with another action!"); // } else // { // check for conflicts: ResourceUsage ru = p.m_b.resourceUsage(p.m_a, pgs); for(UnitActionAssignment uaa:unitActions.values()) { if (!uaa.action.resourceUsage(uaa.unit, pgs).consistentWith(ru, this)) { // conflicting actions: if (uaa.time==time) { // The actions were issued in the same game cycle, so it's normal boolean cancel_old = false; boolean cancel_new = false; switch(utt.getMoveConflictResolutionStrategy()) { default: System.err.println("Unknown move conflict resolution strategy in the UnitTypeTable!: " + utt.getMoveConflictResolutionStrategy()); System.err.println("Defaulting to MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH"); case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH: cancel_old = cancel_new = true; break; case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM: if (r.nextInt(2)==0) cancel_new = true; else cancel_old = true; break; case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING: if ((unitCancelationCounter%2)==0) cancel_new = true; else cancel_old = true; unitCancelationCounter++; break; } int duration1 = uaa.action.ETA(uaa.unit); int duration2 = p.m_b.ETA(p.m_a); if (cancel_old) { // System.out.println("Old action canceled: " + uaa.unit.getID() + ", " + uaa.action); uaa.action = new UnitAction(UnitAction.TYPE_NONE,Math.min(duration1,duration2)); } if (cancel_new) { // System.out.println("New action canceled: " + p.m_a.getID() + ", " + p.m_b); p = new Pair<>(p.m_a, new UnitAction(UnitAction.TYPE_NONE,Math.min(duration1,duration2))); } } else { // This is more a problem, since it means there is a bug somewhere... // (probably in one of the AIs) System.err.println("Inconsistent actions were executed!"); System.err.println(uaa); System.err.println(" Resources: " + uaa.action.resourceUsage(uaa.unit, pgs)); System.err.println(p.m_a + " assigned action " + p.m_b + " at time " + time); System.err.println(" Resources: " + ru); System.err.println("Player resources: " + pgs.getPlayer(0).getResources() + ", " + pgs.getPlayer(1).getResources()); System.err.println("Resource Consistency: " + uaa.action.resourceUsage(uaa.unit, pgs).consistentWith(ru, this)); try { throw new Exception("dummy"); // just to be able to print the stack trace }catch(Exception e) { e.printStackTrace(); } // only the newly issued action is cancelled, since it's the problematic one... p.m_b = new UnitAction(UnitAction.TYPE_NONE); } } } UnitActionAssignment uaa = new UnitActionAssignment(p.m_a, p.m_b, time); unitActions.put(p.m_a,uaa); if (p.m_b.type!=UnitAction.TYPE_NONE) returnValue = true; // System.out.println("Issuing action " + p.m_b + " to " + p.m_a); // } } return returnValue; } /** * Issues a player action, with additional checks for validity. This function is slower * than "issue", and should not be used internally by any AI. It is used externally in the main loop * to verify that the actions proposed by an AI are valid, before sending them to the game. * @param pa * @return "true" is any action different from NONE was issued */ public boolean issueSafe(PlayerAction pa) { if (!pa.integrityCheck()) throw new Error("PlayerAction inconsistent before 'issueSafe'"); if (!integrityCheck()) throw new Error("GameState inconsistent before 'issueSafe'"); for(Pair<Unit,UnitAction> p:pa.actions) { if (p.m_a==null) { System.err.println("Issuing an action to a null unit!!!"); System.exit(1); } if (!p.m_a.canExecuteAction(p.m_b, this)) { if (REPORT_ILLEGAL_ACTIONS) { System.err.println("Issuing a non legal action to unit " + p.m_a + "!! Ignoring it..."); } // replace the action by a NONE action of the same duration: int l = p.m_b.ETA(p.m_a); p.m_b = new UnitAction(UnitAction.TYPE_NONE, l); } // get the unit that corresponds to that action (since the state might have been cloned): if (pgs.units.indexOf(p.m_a)==-1) { boolean found = false; for(Unit u:pgs.units) { if (u.getClass()==p.m_a.getClass() && // u.getID() == p.m_a.getID()) { u.getX()==p.m_a.getX() && u.getY()==p.m_a.getY()) { p.m_a = u; found = true; break; } } if (!found) { System.err.println("Inconsistent order: " + pa); System.err.println(this); System.err.println("The problem was with unit " + p.m_a); } } { // check to see if the action is legal! ResourceUsage r = p.m_b.resourceUsage(p.m_a, pgs); for(int position:r.getPositionsUsed()) { int y = position/pgs.getWidth(); int x = position%pgs.getWidth(); if (pgs.getTerrain(x, y) != PhysicalGameState.TERRAIN_NONE || pgs.getUnitAt(x, y) != null) { UnitAction new_ua = new UnitAction(UnitAction.TYPE_NONE, p.m_b.ETA(p.m_a)); System.err.println("Player " + p.m_a.getPlayer() + " issued an illegal move action (to "+x+","+y+") to unit "+p.m_a.getID()+" at time "+getTime()+", cancelling and replacing by " + new_ua); System.err.println(" Action: " + p.m_b); System.err.println(" Resources used by the action: " + r); System.err.println(" Unit at that coordinate " + pgs.getUnitAt(x, y)); p.m_b = new_ua; } } } } boolean returnValue = issue(pa); if (!integrityCheck()) throw new Error("GameState inconsistent after 'issueSafe': " + pa); return returnValue; } /** * Indicates whether a player can issue an action in this state * @param pID the player ID * @return true if the player can execute any action */ public boolean canExecuteAnyAction(int pID) { for(Unit u : pgs.getUnits()) { if (u.getPlayer() == pID) { if (unitActions.get(u) == null) return true; } } return false; } /** * This function checks whether the intended unit action has any conflicts with some * other action. It assumes that the UnitAction ua is valid (i.e. one of the * actions that the unit can potentially execute) * @param u * @param ua * @return */ public boolean isUnitActionAllowed(Unit u, UnitAction ua) { PlayerAction empty = new PlayerAction(); if (ua.getType()==UnitAction.TYPE_MOVE) { int x2 = u.getX() + UnitAction.DIRECTION_OFFSET_X[ua.getDirection()]; int y2 = u.getY() + UnitAction.DIRECTION_OFFSET_Y[ua.getDirection()]; if (x2<0 || y2<0 || x2>=getPhysicalGameState().getWidth() || y2>=getPhysicalGameState().getHeight() || getPhysicalGameState().getTerrain(x2, y2) == PhysicalGameState.TERRAIN_WALL || getPhysicalGameState().getUnitAt(x2, y2) != null) return false; } // Generate the reserved resources: for(Unit u2:pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u2); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u2, pgs); empty.r.merge(ru); } } return ua.resourceUsage(u, pgs).consistentWith(empty.getResourceUsage(), this); } /** * * @param unit * @return */ public List<PlayerAction> getPlayerActionsSingleUnit(Unit unit) { List<PlayerAction> l = new LinkedList<>(); PlayerAction empty = new PlayerAction(); l.add(empty); // Generate the reserved resources: for(Unit u:pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); empty.r.merge(ru); } } if (unitActions.get(unit)==null) { l = empty.cartesianProduct(unit.getUnitActions(this), unit, this); } return l; } /** * Returns the list of {@link PlayerAction} for a given player * @param playerID the player ID * @return */ public List<PlayerAction> getPlayerActions(int playerID) { List<PlayerAction> l = new LinkedList<>(); PlayerAction empty = new PlayerAction(); l.add(empty); // Generate the reserved resources: for(Unit u:pgs.getUnits()) { // if (u.getPlayer()==pID) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); empty.r.merge(ru); } // } } for(Unit u:pgs.getUnits()) { if (u.getPlayer()==playerID) { if (unitActions.get(u)==null) { List<PlayerAction> l2 = new LinkedList<>(); for(PlayerAction pa:l) { l2.addAll(pa.cartesianProduct(u.getUnitActions(this), u, this)); } l = l2; } } } return l; } /** * Returns the time the next unit action will complete, or current time * if a player can act * @return */ public int getNextChangeTime() { int nextChangeTime = -1; for(Player player:pgs.players) { if (canExecuteAnyAction(player.ID)) return time; } for(UnitActionAssignment uaa:unitActions.values()) { int t = uaa.time + uaa.action.ETA(uaa.unit); if (nextChangeTime == -1 || t < nextChangeTime) nextChangeTime = t; } if (nextChangeTime == -1) return time; return nextChangeTime; } /** * Runs a game cycle, execution all assigned actions * @return whether the game was over */ public boolean cycle() { time++; List<UnitActionAssignment> readyToExecute = new LinkedList<>(); for(UnitActionAssignment uaa:unitActions.values()) { if (uaa.action.ETA(uaa.unit)+uaa.time<=time) readyToExecute.add(uaa); } // execute the actions: for(UnitActionAssignment uaa:readyToExecute) { unitActions.remove(uaa.unit); // System.out.println("Executing action for " + u + " issued at time " + uaa.time + " with duration " + uaa.action.ETA(uaa.unit)); uaa.action.execute(uaa.unit,this); } return gameover(); } /** * Forces the execution of all assigned actions */ public void forceExecuteAllActions() { List<UnitActionAssignment> readyToExecute = new LinkedList<>(unitActions.values()); // execute all the actions: for(UnitActionAssignment uaa:readyToExecute) { unitActions.remove(uaa.unit); uaa.action.execute(uaa.unit,this); } } /* * @see java.lang.Object#clone() */ public GameState clone() { GameState gs = new GameState(pgs.clone(), utt); gs.time = time; gs.unitCancelationCounter = unitCancelationCounter; for(UnitActionAssignment uaa:unitActions.values()) { Unit u = uaa.unit; int idx = pgs.getUnits().indexOf(u); if (idx==-1) { System.out.println("Problematic game state:"); System.out.println(this); System.out.println("Problematic action:"); System.out.println(uaa); throw new Error("Inconsistent game state during cloning..."); } else { Unit u2 = gs.pgs.getUnits().get(idx); gs.unitActions.put(u2,new UnitActionAssignment(u2, uaa.action, uaa.time)); } } return gs; } /** * This method does a quick clone, that shares the same PGS, but different unit assignments * @param pa * @return */ public GameState cloneIssue(PlayerAction pa) { GameState gs = new GameState(pgs, utt); gs.time = time; gs.unitCancelationCounter = unitCancelationCounter; gs.unitActions.putAll(unitActions); gs.issue(pa); return gs; } /** * Clone this game state, replacing the active {@link UnitTypeTable} * @param new_utt * @return the new GameState */ public GameState cloneChangingUTT(UnitTypeTable new_utt) { GameState gs = clone(); gs.utt = new_utt; for(Unit u:gs.getUnits()) { UnitType new_type = new_utt.getUnitType(u.getType().name); if (new_type == null) return null; if (u.getHitPoints() == u.getType().hp) u.setHitPoints(new_type.hp); u.setType(new_type); } return gs; } /** * Returns the resources being used for all actions issued * in current cycle * @return */ public ResourceUsage getResourceUsage() { ResourceUsage base_ru = new ResourceUsage(); for(Unit u : pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); base_ru.merge(ru); } } return base_ru; } /* * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (!(o instanceof GameState)) return false; GameState s2 = (GameState)o; if(this.getTime() != s2.getTime()) return false; if (!pgs.equivalents(s2.pgs)) return false; // compare actions: int n = pgs.units.size(); for(int i = 0;i<n;i++) { UnitActionAssignment uaa = unitActions.get(pgs.units.get(i)); UnitActionAssignment uaa2 = s2.unitActions.get(s2.pgs.units.get(i)); if (uaa==null) { if (uaa2!=null) return false; } else { if (uaa2==null) return false; if (uaa.time!=uaa2.time) return false; if (!uaa.action.equals(uaa2.action)) return false; } } return true; } /** * Verifies integrity: if an action was assigned to non-existing unit * or two actions were assigned to the same unit, integrity is violated * @return */ public boolean integrityCheck() { List<Unit> alreadyUsed = new LinkedList<>(); for(UnitActionAssignment uaa:unitActions.values()) { Unit u = uaa.unit; int idx = pgs.getUnits().indexOf(u); if (idx==-1) { System.err.println("integrityCheck: unit does not exist!"); return false; } if (alreadyUsed.contains(u)) { System.err.println("integrityCheck: two actions to the same unit!"); return false; } alreadyUsed.add(u); } return true; } /** * Shows {@link UnitActionAssignment}s on the terminal */ public void dumpActionAssignments() { for(Unit u:pgs.getUnits()) { if (u.getPlayer()>=0) { UnitActionAssignment uaa = unitActions.get(u); if (uaa==null) { System.out.println(u + " : -"); } else { System.out.println(u + " : " + uaa.action + " at " + uaa.time); } } } } /* * @see java.lang.Object#toString() */ public String toString() { StringBuilder tmp = new StringBuilder("ObservableGameState: " + time + "\n"); for(Player p:pgs.getPlayers()) tmp.append("player ").append(p.ID).append(": ").append(p.getResources()).append("\n"); for(Unit u:unitActions.keySet()) { UnitActionAssignment ua = unitActions.get(u); if (ua==null) { tmp.append(" ").append(u).append(" -> null (ERROR!)\n"); } else { tmp.append(" ").append(u).append(" -> ").append(ua.time).append(" ").append(ua.action).append("\n"); } } tmp.append(pgs); return tmp.toString(); } /** * Writes a XML representation of this state into a XMLWriter * * @param w */ public void toxml(XMLWriter w) { toxml(w, true, false); } /** * Writes a XML representation of this state into a XMLWriter * * @param w */ public void toxml(XMLWriter w, boolean includeConstants, boolean compressTerrain) { w.tagWithAttributes(this.getClass().getName(), "time=\"" + time + "\""); pgs.toxml(w, includeConstants, compressTerrain); w.tag("actions"); for (Unit u : unitActions.keySet()) { UnitActionAssignment uaa = unitActions.get(u); w.tagWithAttributes("unitAction", "ID=\"" + uaa.unit.getID() + "\" time=\"" + uaa.time + "\""); uaa.action.toxml(w); w.tag("/unitAction"); } w.tag("/actions"); w.tag("/" + this.getClass().getName()); } /** * Dumps this state to a XML file. * It can be reconstructed later (e.g. with {@link #fromXML(String, UnitTypeTable)} * @param path */ public void toxml(String path) { try { XMLWriter dumper = new XMLWriter(new FileWriter(path)); this.toxml(dumper); dumper.close(); } catch (IOException e) { System.err.println("Error while writing state to: " + path); e.printStackTrace(); } } /** * Writes a JSON representation of this state * * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { toJSON(w, true, false); } /** * Writes a JSON representation of this state * * @param w * @throws Exception */ public void toJSON(Writer w, boolean includeConstants, boolean compressTerrain) throws Exception { w.write("{"); w.write("\"time\":" + time + ",\"pgs\":"); pgs.toJSON(w, includeConstants, compressTerrain); w.write(",\"actions\":["); boolean first = true; for (Unit u : unitActions.keySet()) { if (!first) { w.write(","); } first = false; UnitActionAssignment uaa = unitActions.get(u); w.write("{\"ID\":" + uaa.unit.getID() + ", \"time\":" + uaa.time + ", \"action\":"); uaa.action.toJSON(w); w.write("}"); } w.write("]"); w.write("}"); } /** * Constructs a GameState from a XML Element * @param e * @param utt * @return */ public static GameState fromXML(Element e, UnitTypeTable utt) throws Exception { PhysicalGameState pgs = PhysicalGameState.fromXML(e.getChild(PhysicalGameState.class.getName()), utt); GameState gs = new GameState(pgs, utt); gs.time = Integer.parseInt(e.getAttributeValue("time")); Element actions_e = e.getChild("actions"); for(Object o:actions_e.getChildren()) { Element action_e = (Element)o; long ID = Long.parseLong(action_e.getAttributeValue("ID")); Unit u = gs.getUnit(ID); int time = Integer.parseInt(action_e.getAttributeValue("time")); UnitAction ua = UnitAction.fromXML(action_e.getChild("UnitAction"), utt); UnitActionAssignment uaa = new UnitActionAssignment(u, ua, time); gs.unitActions.put(u, uaa); } return gs; } /** * Returns the GameState previously dumped (e.g. with {@link #toxml(String)} from the specified file. * @param utt * @param path * @return */ public static GameState fromXML(String path, UnitTypeTable utt) { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(path); Document document = null; GameState reconstructed = null; try { document = (Document) builder.build(xmlFile); } catch (JDOMException | IOException e) { System.err.println("Error while opening file: '" + path + "'. Returning null."); e.printStackTrace(); } try { reconstructed = GameState.fromXML(document.getRootElement(), utt); } catch (Exception e) { System.err.println("ERror while reconstructing the state from the XML element. Returning null."); e.printStackTrace(); } return reconstructed; } /** * Constructs a GameState from JSON * @param JSON * @param utt * @return */ public static GameState fromJSON(String JSON, UnitTypeTable utt) { JsonObject o = Json.parse(JSON).asObject(); PhysicalGameState pgs = PhysicalGameState.fromJSON(o.get("pgs").asObject(), utt); GameState gs = new GameState(pgs, utt); gs.time = o.getInt("time", 0); JsonArray actions_a = o.get("actions").asArray(); for(JsonValue v:actions_a.values()) { JsonObject uaa_o = v.asObject(); long ID = uaa_o.getLong("ID", -1); Unit u = gs.getUnit(ID); int time = uaa_o.getInt("time", 0); UnitAction ua = UnitAction.fromJSON(uaa_o.get("action").asObject(), utt); UnitActionAssignment uaa = new UnitActionAssignment(u, ua, time); gs.unitActions.put(u, uaa); } return gs; } /** * Constructs a vector observation for a player * @param player * @return a vector observation for the specified player */ public int [][][] getVectorObservation(int player){ if (vectorObservation == null) { vectorObservation = new int[2][numVectorObservationFeatureMaps][pgs.height][pgs.width]; } // hitpointsMatrix is vectorObservation[player][0] // resourcesMatrix is vectorObservation[player][1] // playersMatrix is vectorObservation[player][2] // unitTypesMatrix is vectorObservation[player][3] // unitActionMatrix is vectorObservation[player][4] for (int i=0; i<vectorObservation[player][0].length; i++) { Arrays.fill(vectorObservation[player][0][i], 0); Arrays.fill(vectorObservation[player][1][i], 0); Arrays.fill(vectorObservation[player][4][i], 0); // temp default value for empty spaces Arrays.fill(vectorObservation[player][2][i], -1); Arrays.fill(vectorObservation[player][3][i], -1); } for (int i = 0; i < pgs.units.size(); i++) { Unit u = pgs.units.get(i); UnitActionAssignment uaa = unitActions.get(u); vectorObservation[player][0][u.getY()][u.getX()] = u.getHitPoints(); vectorObservation[player][1][u.getY()][u.getX()] = u.getResources(); vectorObservation[player][2][u.getY()][u.getX()] = (u.getPlayer() + player) % 2; vectorObservation[player][3][u.getY()][u.getX()] = u.getType().ID; if (uaa != null) { vectorObservation[player][4][u.getY()][u.getX()] = uaa.action.type; } else { vectorObservation[player][4][u.getY()][u.getX()] = UnitAction.TYPE_NONE; } } // normalize by getting rid of -1 for(int i=0; i<vectorObservation[player][2].length; i++) { for(int j=0; j<vectorObservation[player][2][i].length; j++) { vectorObservation[player][3][i][j] += 1; vectorObservation[player][2][i][j] += 1; } } return vectorObservation[player]; } }
33,704
34.628964
213
java
MicroRTS
MicroRTS-master/src/rts/MicroRTS.java
package rts; import gui.frontend.FrontEnd; import java.net.ServerSocket; import java.net.Socket; /*** * The main class for running a MicroRTS game. To modify existing settings change the file "config.properties". */ public class MicroRTS { public static void main(String args[]) throws Exception { for (int i = args.length; i > 0; i--) { if (args[i - 1].equals("-h")) { System.out.println(GameSettings.getHelpMessage()); return; } } String configFile = "resources/config.properties"; for (int i = args.length; i > 0; i--) { if (args[i - 1].equals("-f")) { configFile = args[i]; } } GameSettings gameSettings; try { gameSettings = GameSettings.loadFromConfig(GameSettings.fetchConfig(configFile)) .overrideFromArgs(args); } catch (java.io.FileNotFoundException ex) { System.err.println( "File " + configFile + " not found. Trying to initialize from command-line args."); gameSettings = new GameSettings(args); } System.out.println(gameSettings); switch (gameSettings.getLaunchMode()) { case STANDALONE: case HUMAN: runStandAloneGame(gameSettings); break; case GUI: FrontEnd.main(args); break; case SERVER: startServer(gameSettings); break; case CLIENT: startClient(gameSettings); break; } } /** * Starts microRTS as a server instance. * @param gameSettings The game settings. */ private static void startServer(GameSettings gameSettings) throws Exception { try(ServerSocket serverSocket = new ServerSocket(gameSettings.getServerPort())) { while(true) { try( Socket socket = serverSocket.accept() ) { new RemoteGame(socket, gameSettings).run(); } catch (Exception e ) { e.printStackTrace(); } } } } /** * Starts microRTS as a client instance. * @param gameSettings The game settings. */ private static void startClient(GameSettings gameSettings) throws Exception { Socket socket = new Socket(gameSettings.getServerAddress(), gameSettings.getServerPort()); new RemoteGame(socket, gameSettings).run(); } /** * Starts a standalone game of microRTS with the specified opponents, and game setting * @param gameSettings * @throws Exception */ public static void runStandAloneGame(GameSettings gameSettings) throws Exception { if (gameSettings.getLaunchMode() == GameSettings.LaunchMode.STANDALONE) new Game(gameSettings).start(); else if (gameSettings.getLaunchMode() == GameSettings.LaunchMode.HUMAN) new MouseGame(gameSettings).start(); } }
3,093
31.229167
111
java
MicroRTS
MicroRTS-master/src/rts/MouseGame.java
package rts; import gui.MouseController; import gui.PhysicalGameStateMouseJFrame; import gui.PhysicalGameStatePanel; public class MouseGame extends Game { private PhysicalGameStateMouseJFrame w; MouseGame(GameSettings gameSettings) throws Exception { super(gameSettings); PhysicalGameStatePanel pgsp = new PhysicalGameStatePanel(gs); w = new PhysicalGameStateMouseJFrame("Game State Visualizer (Mouse)", 640, 640, pgsp); this.ai1 = new MouseController(w); } @Override public void start() throws Exception { super.start(w); } }
598
22.96
94
java
MicroRTS
MicroRTS-master/src/rts/PartiallyObservableGameState.java
package rts; import java.util.LinkedList; import java.util.List; import rts.units.Unit; /** * A partially observable game state. It is associated with a player to check whether * it is able to observe the map portion * @author santi */ public class PartiallyObservableGameState extends GameState { /** * */ protected int player; // the observer player /** * Creates a partially observable game state, from the point of view of 'player': * @param gs a fully-observable game state * @param a_player */ public PartiallyObservableGameState(GameState gs, int a_player) { super(gs.getPhysicalGameState().cloneKeepingUnits(), gs.getUnitTypeTable()); unitCancelationCounter = gs.unitCancelationCounter; time = gs.time; player = a_player; unitActions.putAll(gs.unitActions); List<Unit> toDelete = new LinkedList<>(); for (Unit u : pgs.getUnits()) { if (u.getPlayer() != player) { if (!observable(u.getX(), u.getY())) { toDelete.add(u); } } } for (Unit u : toDelete) removeUnit(u); } /** * Returns whether the position is within view of the player * @see rts.GameState#observable(int, int) */ public boolean observable(int x, int y) { for (Unit u : pgs.getUnits()) { if (u.getPlayer() == player) { double d = Math.sqrt((u.getX() - x) * (u.getX() - x) + (u.getY() - y) * (u.getY() - y)); if (d <= u.getType().sightRadius) return true; } } return false; } /* (non-Javadoc) * @see rts.GameState#clone() */ public PartiallyObservableGameState clone() { return new PartiallyObservableGameState(super.clone(), player); } }
1,693
24.283582
92
java
MicroRTS
MicroRTS-master/src/rts/PhysicalGameState.java
package rts; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import util.XMLWriter; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import rts.units.Unit; import rts.units.UnitTypeTable; /** * The physical game state (the actual 'map') of a microRTS game * * @author santi */ public class PhysicalGameState { /** * Indicates a free tile */ public static final int TERRAIN_NONE = 0; /** * Indicates a blocked tile */ public static final int TERRAIN_WALL = 1; int width = 8; int height = 8; int terrain[]; List<Player> players = new ArrayList<>(); List<Unit> units = new LinkedList<>(); /** * Constructs the game state map from a XML * * @param fileName * @param utt * @return * @throws JDOMException * @throws IOException */ public static PhysicalGameState load(String fileName, UnitTypeTable utt) throws Exception { try { return PhysicalGameState.fromXML(new SAXBuilder().build(fileName).getRootElement(), utt); } catch (IllegalArgumentException | FileNotFoundException e) { // Attempt to load the resource as a resource stream. try (InputStream is = PhysicalGameState.class.getClassLoader().getResourceAsStream(fileName)) { return fromXML((new SAXBuilder()).build(is).getRootElement(), utt); } catch (IllegalArgumentException var3) { throw new IllegalArgumentException("Error loading map: " + fileName, var3); } } } /** * Creates a new game state map with the informed width and height. * Initializes an empty terrain. * * @param a_width * @param a_height */ public PhysicalGameState(int a_width, int a_height) { width = a_width; height = a_height; terrain = new int[width * height]; } /** * Creates a new game state map with the informed width and height. * Initializes with the received terrain. * * @param a_width * @param a_height * @param t */ PhysicalGameState(int a_width, int a_height, int t[]) { width = a_width; height = a_height; terrain = t; } /** * @return */ public int getWidth() { return width; } /** * @return */ public int getHeight() { return height; } /** * Sets a new width. This do not change the terrain array, remember to * change that when you change the map width or height * * @param w */ public void setWidth(int w) { width = w; } /** * Sets a new height. This do not change the terrain array, remember to * change that when you change the map width or height * * @param h */ public void setHeight(int h) { height = h; } /** * Returns what is on a given position of the terrain * * @param x * @param y * @return */ public int getTerrain(int x, int y) { return terrain[x + y * width]; } /** * Puts an entity in a given position of the terrain * * @param x * @param y * @param v */ public void setTerrain(int x, int y, int v) { terrain[x + y * width] = v; } /** * Sets the whole terrain * * @param t */ public void setTerrain(int t[]) { terrain = t; } /** * Adds a player * * @param p */ public void addPlayer(Player p) { if (p.getID() != players.size()) { throw new IllegalArgumentException("PhysicalGameState.addPlayer: player added in the wrong order."); } players.add(p); } /** * Adds a new {@link Unit} to the map if its position is free * * @param newUnit * @throws IllegalArgumentException if the new unit's position is already * occupied */ public void addUnit(Unit newUnit) throws IllegalArgumentException { for (Unit existingUnit : units) { if (newUnit.getX() == existingUnit.getX() && newUnit.getY() == existingUnit.getY()) { throw new IllegalArgumentException( "PhysicalGameState.addUnit: added two units in position: (" + newUnit.getX() + ", " + newUnit.getY() + ")"); } } units.add(newUnit); } /** * Removes a unit from the map * * @param u */ public void removeUnit(Unit u) { units.remove(u); } /** * Returns the list of units in the map * * @return */ public List<Unit> getUnits() { return units; } /** * Returns a list of players * * @return */ public List<Player> getPlayers() { return players; } /** * Returns a player given its ID * * @param pID * @return */ public Player getPlayer(int pID) { return players.get(pID); } /** * Returns a {@link Unit} given its ID or null if not found * * @param ID * @return */ public Unit getUnit(long ID) { for (Unit u : units) { if (u.getID() == ID) { return u; } } return null; } /** * Returns the {@link Unit} at a given coordinate or null if no unit is * present * * @param x * @param y * @return */ public Unit getUnitAt(int x, int y) { for (Unit u : units) { if (u.getX() == x && u.getY() == y) { return u; } } return null; } /** * Returns the units within a squared area centered in the given coordinates * * @param x center coordinate of the square * @param y center coordinate of the square * @param squareRange square size * @return */ public Collection<Unit> getUnitsAround(int x, int y, int squareRange) { // returns the units around a rectangle with same width and height return getUnitsAround(x, y, squareRange, squareRange); } /** * Returns units within a rectangular area centered in the given coordinates * @param x center coordinate of the rectangle * @param y center coordinate of the square * @param width rectangle width * @param height rectangle height * @return */ public Collection<Unit> getUnitsAround(int x, int y, int width, int height) { List<Unit> closeUnits = new LinkedList<>(); for (Unit u : units) { if ((Math.abs(u.getX() - x) <= width && Math.abs(u.getY() - y) <= height)) { closeUnits.add(u); } } return closeUnits; } /** * Returns units within a rectangle with the given top-left vertex and dimensions * Tests for x <= unitX < x+width && y <= unitY < y+height * Notice that the test is inclusive in top and left but exclusive on bottom and right * @param x top left coordinate of the rectangle * @param y top left coordinate of the rectangle * @param width rectangle width * @param height rectangle height * @return */ public Collection<Unit> getUnitsInRectangle(int x, int y, int width, int height) { if(width < 1 || height < 1) throw new IllegalArgumentException("Width and height must be >=1"); List<Unit> unitsInside = new LinkedList<Unit>(); for (Unit u : units) { //tests for x <= unitX < x+width && y <= unitY < y+height if(x <= u.getX() && u.getX() < x + width && y <= u.getY() && u.getY() < y+height) { unitsInside.add(u); } } return unitsInside; } /** * Returns the winner of the game, given the unit counts or -1 if the game * is not over TODO: verify where unit counts are being compared! * * @return */ public int winner() { int unitcounts[] = new int[players.size()]; for (Unit u : units) { if (u.getPlayer() >= 0) { unitcounts[u.getPlayer()]++; } } int winner = -1; for (int i = 0; i < unitcounts.length; i++) { if (unitcounts[i] > 0) { if (winner == -1) { winner = i; } else { return -1; } } } return winner; } /** * Returns whether the game is over. The game is over when a player has zero * units * * @return */ boolean gameover() { int unitcounts[] = new int[players.size()]; int totalunits = 0; for (Unit u : units) { if (u.getPlayer() >= 0) { unitcounts[u.getPlayer()]++; totalunits++; } } if (totalunits == 0) { return true; } int winner = -1; for (int i = 0; i < unitcounts.length; i++) { if (unitcounts[i] > 0) { if (winner == -1) { winner = i; } else { return false; } } } return winner != -1; } /* (non-Javadoc) * @see java.lang.Object#clone() */ public PhysicalGameState clone() { PhysicalGameState pgs = new PhysicalGameState(width, height, terrain); // The terrain is shared amongst all instances, since it never changes for (Player p : players) { pgs.players.add(p.clone()); } for (Unit u : units) { pgs.units.add(u.clone()); } return pgs; } /** * Clone the physical game state, but does not clone the units The terrain * is shared amongst all instances, since it never changes * * @return */ public PhysicalGameState cloneKeepingUnits() { PhysicalGameState pgs = new PhysicalGameState(width, height, terrain); // The terrain is shared amongst all instances, since it never changes pgs.players.addAll(players); pgs.units.addAll(units); return pgs; } /** * Clones the physical game state, including its terrain * * @return */ public PhysicalGameState cloneIncludingTerrain() { int new_terrain[] = new int[terrain.length]; System.arraycopy(terrain, 0, new_terrain, 0, terrain.length); PhysicalGameState pgs = new PhysicalGameState(width, height, new_terrain); for (Player p : players) { pgs.players.add(p.clone()); } for (Unit u : units) { pgs.units.add(u.clone()); } return pgs; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuilder tmp = new StringBuilder("PhysicalGameState:\n"); for (Player p : players) { tmp.append(" ").append(p).append("\n"); } for (Unit u : units) { tmp.append(" ").append(u).append("\n"); } return tmp.toString(); } /** * This function tests if two PhysicalGameStates are identical (I didn't * name this method "equals" since I don't want Java to use it) * * @param pgs * @return */ public boolean equivalents(PhysicalGameState pgs) { if (width != pgs.width) { return false; } if (height != pgs.height) { return false; } if (players.size() != pgs.players.size()) { return false; } for (int i = 0; i < players.size(); i++) { if (players.get(i).ID != pgs.players.get(i).ID) { return false; } if (players.get(i).resources != pgs.players.get(i).resources) { return false; } } if (units.size() != pgs.units.size()) { return false; } for (int i = 0; i < units.size(); i++) { if (units.get(i).getType() != pgs.units.get(i).getType()) { return false; } if (units.get(i).getHitPoints() != pgs.units.get(i).getHitPoints()) { return false; } if (units.get(i).getX() != pgs.units.get(i).getX()) { return false; } if (units.get(i).getY() != pgs.units.get(i).getY()) { return false; } } return true; } /** * This function tests if two PhysicalGameStates are identical, including their terrain * * * @param pgs * @return */ public boolean equivalentsIncludingTerrain(PhysicalGameState pgs) { if (this.equivalents(pgs)) { return Arrays.toString(this.terrain).equals(Arrays.toString(pgs.terrain)); } else return false; } /** * Returns an array with true if the given position has * {@link PhysicalGameState.TERRAIN_NONE} * * @return */ public boolean[][] getAllFree() { boolean free[][] = new boolean[getWidth()][getHeight()]; for (int x = 0; x < getWidth(); x++) { for (int y = 0; y < getHeight(); y++) { free[x][y] = (getTerrain(x, y) == PhysicalGameState.TERRAIN_NONE); } } for (Unit u : units) { free[u.getX()][u.getY()] = false; } return free; } /** * Create a compressed String representation of the terrain vector. * <p> * The terrain vector is an array of Integers, whose elements only assume 0 and 1 as * possible values. This method compresses the terrain vector by counting the number of * consecutive occurrences of a value and appending this to a String. * Since 0 and 1 may appear in the counter, 0 is replaced by A and 1 is replaced by B. * </p> * <p> * For example, the String <code>00000011110000000000</code> is transformed into * <code>A6B4A10</code>. * </p> * <p> * This method is useful when the terrain composes part of a message, to be shared between * client and server. * </p> * * @return compressed String representation of the terrain vector */ private String compressTerrain() { StringBuilder strTerrain = new StringBuilder(); int occurrences = 1; for (int i = 1; i < height * width; i++) { if (terrain[i] == terrain[i - 1]) { occurrences++; } else { strTerrain.append(terrain[i - 1] == 0 ? 'A' : 'B'); if (occurrences > 1) { strTerrain.append(occurrences); } occurrences = 1; } } if (occurrences > 1) { strTerrain.append(terrain[terrain.length - 1] == 0 ? 'A' : 'B').append(occurrences); } return strTerrain.toString(); } /** * Create an uncompressed int array from a compressed String representation of * the terrain. * @param t a compressed String representation of the terrain * @return int array representation of the terrain */ private static int[] uncompressTerrain(String t) { ArrayList<Integer> terrain = new ArrayList<>(); StringBuilder counter = new StringBuilder(); for (char ch : t.toCharArray()) { if (ch == 'A' || ch == 'B') { if (counter.length() > 0) { for (int i = 0; i < Integer.parseInt(counter.toString()) - 1; i++) { terrain.add(terrain.get(terrain.size() - 1)); } counter = new StringBuilder(); } terrain.add(ch == 'A' ? 0 : 1); } else { counter.append(ch); } } if (counter.length() > 0) { for (int i = 0; i < Integer.parseInt(counter.toString()) - 1; i++) { terrain.add(terrain.get(terrain.size() - 1)); } } int[] rt = new int[terrain.size()]; for (int i = 0; i < terrain.size(); i++) { rt[i] = terrain.get(i); } return rt; } /** * Writes a XML representation of the map * * @param w */ public void toxml(XMLWriter w) { toxml(w, true, false); } public void toxml(XMLWriter w, boolean includeConstants, boolean compressTerrain) { if (!includeConstants) { w.tag(this.getClass().getName()); } else { w.tagWithAttributes(this.getClass().getName(), "width=\"" + width + "\" height=\"" + height + "\""); if (compressTerrain) { w.tag("terrain", compressTerrain()); } else { StringBuilder tmp = new StringBuilder(height * width); for (int i = 0; i < height * width; i++) { tmp.append(terrain[i]); } w.tag("terrain", tmp.toString()); } } w.tag("players"); for (Player p : players) { p.toxml(w); } w.tag("/players"); w.tag("units"); for (Unit u : units) { u.toxml(w); } w.tag("/units"); w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation of this map * * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { toJSON(w, true, false); } public void toJSON(Writer w, boolean includeConstants, boolean compressTerrain) throws Exception { w.write("{"); if (includeConstants) { w.write("\"width\":" + width + ",\"height\":" + height+","); if (compressTerrain) { w.write("\"terrain\":\"" + compressTerrain()); } else { w.write("\"terrain\":\""); for (int i = 0; i < height * width; i++) { w.write("" + terrain[i]); } } w.write("\","); } w.write("\"players\":["); for (int i = 0; i < players.size(); i++) { players.get(i).toJSON(w); if (i < players.size() - 1) { w.write(","); } } w.write("],"); w.write("\"units\":["); for (int i = 0; i < units.size(); i++) { units.get(i).toJSON(w); if (i < units.size() - 1) { w.write(","); } } w.write("]"); w.write("}"); } /** * Constructs a map from XML * * @param e * @param utt * @return */ public static PhysicalGameState fromXML(Element e, UnitTypeTable utt) throws Exception { Element terrain_e = e.getChild("terrain"); Element players_e = e.getChild("players"); Element units_e = e.getChild("units"); int width = Integer.parseInt(e.getAttributeValue("width")); int height = Integer.parseInt(e.getAttributeValue("height")); int[] terrain = getTerrainFromUnknownString(terrain_e.getValue(), width * height); PhysicalGameState pgs = new PhysicalGameState(width, height, terrain); for (Object o : players_e.getChildren()) { Element player_e = (Element) o; pgs.addPlayer(Player.fromXML(player_e)); } for (Object o : units_e.getChildren()) { Element unit_e = (Element) o; Unit u = Unit.fromXML(unit_e, utt); // check for repeated IDs: if (pgs.getUnit(u.getID()) != null) { throw new Exception("Repeated unit ID " + u.getID() + " in map!"); } pgs.addUnit(u); } return pgs; } /** * Constructs a map from JSON * * @param o * @param utt * @return */ public static PhysicalGameState fromJSON(JsonObject o, UnitTypeTable utt) { String terrainString = o.getString("terrain", null); JsonArray players_o = o.get("players").asArray(); JsonArray units_o = o.get("units").asArray(); int width = o.getInt("width", 8); int height = o.getInt("height", 8); int[] terrain = getTerrainFromUnknownString(terrainString, width * height); PhysicalGameState pgs = new PhysicalGameState(width, height, terrain); for (JsonValue v : players_o.values()) { JsonObject player_o = (JsonObject) v; pgs.addPlayer(Player.fromJSON(player_o)); } for (JsonValue v : units_o.values()) { JsonObject unit_o = (JsonObject) v; pgs.addUnit(Unit.fromJSON(unit_o, utt)); } return pgs; } /** * Transforms a compressed or uncompressed String representation of the terrain into an integer * array * @param terrainString the compressed or uncompressed String representation of the terrain * @param size size of the resulting integer array * @return the terrain, in its integer representation */ private static int[] getTerrainFromUnknownString(String terrainString, int size) { int[] terrain = new int[size]; if (terrainString.contains("A") || terrainString.contains("B")) { terrain = uncompressTerrain(terrainString); } else { for (int i = 0; i < size; i++) { String c = terrainString.substring(i, i + 1); terrain[i] = Integer.parseInt(c); } } return terrain; } /** * Reset all units HP to their base value */ public void resetAllUnitsHP() { for (Unit u : units) { u.setHitPoints(u.getType().hp); } } }
22,341
27.902975
150
java
MicroRTS
MicroRTS-master/src/rts/Player.java
package rts; import com.eclipsesource.json.JsonObject; import java.io.Writer; import org.jdom.Element; import util.XMLWriter; /** * A microRTS player, an entity who owns units * @author santi */ public class Player { /** * An integer that identifies the player */ int ID = 0; /** * The amount of resources owned by the player */ int resources = 0; /** * Creates a Player instance with the given ID and resources * @param a_ID * @param a_resources */ public Player(int a_ID, int a_resources) { ID = a_ID; resources = a_resources; } /** * Returns the player ID * @return */ public int getID() { return ID; } /** * Returns the amount of resources owned by the player * @return */ public int getResources() { return resources; } /** * Sets the amount of resources owned by the player * @param a_resources */ public void setResources(int a_resources) { resources = a_resources; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "player " + ID + "(" + resources + ")"; } /* (non-Javadoc) * @see java.lang.Object#clone() */ public Player clone() { return new Player(ID,resources); } /** * Writes a XML representation of the player * @param w */ public void toxml(XMLWriter w) { w.tagWithAttributes(this.getClass().getName(), "ID=\"" + ID + "\" resources=\"" + resources + "\""); w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation of the player * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { w.write("{\"ID\":"+ID+", \"resources\":"+resources+"}"); } /** * Constructs a player from a XML player element * @param e * @return */ public static Player fromXML(Element e) { Player p = new Player(Integer.parseInt(e.getAttributeValue("ID")), Integer.parseInt(e.getAttributeValue("resources"))); return p; } /** * Constructs a Player from a JSON object * @param o * @return */ public static Player fromJSON(JsonObject o) { Player p = new Player(o.getInt("ID",-1), o.getInt("resources",0)); return p; } }
2,539
21.477876
108
java
MicroRTS
MicroRTS-master/src/rts/PlayerAction.java
package rts; import java.io.Writer; import java.util.LinkedList; import java.util.List; import org.jdom.Element; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * Stores a collection of pairs({@link Unit}, {@link UnitAction}) * @author santi */ public class PlayerAction { /** * A list of unit actions */ List<Pair<Unit,UnitAction>> actions = new LinkedList<>(); /** * Represents the resources used by the player action * TODO rename the field */ ResourceUsage r = new ResourceUsage(); /** * */ public PlayerAction() { } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (!(o instanceof PlayerAction)) return false; PlayerAction a = (PlayerAction)o; for(Pair<Unit,UnitAction> p:actions) { for(Pair<Unit,UnitAction> p2:a.actions) { if (p.m_a.getID()==p2.m_a.getID() && !p.m_b.equals(p2.m_b)) return false; } } return true; } /** * Returns whether there are no player actions * @return */ public boolean isEmpty() { return actions.isEmpty(); } /** * Returns whether the player has assigned any action different * than {@link UnitAction#TYPE_NONE} to any of its units * @return */ public boolean hasNonNoneActions() { for (Pair<Unit, UnitAction> ua : actions) { if (ua.m_b.type != UnitAction.TYPE_NONE) return true; } return false; } /** * Returns the number of actions different than * {@link UnitAction#TYPE_NONE} * @return */ public int hasNamNoneActions() { int j = 0; for (Pair<Unit, UnitAction> ua : actions) { if (ua.m_b.type != UnitAction.TYPE_NONE) j++; } return j; } /** * Returns the usage of resources * @return */ public ResourceUsage getResourceUsage() { return r; } /** * Sets the resource usage * @param a_r */ public void setResourceUsage(ResourceUsage a_r) { r = a_r; } /** * Adds a new {@link UnitAction} to a given {@link Unit} * @param u * @param a */ public void addUnitAction(Unit u, UnitAction a) { actions.add(new Pair<>(u, a)); } /** * Removes a pair of Unit and UnitAction from the list * @param u * @param a */ public void removeUnitAction(Unit u, UnitAction a) { Pair<Unit, UnitAction> found = null; for (Pair<Unit, UnitAction> tmp : actions) { if (tmp.m_a == u && tmp.m_b == a) { found = tmp; break; } } if (found != null) actions.remove(found); } /** * Merges this with another PlayerAction * @param a * @return */ public PlayerAction merge(PlayerAction a) { PlayerAction merge = new PlayerAction(); merge.actions.addAll(actions); merge.actions.addAll(a.actions); merge.r = r.mergeIntoNew(a.r); return merge; } /** * Returns a list of pairs of units and UnitActions * @return */ public List<Pair<Unit,UnitAction>> getActions() { return actions; } /** * Searches for the unit in the collection and returns the respective {@link UnitAction} * @param u * @return */ public UnitAction getAction(Unit u) { for (Pair<Unit, UnitAction> tmp : actions) { if (tmp.m_a == u) return tmp.m_b; } return null; } /** * @param lu * @param u * @param s * @return */ public List<PlayerAction> cartesianProduct(List<UnitAction> lu, Unit u, GameState s) { List<PlayerAction> l = new LinkedList<>(); for (UnitAction ua : lu) { ResourceUsage r2 = ua.resourceUsage(u, s.getPhysicalGameState()); if (r.consistentWith(r2, s)) { PlayerAction a = new PlayerAction(); a.r = r.mergeIntoNew(r2); a.actions.addAll(actions); a.addUnitAction(u, ua); l.add(a); } } return l; } /** * Returns whether this PlayerAction is consistent with a * given {@link ResourceUsage} and a {@link GameState} * @param u * @param gs * @return */ public boolean consistentWith(ResourceUsage u, GameState gs) { return r.consistentWith(u, gs); } /** * Assign "none" to all the units that need an action and do not have one * for the specified duration * @param s * @param pID the player ID * @param duration the number of frames the 'none' action should last */ public void fillWithNones(GameState s, int pID, int duration) { PhysicalGameState pgs = s.getPhysicalGameState(); for (Unit u : pgs.getUnits()) { if (u.getPlayer() == pID) { if (s.unitActions.get(u) == null) { boolean found = false; for (Pair<Unit, UnitAction> pa : actions) { if (pa.m_a == u) { found = true; break; } } if (!found) { actions.add(new Pair<>(u, new UnitAction(UnitAction.TYPE_NONE, duration))); } } } } } /** * Returns true if this object passes the integrity check. * It fails if the unit is being assigned an action from a player * that does not owns it * @return */ public boolean integrityCheck() { int player = -1; // List<Unit> alreadyUsed = new LinkedList<Unit>(); for (Pair<Unit, UnitAction> uaa : actions) { Unit u = uaa.m_a; if (player == -1) { player = u.getPlayer(); } else { if (player != u.getPlayer()) { System.err.println("integrityCheck: units from more than one player!"); return false; } } } return true; } /* (non-Javadoc) * @see java.lang.Object#clone() */ public PlayerAction clone() { PlayerAction clone = new PlayerAction(); clone.actions = new LinkedList<>(); for(Pair<Unit,UnitAction> tmp:actions) { clone.actions.add(new Pair<>(tmp.m_a, tmp.m_b)); } clone.r = r.clone(); return clone; } /** * Resets the PlayerAction */ public void clear() { actions.clear(); r = new ResourceUsage(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuilder tmp = new StringBuilder("{ "); for(Pair<Unit,UnitAction> ua:actions) { tmp.append("(").append(ua.m_a).append(",").append(ua.m_b).append(")"); } return tmp + " }"; } /** * Writes to XML * @param w */ public void toxml(XMLWriter w) { w.tag("PlayerAction"); for(Pair<Unit,UnitAction> ua:actions) { w.tagWithAttributes("action", "unitID=\"" + ua.m_a.getID() + "\""); ua.m_b.toxml(w); w.tag("/action"); } w.tag("/PlayerAction"); } /** * Writes to JSON * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { boolean first = true; w.write("["); for(Pair<Unit,UnitAction> ua:actions) { if (!first) w.write(" ,"); w.write("{\"unitID\":" + ua.m_a.getID() + ", \"unitAction\":"); ua.m_b.toJSON(w); w.write("}"); first = false; } w.write("]"); } /** * Creates a PlayerAction from a XML element * @param e * @param gs * @param utt * @return */ public static PlayerAction fromXML(Element e, GameState gs, UnitTypeTable utt) { PlayerAction pa = new PlayerAction(); List<?> l = e.getChildren("action"); for(Object o:l) { Element action_e = (Element)o; int id = Integer.parseInt(action_e.getAttributeValue("unitID")); Unit u = gs.getUnit(id); UnitAction ua = UnitAction.fromXML(action_e.getChild("UnitAction"), utt); pa.addUnitAction(u, ua); } return pa; } /** * Creates a PlayerAction from a JSON object * @param JSON * @param gs * @param utt * @return */ public static PlayerAction fromJSON(String JSON, GameState gs, UnitTypeTable utt) { PlayerAction pa = new PlayerAction(); JsonArray a = Json.parse(JSON).asArray(); for(JsonValue v:a.values()) { JsonObject o = v.asObject(); int id = o.getInt("unitID", -1); Unit u = gs.getUnit(id); UnitAction ua = UnitAction.fromJSON(o.get("unitAction").asObject(), utt); pa.addUnitAction(u, ua); } return pa; } /** * Creates a full assignment of actions to inactive units for a given player * from a vector-based action representation. * * @param actions Vector representation of actions. Outer dimension is for * the list of actions/units, i.e. actions[i] gives us the vector * representation for the i^th unit that we are assigning an action to. * @param gs * @param utt * @param currentPlayer Player whom we are processing actions for * @param maxAttackRadius This should be 2*a + 1, where a is the maximum * attack range over all units. * @return The constructed PlayerAction object */ public static PlayerAction fromVectorAction(int[][] actions, GameState gs, UnitTypeTable utt, int currentPlayer, int maxAttackRadius) { PlayerAction pa = new PlayerAction(); // calculating the resource usage of existing actions ResourceUsage base_ru = new ResourceUsage(); for (Unit u : gs.getPhysicalGameState().getUnits()) { UnitActionAssignment uaa = gs.unitActions.get(u); if (uaa != null) { ResourceUsage ru = uaa.action.resourceUsage(u, gs.getPhysicalGameState()); base_ru.merge(ru); } } // FIXME is the clone() really necessary here? base_ru was just newly constructed, // and will not be used outside of this, so I think we can just pass it directly? pa.setResourceUsage(base_ru.clone()); for(int[] action:actions) { Unit u = gs.pgs.getUnitAt(action[0] % gs.pgs.width, action[0] / gs.pgs.width); // execute the action if the following happens // 1. The selected unit is *not* null. // 2. The unit selected is owned by the current player // 3. The unit is not currently busy (its unit action is null) if (u != null && u.getPlayer() == currentPlayer && gs.unitActions.get(u) == null) { UnitAction ua = UnitAction.fromVectorAction(action, utt, gs, u, maxAttackRadius); if (ua.resourceUsage(u, gs.pgs).consistentWith(pa.getResourceUsage(), gs)) { ResourceUsage ru = ua.resourceUsage(u, gs.pgs); pa.getResourceUsage().merge(ru); pa.addUnitAction(u, ua); } } } return pa; } }
11,518
26.42619
139
java
MicroRTS
MicroRTS-master/src/rts/PlayerActionGenerator.java
package rts; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import rts.units.Unit; import util.Pair; /** * Enumerates the PlayerActions for a given game state * @author santi */ public class PlayerActionGenerator { static Random r = new Random(); GameState gameState; PhysicalGameState physicalGameState; ResourceUsage base_ru; List<Pair<Unit,List<UnitAction>>> choices; PlayerAction lastAction; long size = 1; // this will be capped at Long.MAX_VALUE; long generated = 0; int choiceSizes[]; int currentChoice[]; boolean moreActions = true; /** * * @return */ public long getGenerated() { return generated; } public long getSize() { return size; } public PlayerAction getLastAction() { return lastAction; } public List<Pair<Unit,List<UnitAction>>> getChoices() { return choices; } /** * Generating all possible actions for a player in a given state * @param a_gs * @param pID * @param noneDuration * @throws Exception */ public PlayerActionGenerator(GameState a_gs, int pID, int noneDuration) throws Exception { // Generate the reserved resources: base_ru = new ResourceUsage(); gameState = a_gs; physicalGameState = gameState.getPhysicalGameState(); for (Unit u : physicalGameState.getUnits()) { UnitActionAssignment uaa = gameState.unitActions.get(u); if (uaa != null) { ResourceUsage ru = uaa.action.resourceUsage(u, physicalGameState); base_ru.merge(ru); } } choices = new ArrayList<>(); for (Unit u : physicalGameState.getUnits()) { if (u.getPlayer() == pID) { if (gameState.unitActions.get(u) == null) { List<UnitAction> l = u.getUnitActions(gameState, noneDuration); choices.add(new Pair<>(u, l)); // make sure we don't overflow: long tmp = l.size(); if (Long.MAX_VALUE / size <= tmp) { size = Long.MAX_VALUE; } else { size *= (long) l.size(); } // System.out.println("size = " + size); } } } // System.out.println("---"); if (choices.size() == 0) { System.err.println("Problematic game state:"); System.err.println(a_gs); throw new Exception( "Move generator for player " + pID + " created with no units that can execute actions! (status: " + a_gs.canExecuteAnyAction(0) + ", " + a_gs.canExecuteAnyAction(1) + ")" ); } choiceSizes = new int[choices.size()]; currentChoice = new int[choices.size()]; int i = 0; for(Pair<Unit,List<UnitAction>> choice:choices) { choiceSizes[i] = choice.m_b.size(); currentChoice[i] = 0; i++; } } public PlayerActionGenerator(GameState a_gs, int pID) throws Exception { this(a_gs, pID, 10); } /** * Shuffles the list of choices */ public void randomizeOrder() { for (Pair<Unit, List<UnitAction>> choice : choices) { List<UnitAction> tmp = new LinkedList<>(choice.m_b); choice.m_b.clear(); while (!tmp.isEmpty()) choice.m_b.add(tmp.remove(r.nextInt(tmp.size()))); } } /** * Increases the index that tracks the next action to be returned * by {@link #getNextAction(long)} * @param startPosition */ public void incrementCurrentChoice(int startPosition) { for (int i = 0; i < startPosition; i++) currentChoice[i] = 0; currentChoice[startPosition]++; if (currentChoice[startPosition] >= choiceSizes[startPosition]) { if (startPosition < currentChoice.length - 1) { incrementCurrentChoice(startPosition + 1); } else { moreActions = false; } } } /** * Returns the next PlayerAction for the state stored in this object * @param cutOffTime time to stop generationg the action * @return * @throws Exception */ public PlayerAction getNextAction(long cutOffTime) throws Exception { int count = 0; while(moreActions) { boolean consistent = true; PlayerAction pa = new PlayerAction(); pa.setResourceUsage(base_ru.clone()); int i = choices.size(); if (i == 0) throw new Exception("Move generator created with no units that can execute actions!"); while (i > 0) { i--; Pair<Unit, List<UnitAction>> unitChoices = choices.get(i); int choice = currentChoice[i]; Unit u = unitChoices.m_a; UnitAction ua = unitChoices.m_b.get(choice); ResourceUsage r2 = ua.resourceUsage(u, physicalGameState); if (pa.getResourceUsage().consistentWith(r2, gameState)) { pa.getResourceUsage().merge(r2); pa.addUnitAction(u, ua); } else { consistent = false; break; } } incrementCurrentChoice(i); if (consistent) { lastAction = pa; generated++; return pa; } // check if we are over time (only check once every 1000 actions, since currenttimeMillis is a slow call): if (cutOffTime > 0 && (count % 1000 == 0) && System.currentTimeMillis() > cutOffTime) { lastAction = null; return null; } count++; } lastAction = null; return null; } /** * Returns a random player action for the game state in this object * @return */ public PlayerAction getRandom() { Random r = new Random(); PlayerAction pa = new PlayerAction(); pa.setResourceUsage(base_ru.clone()); for (Pair<Unit, List<UnitAction>> unitChoices : choices) { List<UnitAction> l = new LinkedList<>(unitChoices.m_b); Unit u = unitChoices.m_a; boolean consistent = false; do { UnitAction ua = l.remove(r.nextInt(l.size())); ResourceUsage r2 = ua.resourceUsage(u, physicalGameState); if (pa.getResourceUsage().consistentWith(r2, gameState)) { pa.getResourceUsage().merge(r2); pa.addUnitAction(u, ua); consistent = true; } } while (!consistent); } return pa; } /** * Finds the index of a given PlayerAction within the list of PlayerActions * @param a * @return */ public long getActionIndex(PlayerAction a) { int choice[] = new int[choices.size()]; for (Pair<Unit, UnitAction> ua : a.actions) { int idx = 0; Pair<Unit, List<UnitAction>> ua_choice = null; for (Pair<Unit, List<UnitAction>> c : choices) { if (ua.m_a == c.m_a) { ua_choice = c; break; } idx++; } if (ua_choice == null) return -1; choice[idx] = ua_choice.m_b.indexOf(ua.m_b); } long index = 0; long multiplier = 1; for (int i = 0; i < choice.length; i++) { index += choice[i] * multiplier; multiplier *= choiceSizes[i]; } return index; } public String toString() { StringBuilder ret = new StringBuilder("PlayerActionGenerator:\n"); for(Pair<Unit,List<UnitAction>> choice:choices) { ret.append(" (").append(choice.m_a).append(",").append(choice.m_b.size()).append(")\n"); } ret.append("currentChoice: "); for (int value : currentChoice) { ret.append(value).append(" "); } ret.append("\nactions generated so far: ").append(generated); return ret.toString(); } }
7,396
26.396296
118
java
MicroRTS
MicroRTS-master/src/rts/RemoteGame.java
package rts; import ai.core.AI; import ai.socket.SocketAI; import java.lang.reflect.Constructor; import java.net.Socket; import rts.units.UnitTypeTable; class RemoteGame implements Runnable { private Socket socket; private GameSettings gameSettings; RemoteGame(Socket socket, GameSettings gameSettings) { this.socket = socket; this.gameSettings = gameSettings; } /** * Starts the game. */ @Override public void run() { try { UnitTypeTable unitTypeTable = new UnitTypeTable( gameSettings.getUTTVersion(), gameSettings.getConflictPolicy()); // Generate players // player 1 is created from SocketAI AI player_one = SocketAI.createFromExistingSocket(100, 0, unitTypeTable, gameSettings.getSerializationType(), gameSettings.isIncludeConstantsInState(), gameSettings.isCompressTerrain(), socket); // player 2 is created using the info from gameSettings Constructor cons2 = Class.forName(gameSettings.getAI2()) .getConstructor(UnitTypeTable.class); AI player_two = (AI) cons2.newInstance(unitTypeTable); Game game = new Game(gameSettings, player_one, player_two); game.start(); } catch (Exception e) { e.printStackTrace(); } } }
1,395
30.022222
94
java
MicroRTS
MicroRTS-master/src/rts/ResourceUsage.java
package rts; import java.util.LinkedList; import java.util.List; /** * * @author santi */ public class ResourceUsage { List<Integer> positionsUsed = new LinkedList<>(); int[] resourcesUsed = new int[2]; // 2 players is hardcoded here! FIX!!! /** * Empty constructor */ public ResourceUsage() { } /** * Returns whether this instance is consistent with another ResourceUsage in * a given game state. Resource usages are consistent if they respect the * players' resource amount and don't have conflicting uses * * @param anotherUsage * @param gs * @return */ public boolean consistentWith(ResourceUsage anotherUsage, GameState gs) { for (Integer pos : anotherUsage.positionsUsed) { if (positionsUsed.contains(pos)) { return false; } } for (int i = 0; i < resourcesUsed.length; i++) { if (anotherUsage.resourcesUsed[i] == 0) continue; if (resourcesUsed[i] + anotherUsage.resourcesUsed[i] > 0 && // this extra condition (which should not be needed), is because // if an AI has a bug and allows execution of actions that // brings resources below 0, this code would fail. resourcesUsed[i] + anotherUsage.resourcesUsed[i] > gs.getPlayer(i).getResources()) { return false; } } return true; } /** * Returns the list with used resource positions * * @return */ public List<Integer> getPositionsUsed() { return positionsUsed; } /** * Returns the amount of resources used by the player * * @param player * @return */ public int getResourcesUsed(int player) { return resourcesUsed[player]; } /** * Merges this and another instance of ResourceUsage into a new one * * @param other * @return */ public ResourceUsage mergeIntoNew(ResourceUsage other) { ResourceUsage newResourceUsage = new ResourceUsage(); newResourceUsage.positionsUsed.addAll(positionsUsed); newResourceUsage.positionsUsed.addAll(other.positionsUsed); for (int i = 0; i < resourcesUsed.length; i++) { newResourceUsage.resourcesUsed[i] = resourcesUsed[i] + other.resourcesUsed[i]; } return newResourceUsage; } /** * Merges another instance of ResourceUsage into this one * * @param other */ public void merge(ResourceUsage other) { positionsUsed.addAll(other.positionsUsed); for (int i = 0; i < resourcesUsed.length; i++) { resourcesUsed[i] += other.resourcesUsed[i]; } } public ResourceUsage clone() { ResourceUsage ru = new ResourceUsage(); ru.positionsUsed.addAll(positionsUsed); ru.resourcesUsed[0] = resourcesUsed[0]; ru.resourcesUsed[1] = resourcesUsed[1]; return ru; } public String toString() { return "ResourceUsage: " + resourcesUsed[0] + "," + resourcesUsed[1] + " positions: " + positionsUsed; } }
3,191
27.5
110
java
MicroRTS
MicroRTS-master/src/rts/Trace.java
package rts; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.LinkedList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.jdom.Element; import org.jdom.input.SAXBuilder; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * Contains actions executed throughout a match, serving as a 'replay' class * * @author santi */ public class Trace { UnitTypeTable utt; List<TraceEntry> entries = new LinkedList<>(); /** * Constructs from a UnitTypeTable * * @param a_utt */ public Trace(UnitTypeTable a_utt) { utt = a_utt; } /** * Returns the list of entries, where each entry corresponds to actions * executed in a frame * * @return */ public List<TraceEntry> getEntries() { return entries; } public UnitTypeTable getUnitTypeTable() { return utt; } /** * Returns the number of the last frame stored in this trace * * @return */ public int getLength() { return entries.get(entries.size() - 1).getTime(); } /** * Returns the index of the winner player. Or returns -1 if there are no * entries or the game is not over * * @return */ public int winner() { if (entries.isEmpty()) { return -1; } return entries.get(entries.size() - 1).pgs.winner(); } /** * Adds a new entry, which corresponds to a frame * * @param te */ public void addEntry(TraceEntry te) { entries.add(te); } /** * Writes a XML representation * * @param w */ public void toxml(XMLWriter w) { w.tag(this.getClass().getName()); utt.toxml(w); w.tag("entries"); for (TraceEntry te : entries) { te.toxml(w); } w.tag("/entries"); w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation * * @param w */ public void toJSON(Writer w) throws Exception { w.write("{\"utt\":"); utt.toJSON(w); w.write(",\n\"entries\":["); boolean first = true; for (TraceEntry te : entries) { if (!first) w.write(",\n"); te.toJSON(w); first = false; } w.write("]}"); } /** * Dumps this trace to the XML file specified on path * It can be reconstructed later (e.g. with {@link #fromXML(String, UnitTypeTable)} * @param path */ public void toxml(String path) { try { XMLWriter dumper = new XMLWriter(new FileWriter(path)); this.toxml(dumper); dumper.close(); } catch (IOException e) { System.err.println("Error while writing trace to: " + path); e.printStackTrace(); } } public void toZip(String path) { if(path.endsWith(".zip")) { path.replaceFirst("[.][^.]+$", ".xml"); // replaces .zip by .xml } File f = new File(path); ZipOutputStream out; try { out = new ZipOutputStream(new FileOutputStream(f)); ZipEntry e = new ZipEntry(f.getName()); out.putNextEntry(e); StringWriter xmlStringContainer = new StringWriter(); XMLWriter dumper = new XMLWriter(xmlStringContainer); //XMLWriter dumper = new XMLWriter(new FileWriter(path)); this.toxml(dumper); byte[] data = xmlStringContainer.toString().getBytes(); out.write(data, 0, data.length); out.closeEntry(); out.close(); } catch (FileNotFoundException e1) { System.err.println("File not found: " + path); e1.printStackTrace(); } catch (IOException e1) { System.err.println("Error while writing to " + path); e1.printStackTrace(); } } public static Trace fromZip(String path) throws Exception { ZipInputStream zis = new ZipInputStream(new FileInputStream(path)); zis.getNextEntry(); return new Trace(new SAXBuilder().build(zis).getRootElement()); } /** * Constructs the Trace from a XML element * * @param e */ public Trace(Element e) throws Exception { utt = UnitTypeTable.fromXML(e.getChild(UnitTypeTable.class.getName())); Element entries_e = e.getChild("entries"); for (Object o : entries_e.getChildren()) { Element entry_e = (Element) o; entries.add(new TraceEntry(entry_e, utt)); } } /** * Constructs the Trace from a XML element, overriding the UnitTypeTable of * that element with one provided * * @param e * @param a_utt */ public Trace(Element e, UnitTypeTable a_utt) throws Exception { utt = a_utt; Element entries_e = e.getChild("entries"); for (Object o : entries_e.getChildren()) { Element entry_e = (Element) o; entries.add(new TraceEntry(entry_e, utt)); } } /** * this accelerates the function below if traversing a trace sequentially */ GameState getGameStateAtCycle_cache; /** * Simulates the game from the from the last cached cycle (initialized as * null) to get the appropriate unit actions. Thus, this function can be * slow, do not use in the internal loop of any AI! * * @param cycle * @return */ public GameState getGameStateAtCycle(int cycle) { GameState gs = null; for (TraceEntry te : getEntries()) { if (gs == null) { if (getGameStateAtCycle_cache != null && cycle >= getGameStateAtCycle_cache.getTime()) { if (te.getTime() < getGameStateAtCycle_cache.getTime()) { continue; } else { gs = getGameStateAtCycle_cache.clone(); } } else { gs = new GameState(te.getPhysicalGameState().clone(), utt); } } while (gs.getTime() < te.getTime() && gs.getTime() < cycle) { gs.cycle(); } // synchronize the traces (some times the unit IDs might go off): for (Unit u1 : gs.getUnits()) { for (Unit u2 : te.getPhysicalGameState().getUnits()) { if (u1.getX() == u2.getX() && u1.getY() == u2.getY() && u1.getType() == u2.getType() && u1.getID() != u2.getID()) { u1.setID(u2.getID()); } } } if (gs.getTime() == cycle) { getGameStateAtCycle_cache = gs; return gs; } PlayerAction pa0 = new PlayerAction(); PlayerAction pa1 = new PlayerAction(); for (Pair<Unit, UnitAction> tmp : te.getActions()) { if (tmp.m_a != null) { if (tmp.m_a.getPlayer() == 0) { pa0.addUnitAction(tmp.m_a, tmp.m_b); } if (tmp.m_a.getPlayer() == 1) { pa1.addUnitAction(tmp.m_a, tmp.m_b); } } else { System.err.println("TraceEntry at time " + te.getTime() + " has actions for undefined units! This will probably cause errors down the line..."); } } gs.issueSafe(pa0); gs.issueSafe(pa1); if (gs.getTime() == cycle) { getGameStateAtCycle_cache = gs; return gs; } } while (gs.getTime() < cycle) { gs.cycle(); } getGameStateAtCycle_cache = gs; return gs; } }
8,207
27.5
164
java
MicroRTS
MicroRTS-master/src/rts/TraceEntry.java
package rts; import java.io.Writer; import java.util.LinkedList; import java.util.List; import org.jdom.Element; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * Stores the actions executed in a game state, useful to re-trace / re-play the * match * * @author santi */ public class TraceEntry { int time; PhysicalGameState pgs; List<Pair<Unit, UnitAction>> actions = new LinkedList<>(); /** * Creates from a PhysicalGameState and time * * @param a_pgs * @param a_time */ public TraceEntry(PhysicalGameState a_pgs, int a_time) { pgs = a_pgs; time = a_time; } /** * Adds a UnitAction to a Unit * * @param u * @param a */ public void addUnitAction(Unit u, UnitAction a) { actions.add(new Pair<>(u, a)); } /** * Adds all actions of a player * * @param a */ public void addPlayerAction(PlayerAction a) { for (Pair<Unit, UnitAction> ua : a.actions) { if (pgs.getUnit(ua.m_a.getID()) == null) { boolean found = false; for(Unit u:pgs.units) { if (u.getClass()==ua.m_a.getClass() && u.getX()==ua.m_a.getX() && u.getY()==ua.m_a.getY()) { ua.m_a = u; found = true; break; } } if (!found) { System.err.println("Inconsistent order: " + a); System.err.println(this); System.err.println("The problem was with unit " + ua.m_a); } } actions.add(ua); } } /** * Returns the physical game state this object stores * * @return */ public PhysicalGameState getPhysicalGameState() { return pgs; } /** * Returns the list of actions this instance refers to * * @return */ public List<Pair<Unit, UnitAction>> getActions() { return actions; } /** * Returns the time this TraceEntry refers to * * @return */ public int getTime() { return time; } /** * Constructs a XML representation for this object * * @param w */ public void toxml(XMLWriter w) { w.tagWithAttributes(this.getClass().getName(), "time = \"" + time + "\""); pgs.toxml(w); w.tag("actions"); for (Pair<Unit, UnitAction> ua : actions) { w.tagWithAttributes("action", "unitID=\"" + ua.m_a.getID() + "\""); ua.m_b.toxml(w); w.tag("/action"); } w.tag("/actions"); w.tag("/" + this.getClass().getName()); } /** * Constructs a JSON representation for this object * * @param w */ public void toJSON(Writer w) throws Exception { w.write("{"); w.write("\"time\":" + time + ",\"pgs\":"); pgs.toJSON(w); w.write(",\"actions\":["); boolean first = true; for (Pair<Unit, UnitAction> ua : actions) { if (!first) w.write(","); first = false; w.write("{\"unitID\":" + ua.m_a.getID() +", \"action\":"); ua.m_b.toJSON(w); w.write("}"); } w.write("]}"); } /** * Constructs the TraceEntry from a XML element and a UnitTypeTable * * @param e * @param utt */ public TraceEntry(Element e, UnitTypeTable utt) throws Exception { Element actions_e = e.getChild("actions"); time = Integer.parseInt(e.getAttributeValue("time")); Element pgs_e = e.getChild(PhysicalGameState.class.getName()); pgs = PhysicalGameState.fromXML(pgs_e, utt); for (Object o : actions_e.getChildren()) { Element action_e = (Element) o; long ID = Long.parseLong(action_e.getAttributeValue("unitID")); UnitAction a = new UnitAction(action_e.getChild("UnitAction"), utt); Unit u = pgs.getUnit(ID); if (u == null) { System.err.println("Undefined unit ID " + ID + " in action " + a + " at time " + time); } actions.add(new Pair<>(u, a)); } } }
4,400
25.672727
103
java
MicroRTS
MicroRTS-master/src/rts/UnitAction.java
package rts; import java.io.Writer; import java.util.List; import java.util.Objects; import java.util.Random; import org.jdom.Element; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class UnitAction { public static Random r = new Random(); // only used for non-deterministic events /** * The 'no-op' action */ public static final int TYPE_NONE = 0; /** * Action of moving */ public static final int TYPE_MOVE = 1; /** * Action of harvesting */ public static final int TYPE_HARVEST = 2; /** * Action of return to base with resource */ public static final int TYPE_RETURN = 3; /** * Action of produce a unit */ public static final int TYPE_PRODUCE = 4; /** * Action of attacking a location */ public static final int TYPE_ATTACK_LOCATION = 5; /** * Total number of action types */ public static final int NUMBER_OF_ACTION_TYPES = 6; public static String actionName[] = { "wait", "move", "harvest", "return", "produce", "attack_location" }; /** * Direction of 'standing still' */ public static final int DIRECTION_NONE = -1; /** * Alias for up */ public static final int DIRECTION_UP = 0; /** * Alias for right */ public static final int DIRECTION_RIGHT = 1; /** * Alias for down */ public static final int DIRECTION_DOWN = 2; /** * Alias for left */ public static final int DIRECTION_LEFT = 3; /** * The offset caused by each direction of movement in X Indexes correspond * to the constants used in this class */ public static final int DIRECTION_OFFSET_X[] = {0, 1, 0, -1}; /** * The offset caused by each direction of movement in y Indexes correspond * to the constants used in this class */ public static final int DIRECTION_OFFSET_Y[] = {-1, 0, 1, 0}; /** * Direction names. Indexes correspond to the constants used in this class */ public static final String DIRECTION_NAMES[] = {"up", "right", "down", "left"}; /** * Type of this UnitAction */ int type = TYPE_NONE; /** * used for both "direction" and "duration" */ int parameter = DIRECTION_NONE; /** * X and Y coordinates of an attack-location action */ int x = 0, y = 0; /** * UnitType associated with a 'produce' action */ UnitType unitType; /** * Amount of resources associated with this action */ ResourceUsage r_cache; /** * Creates an action with specified type * * @param a_type */ public UnitAction(int a_type) { type = a_type; } /** * Creates an action with type and direction * * @param a_type * @param a_direction */ public UnitAction(int a_type, int a_direction) { type = a_type; parameter = a_direction; } /** * Creates an action with type, direction and unit type * * @param a_type * @param a_direction * @param a_unit_type */ public UnitAction(int a_type, int a_direction, UnitType a_unit_type) { type = a_type; parameter = a_direction; unitType = a_unit_type; } /** * Creates a unit action with coordinates * * @param a_type * @param a_x * @param a_y */ public UnitAction(int a_type, int a_x, int a_y) { type = a_type; x = a_x; y = a_y; } /** * Copies the parameters of other unit action * * @param other */ public UnitAction(UnitAction other) { type = other.type; parameter = other.parameter; x = other.x; y = other.y; unitType = other.unitType; } @Override public boolean equals(Object o) { if (!(o instanceof UnitAction)) { return false; } UnitAction a = (UnitAction) o; if (a.type != type) { return false; } else if (type == TYPE_NONE || type == TYPE_MOVE || type == TYPE_HARVEST || type == TYPE_RETURN) { return a.parameter == parameter; } else if (type == TYPE_ATTACK_LOCATION) { return a.x == x && a.y == y; } else { return a.parameter == parameter && a.unitType == unitType; } } @Override public int hashCode() { int hash = this.type; hash = 19 * hash + this.parameter; hash = 19 * hash + this.x; hash = 19 * hash + this.y; hash = 19 * hash + Objects.hashCode(this.unitType); return hash; } /** * Returns the type associated with this action * * @return */ public int getType() { return type; } /** * Returns the UnitType associated with this action * * @return */ public UnitType getUnitType() { return unitType; } /** * Returns the ResourceUsage associated with this action, given a Unit and a * PhysicalGameState * * @param u * @param pgs * @return */ public ResourceUsage resourceUsage(Unit u, PhysicalGameState pgs) { if (r_cache != null) { return r_cache; } r_cache = new ResourceUsage(); switch (type) { case TYPE_MOVE: { int pos = u.getX() + u.getY() * pgs.getWidth(); switch (parameter) { case DIRECTION_UP: pos -= pgs.getWidth(); break; case DIRECTION_RIGHT: pos++; break; case DIRECTION_DOWN: pos += pgs.getWidth(); break; case DIRECTION_LEFT: pos--; break; } r_cache.positionsUsed.add(pos); } break; case TYPE_PRODUCE: { r_cache.resourcesUsed[u.getPlayer()] += unitType.cost; int pos = u.getX() + u.getY() * pgs.getWidth(); switch (parameter) { case DIRECTION_UP: pos -= pgs.getWidth(); break; case DIRECTION_RIGHT: pos++; break; case DIRECTION_DOWN: pos += pgs.getWidth(); break; case DIRECTION_LEFT: pos--; break; } r_cache.positionsUsed.add(pos); } break; } return r_cache; } /** * Returns the estimated time of conclusion of this action The Unit * parameter is necessary for actions of {@link #TYPE_MOVE}, * {@link #TYPE_ATTACK_LOCATION} and {@link #TYPE_RETURN}. In other cases it * can be null * * @param u * @return */ public int ETA(Unit u) { switch (type) { case TYPE_NONE: return parameter; case TYPE_MOVE: return u.getMoveTime(); case TYPE_ATTACK_LOCATION: return u.getAttackTime(); case TYPE_HARVEST: return u.getHarvestTime(); case TYPE_RETURN: return u.getMoveTime(); case TYPE_PRODUCE: return unitType.produceTime; } return 0; } /** * Effects this action in the game state. If the action is related to a * unit, changes it position accordingly * * @param u * @param s */ public void execute(Unit u, GameState s) { PhysicalGameState pgs = s.getPhysicalGameState(); switch (type) { case TYPE_NONE: //no-op break; case TYPE_MOVE: //moves the unit in the intended direction switch (parameter) { case DIRECTION_UP: u.setY(u.getY() - 1); break; case DIRECTION_RIGHT: u.setX(u.getX() + 1); break; case DIRECTION_DOWN: u.setY(u.getY() + 1); break; case DIRECTION_LEFT: u.setX(u.getX() - 1); break; } break; case TYPE_ATTACK_LOCATION: //if there's a unit in the target location, damages it { Unit other = pgs.getUnitAt(x, y); if (other != null) { int damage; if (u.getMinDamage() == u.getMaxDamage()) { damage = u.getMinDamage(); } else { damage = u.getMinDamage() + r.nextInt(1 + (u.getMaxDamage() - u.getMinDamage())); } other.setHitPoints(other.getHitPoints() - damage); if (other.getHitPoints() <= 0) { s.removeUnit(other); } } } break; case TYPE_HARVEST: //attempts to harvest from a resource in the target direction { Unit maybeAResource = null; switch (parameter) { case DIRECTION_UP: maybeAResource = pgs.getUnitAt(u.getX(), u.getY() - 1); break; case DIRECTION_RIGHT: maybeAResource = pgs.getUnitAt(u.getX() + 1, u.getY()); break; case DIRECTION_DOWN: maybeAResource = pgs.getUnitAt(u.getX(), u.getY() + 1); break; case DIRECTION_LEFT: maybeAResource = pgs.getUnitAt(u.getX() - 1, u.getY()); break; } if (maybeAResource != null && maybeAResource.getType().isResource && u.getType().canHarvest && u.getResources() == 0) { //indeed it is a resource, harvest from it maybeAResource.setResources(maybeAResource.getResources() - u.getHarvestAmount()); if (maybeAResource.getResources() <= 0) { s.removeUnit(maybeAResource); } u.setResources(u.getHarvestAmount()); } } break; case TYPE_RETURN: //returns to base with a resource { Unit base = null; switch (parameter) { case DIRECTION_UP: base = pgs.getUnitAt(u.getX(), u.getY() - 1); break; case DIRECTION_RIGHT: base = pgs.getUnitAt(u.getX() + 1, u.getY()); break; case DIRECTION_DOWN: base = pgs.getUnitAt(u.getX(), u.getY() + 1); break; case DIRECTION_LEFT: base = pgs.getUnitAt(u.getX() - 1, u.getY()); break; } if (base != null && base.getType().isStockpile && u.getResources() > 0) { Player p = pgs.getPlayer(u.getPlayer()); p.setResources(p.getResources() + u.getResources()); u.setResources(0); } else {// base is not there } } break; case TYPE_PRODUCE: //produces a unit in the target direction { int targetx = u.getX(); int targety = u.getY(); switch (parameter) { case DIRECTION_UP: targety--; break; case DIRECTION_RIGHT: targetx++; break; case DIRECTION_DOWN: targety++; break; case DIRECTION_LEFT: targetx--; break; } Unit newUnit = new Unit(u.getPlayer(), unitType, targetx, targety, 0); Player p = pgs.getPlayer(u.getPlayer()); if((p.getResources() - newUnit.getCost())>=0){ pgs.addUnit(newUnit); p.setResources(p.getResources() - newUnit.getCost()); } else { System.err.print("Illegal action attempted ("+this+")! "+ "Resources of player " + p.ID + " would have been negative!\n"); System.err.print(s); } } break; } } @Override public String toString() { String tmp = actionName[type] + "("; switch (type) { case TYPE_ATTACK_LOCATION: tmp += x + "," + y; break; case TYPE_NONE: tmp += parameter; break; default: if (parameter != DIRECTION_NONE) { if (parameter == DIRECTION_UP) { tmp += "up"; } if (parameter == DIRECTION_RIGHT) { tmp += "right"; } if (parameter == DIRECTION_DOWN) { tmp += "down"; } if (parameter == DIRECTION_LEFT) { tmp += "left"; } } if (parameter != DIRECTION_NONE && unitType != null) { tmp += ","; } if (unitType != null) { tmp += unitType.name; } break; } return tmp + ")"; } /** * Returns the name of this action * * @return */ public String getActionName() { return actionName[type]; } /** * Returns the direction associated with this action * * @return */ public int getDirection() { return parameter; } /** * Returns the X coordinate associated with this action * * @return */ public int getLocationX() { return x; } /** * Returns the Y coordinate associated with this action * * @return */ public int getLocationY() { return y; } /** * Writes a XML representation of this action * * @param w */ public void toxml(XMLWriter w) { String attributes = "type=\"" + type + "\" "; if (type == TYPE_ATTACK_LOCATION) { attributes += "x=\"" + x + "\" y=\"" + y + "\""; } else { if (parameter != DIRECTION_NONE) { attributes += "parameter=\"" + parameter + "\""; if (unitType != null) { attributes += " "; } } if (unitType != null) { attributes += "unitType=\"" + unitType.name + "\""; } } w.tagWithAttributes("UnitAction", attributes); w.tag("/UnitAction"); } /** * Writes a JSON representation of this action * * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { String attributes = "\"type\":" + type + ""; if (type == TYPE_ATTACK_LOCATION) { attributes += ", \"x\":" + x + ",\"y\":" + y; } else { if (parameter != DIRECTION_NONE) { attributes += ", \"parameter\":" + parameter; } if (unitType != null) { attributes += ", \"unitType\":\"" + unitType.name + "\""; } } w.write("{" + attributes + "}"); } /** * Creates a UnitAction from a XML element * * @param e * @param utt */ public UnitAction(Element e, UnitTypeTable utt) { String typeStr = e.getAttributeValue("type"); String parameterStr = e.getAttributeValue("parameter"); String xStr = e.getAttributeValue("x"); String yStr = e.getAttributeValue("y"); String unitTypeStr = e.getAttributeValue("unitType"); type = Integer.parseInt(typeStr); if (parameterStr != null) { parameter = Integer.parseInt(parameterStr); } if (xStr != null) { x = Integer.parseInt(xStr); } if (yStr != null) { y = Integer.parseInt(yStr); } if (unitTypeStr != null) { unitType = utt.getUnitType(unitTypeStr); } } public void clearResourceUSageCache() { r_cache = null; } /** * Creates a UnitAction from a XML element (calls the corresponding * constructor) * * @param e * @param utt * @return */ public static UnitAction fromXML(Element e, UnitTypeTable utt) { return new UnitAction(e, utt); } /** * Creates a UnitAction from a JSON string * * @param JSON * @param utt * @return */ public static UnitAction fromJSON(String JSON, UnitTypeTable utt) { JsonObject o = Json.parse(JSON).asObject(); return fromJSON(o, utt); } /** * Creates a UnitAction from a JSON object * * @param o * @param utt * @return */ public static UnitAction fromJSON(JsonObject o, UnitTypeTable utt) { UnitAction ua = new UnitAction(o.getInt("type", TYPE_NONE)); ua.parameter = o.getInt("parameter", DIRECTION_NONE); ua.x = o.getInt("x", DIRECTION_NONE); ua.y = o.getInt("y", DIRECTION_NONE); String ut = o.getString("unitType", null); if (ut != null) { ua.unitType = utt.getUnitType(ut); } return ua; } /** * Creates a UnitAction from an action array. * Expects [x_coordinate(x) * y_coordinate(y), a_t(6), p_move(4), p_harvest(4), p_return(4), p_produce_direction(4), * p_produce_unit_type(z), p_attack_location_x_coordinate(x) * p_attack_location_y_coordinate(y), frameskip(n)] * * @param action * @param utt * @param gs * @param u * @param max * @param maxAttackRange This should be 2*a + 1, where a is the maximum * attack range over all units. * @return The created UnitAction. */ public static UnitAction fromVectorAction(int[] action, UnitTypeTable utt, GameState gs, Unit u, int maxAttackRange) { int actionType = action[1]; UnitAction ua = new UnitAction(actionType); int centerCoordinate = maxAttackRange / 2; switch (actionType) { case TYPE_NONE: { break; } case TYPE_MOVE: { ua.parameter = action[2]; break; } case TYPE_HARVEST: { ua.parameter = action[3]; break; } case TYPE_RETURN: { ua.parameter = action[4]; break; } case TYPE_PRODUCE: { ua.parameter = action[5]; ua.unitType = utt.getUnitType(action[6]); // FIXME should there be a break here? } case TYPE_ATTACK_LOCATION: { int relative_x = (action[7] % maxAttackRange - centerCoordinate); int relative_y = (action[7] / maxAttackRange - centerCoordinate); ua.x = u.getX() + relative_x; ua.y = u.getY() + relative_y; break; } } return ua; } public static void getValidActionArray(Unit u, GameState gs, UnitTypeTable utt, int[] mask, int maxAttackRange, int idxOffset) { final List<UnitAction> uas = u.getUnitActions(gs); int centerCoordinate = maxAttackRange / 2; int numUnitTypes = utt.getUnitTypes().size(); for (UnitAction ua:uas) { mask[idxOffset+ua.type] = 1; switch (ua.type) { case TYPE_NONE: { break; } case TYPE_MOVE: { mask[idxOffset+NUMBER_OF_ACTION_TYPES+ua.parameter] = 1; break; } case TYPE_HARVEST: { // +4 offset --> slots for movement directions mask[idxOffset+NUMBER_OF_ACTION_TYPES+4+ua.parameter] = 1; break; } case TYPE_RETURN: { // +4+4 offset --> slots for movement and harvest directions mask[idxOffset+NUMBER_OF_ACTION_TYPES+4+4+ua.parameter] = 1; break; } case TYPE_PRODUCE: { // +4+4+4 offset --> slots for movement, harvest, and resource-return directions mask[idxOffset+NUMBER_OF_ACTION_TYPES+4+4+4+ua.parameter] = 1; // +4+4+4+4 offset --> slots for movement, harvest, resource-return, and unit-produce directions mask[idxOffset+NUMBER_OF_ACTION_TYPES+4+4+4+4+ua.unitType.ID] = 1; break; } case TYPE_ATTACK_LOCATION: { int relative_x = ua.x - u.getX(); int relative_y = ua.y - u.getY(); // +4+4+4+4 offset --> slots for movement, harvest, resource-return, and unit-produce directions mask[idxOffset+NUMBER_OF_ACTION_TYPES+4+4+4+4+numUnitTypes+(centerCoordinate+relative_y)*maxAttackRange+(centerCoordinate+relative_x)] = 1; break; } } } } }
22,380
28.761968
159
java
MicroRTS
MicroRTS-master/src/rts/UnitActionAssignment.java
package rts; import rts.units.Unit; /** * Stores the action assigned to a unit in a given time * @author santi */ public class UnitActionAssignment { public Unit unit; public UnitAction action; public int time; public UnitActionAssignment(Unit a_unit, UnitAction a_action, int a_time) { unit = a_unit; action = a_action; if (action==null) { System.err.println("UnitActionAssignment with null action!"); } time = a_time; } public String toString() { return unit + " assigned action " + action + " at time " + time; } }
621
22.037037
79
java
MicroRTS
MicroRTS-master/src/rts/units/Unit.java
package rts.units; import com.eclipsesource.json.JsonObject; import java.io.Serializable; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.UnitAction; import util.XMLWriter; /** * Represents an instance of any unit in the game. * * @author santi */ public class Unit implements Serializable { /** * The type of this unit (worker, ranged, barracks, etc.) */ UnitType type; /** * Indicates the ID to assign to a new unit. It is incremented when the * constructor without explicit ID is used */ public static long next_ID = 0; /** * The unique identifier of this unit */ long ID; /** * Owner ID */ int player; /** * Coordinates */ int x, y; /** * Resources this unit is carrying */ int resources; /** * Unit hit points */ int hitpoints = 0; /** * Constructs a unit, specifying with all parameters, including the ID. * {@link #next_ID} gets ID+1 if ID >= {@link #next_ID} * * @param a_ID * @param a_player * @param a_type * @param a_x * @param a_y * @param a_resources */ public Unit(long a_ID, int a_player, UnitType a_type, int a_x, int a_y, int a_resources) { player = a_player; type = a_type; x = a_x; y = a_y; resources = a_resources; hitpoints = a_type.hp; ID = a_ID; if (ID >= next_ID) { next_ID = ID + 1; } } /** * Creates a unit without specifying its ID. It is automatically assigned * from {@link #next_ID}, which is incremented. * * @param a_player * @param a_type * @param a_x * @param a_y * @param a_resources */ public Unit(int a_player, UnitType a_type, int a_x, int a_y, int a_resources) { player = a_player; type = a_type; x = a_x; y = a_y; resources = a_resources; hitpoints = a_type.hp; ID = next_ID++; } /** * Creates a unit without specifying resources, which receive zero * * @param a_player * @param a_type * @param a_x * @param a_y */ public Unit(int a_player, UnitType a_type, int a_x, int a_y) { player = a_player; type = a_type; x = a_x; y = a_y; resources = 0; hitpoints = a_type.hp; ID = next_ID++; } /** * Copies the attributes from other unit * * @param other */ public Unit(Unit other) { player = other.player; type = other.type; x = other.x; y = other.y; resources = other.resources; hitpoints = other.hitpoints; ID = other.ID; } /** * Returns the owner ID * * @return */ public int getPlayer() { return player; } /** * Returns the type * * @return */ public UnitType getType() { return type; } /** * Sets the type of this unit. Note: this should not be done lightly. It is * currently thought to be used only when the GUI changes the unit type * table, and tries to create a clone of the current game state, but * changing the UTT. * * @param a_type */ public void setType(UnitType a_type) { type = a_type; } /** * Returns the unique identifier * * @return */ public long getID() { return ID; } /** * Changes the unique identifier Note: Do not use this function unless you * know what you are doing! * * @param a_ID */ public void setID(long a_ID) { ID = a_ID; } /** * Returns the index of this unit in a {@link PhysicalGameState} (as it is * an 'unrolled matrix') * * @param pgs * @return */ public int getPosition(PhysicalGameState pgs) { return x + pgs.getWidth() * y; } /** * Returns the x coordinate * * @return */ public int getX() { return x; } /** * Returns the y coordinate * * @return */ public int getY() { return y; } /** * Sets x coordinate * * @param a_x */ public void setX(int a_x) { x = a_x; } /** * Sets y coordinate * * @param a_y */ public void setY(int a_y) { y = a_y; } /** * Returns the amount of resources this unit is carrying * * @return */ public int getResources() { return resources; } /** * Sets the amount of resources the unit is carrying * * @param a_resources */ public void setResources(int a_resources) { resources = a_resources; } /** * Returns the current HP * * @return */ public int getHitPoints() { return hitpoints; } /** * Returns the maximum HP this unit could have * * @return */ public int getMaxHitPoints() { return type.hp; } /** * Sets the amount of HP * * @param a_hitpoints */ public void setHitPoints(int a_hitpoints) { hitpoints = a_hitpoints; } /** * The cost to produce this unit * * @return */ public int getCost() { return type.cost; } /** * The time this unit gets to move * * @return */ public int getMoveTime() { return type.moveTime; } /** * The time it takes to perform an attack * * @return */ public int getAttackTime() { return type.attackTime; } /** * Returns the attack range * * @return */ public int getAttackRange() { return type.attackRange; } /** * Returns the minimum damage this unit's attack inflict * * @return */ public int getMinDamage() { return type.minDamage; } /** * Returns the maximum damage this unit's attack inflict * * @return */ public int getMaxDamage() { return type.maxDamage; } /** * Returns the amount of resources this unit can harvest * * @return */ public int getHarvestAmount() { return type.harvestAmount; } /** * The time it takes to harvest * * @return */ public int getHarvestTime() { return type.harvestTime; } /** * Returns true if the unit is idle (i.e. if it's not executing any actions) * * @return */ public boolean isIdle(GameState s) { UnitAction ua = s.getUnitAction(this); return ua == null; } /** * Returns a list of actions this unit can perform in a given game state. An * idle action for 10 cycles is always generated * * @param s * @return */ public List<UnitAction> getUnitActions(GameState s) { // Unless specified, generate "NONE" actions with duration 10 cycles return getUnitActions(s, 10); } /** * Returns a list of actions this unit can perform in a given game state. An * idle action for noneDuration cycles is always generated * * @param s * @param noneDuration the amount of cycles for the idle action that is * always generated * @return */ public List<UnitAction> getUnitActions(GameState s, int noneDuration) { List<UnitAction> l = new ArrayList<>(); PhysicalGameState pgs = s.getPhysicalGameState(); Player p = pgs.getPlayer(player); // retrieves units around me Unit uup = null, uright = null, udown = null, uleft = null; for (Unit u : pgs.getUnits()) { if (u.x == x) { if (u.y == y - 1) { uup = u; } else if (u.y == y + 1) { udown = u; } } else { if (u.y == y) { if (u.x == x - 1) { uleft = u; } else if (u.x == x + 1) { uright = u; } } } } // if this unit can attack, adds an attack action for each unit around it if (type.canAttack) { if (type.attackRange == 1) { if (y > 0 && uup != null && uup.player != player && uup.player >= 0) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, uup.x, uup.y)); } if (x < pgs.getWidth() - 1 && uright != null && uright.player != player && uright.player >= 0) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, uright.x, uright.y)); } if (y < pgs.getHeight() - 1 && udown != null && udown.player != player && udown.player >= 0) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, udown.x, udown.y)); } if (x > 0 && uleft != null && uleft.player != player && uleft.player >= 0) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, uleft.x, uleft.y)); } } else { int sqrange = type.attackRange * type.attackRange; for (Unit u : pgs.getUnits()) { if (u.player < 0 || u.player == player) { continue; } int sq_dx = (u.x - x) * (u.x - x); int sq_dy = (u.y - y) * (u.y - y); if (sq_dx + sq_dy <= sqrange) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, u.x, u.y)); } } } } // if this unit can harvest, adds a harvest action for each resource around it // if it is already carrying resources, adds a return action for each allied base around it if (type.canHarvest) { // harvest: if (resources == 0) { if (y > 0 && uup != null && uup.type.isResource) { l.add(new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_UP)); } if (x < pgs.getWidth() - 1 && uright != null && uright.type.isResource) { l.add(new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_RIGHT)); } if (y < pgs.getHeight() - 1 && udown != null && udown.type.isResource) { l.add(new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_DOWN)); } if (x > 0 && uleft != null && uleft.type.isResource) { l.add(new UnitAction(UnitAction.TYPE_HARVEST, UnitAction.DIRECTION_LEFT)); } } // return: if (resources > 0) { if (y > 0 && uup != null && uup.type.isStockpile && uup.player == player) { l.add(new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_UP)); } if (x < pgs.getWidth() - 1 && uright != null && uright.type.isStockpile && uright.player == player) { l.add(new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_RIGHT)); } if (y < pgs.getHeight() - 1 && udown != null && udown.type.isStockpile && udown.player == player) { l.add(new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_DOWN)); } if (x > 0 && uleft != null && uleft.type.isStockpile && uleft.player == player) { l.add(new UnitAction(UnitAction.TYPE_RETURN, UnitAction.DIRECTION_LEFT)); } } } // if the player has enough resources, adds a produce action for each type this unit produces. // a produce action is added for each free tile around the producer for (UnitType ut : type.produces) { if (p.getResources() >= ut.cost) { int tup = (y > 0 ? pgs.getTerrain(x, y - 1) : PhysicalGameState.TERRAIN_WALL); int tright = (x < pgs.getWidth() - 1 ? pgs.getTerrain(x + 1, y) : PhysicalGameState.TERRAIN_WALL); int tdown = (y < pgs.getHeight() - 1 ? pgs.getTerrain(x, y + 1) : PhysicalGameState.TERRAIN_WALL); int tleft = (x > 0 ? pgs.getTerrain(x - 1, y) : PhysicalGameState.TERRAIN_WALL); if (tup == PhysicalGameState.TERRAIN_NONE && pgs.getUnitAt(x, y - 1) == null) { l.add(new UnitAction(UnitAction.TYPE_PRODUCE, UnitAction.DIRECTION_UP, ut)); } if (tright == PhysicalGameState.TERRAIN_NONE && pgs.getUnitAt(x + 1, y) == null) { l.add(new UnitAction(UnitAction.TYPE_PRODUCE, UnitAction.DIRECTION_RIGHT, ut)); } if (tdown == PhysicalGameState.TERRAIN_NONE && pgs.getUnitAt(x, y + 1) == null) { l.add(new UnitAction(UnitAction.TYPE_PRODUCE, UnitAction.DIRECTION_DOWN, ut)); } if (tleft == PhysicalGameState.TERRAIN_NONE && pgs.getUnitAt(x - 1, y) == null) { l.add(new UnitAction(UnitAction.TYPE_PRODUCE, UnitAction.DIRECTION_LEFT, ut)); } } } // if the unit can move, adds a move action for each free tile around it if (type.canMove) { int tup = (y > 0 ? pgs.getTerrain(x, y - 1) : PhysicalGameState.TERRAIN_WALL); int tright = (x < pgs.getWidth() - 1 ? pgs.getTerrain(x + 1, y) : PhysicalGameState.TERRAIN_WALL); int tdown = (y < pgs.getHeight() - 1 ? pgs.getTerrain(x, y + 1) : PhysicalGameState.TERRAIN_WALL); int tleft = (x > 0 ? pgs.getTerrain(x - 1, y) : PhysicalGameState.TERRAIN_WALL); if (tup == PhysicalGameState.TERRAIN_NONE && uup == null) { l.add(new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_UP)); } if (tright == PhysicalGameState.TERRAIN_NONE && uright == null) { l.add(new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_RIGHT)); } if (tdown == PhysicalGameState.TERRAIN_NONE && udown == null) { l.add(new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_DOWN)); } if (tleft == PhysicalGameState.TERRAIN_NONE && uleft == null) { l.add(new UnitAction(UnitAction.TYPE_MOVE, UnitAction.DIRECTION_LEFT)); } } // units can always stay idle: l.add(new UnitAction(UnitAction.TYPE_NONE, noneDuration)); return l; } /** * Indicates whether this unit can perform an action in a given state * * @param ua * @param gs * @return */ public boolean canExecuteAction(UnitAction ua, GameState gs) { List<UnitAction> l = getUnitActions(gs, ua.ETA(this)); return l.contains(ua); } public String toString() { return type.name + "(" + ID + ")" + "(" + player + ", (" + x + "," + y + "), " + hitpoints + ", " + resources + ")"; } public Unit clone() { return new Unit(this); } /** * Returns the unique ID */ public int hashCode() { return (int) ID; } /** * Writes the XML representation of this unit * * @param w */ public void toxml(XMLWriter w) { w.tagWithAttributes( this.getClass().getName(), "type=\"" + type.name + "\" " + "ID=\"" + ID + "\" " + "player=\"" + player + "\" " + "x=\"" + x + "\" " + "y=\"" + y + "\" " + "resources=\"" + resources + "\" " + "hitpoints=\"" + hitpoints + "\" " ); w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation of this unit * * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { w.write( "{\"type\":\"" + type.name + "\", " + "\"ID\":" + ID + ", " + "\"player\":" + player + ", " + "\"x\":" + x + ", " + "\"y\":" + y + ", " + "\"resources\":" + resources + ", " + "\"hitpoints\":" + hitpoints + "}" ); } /** * Constructs a unit from a XML element * * @param e * @param utt * @return */ public static Unit fromXML(Element e, UnitTypeTable utt) { String typeName = e.getAttributeValue("type"); String IDStr = e.getAttributeValue("ID"); String playerStr = e.getAttributeValue("player"); String xStr = e.getAttributeValue("x"); String yStr = e.getAttributeValue("y"); String resourcesStr = e.getAttributeValue("resources"); String hitpointsStr = e.getAttributeValue("hitpoints"); long ID = Long.parseLong(IDStr); if (ID >= next_ID) { next_ID = ID + 1; } UnitType type = utt.getUnitType(typeName); int player = Integer.parseInt(playerStr); int x = Integer.parseInt(xStr); int y = Integer.parseInt(yStr); int resources = Integer.parseInt(resourcesStr); int hitpoints = Integer.parseInt(hitpointsStr); Unit u = new Unit(ID, player, type, x, y, resources); u.hitpoints = hitpoints; return u; } /** * Constructs a unit from a JSON object * * @param o * @param utt * @return */ public static Unit fromJSON(JsonObject o, UnitTypeTable utt) { Unit u = new Unit( o.getLong("ID", -1), o.getInt("player", -1), utt.getUnitType(o.getString("type", null)), o.getInt("x", 0), o.getInt("y", 0), o.getInt("resources", 0) ); u.hitpoints = o.getInt("hitpoints", 1); return u; } }
18,313
27.570983
117
java
MicroRTS
MicroRTS-master/src/rts/units/UnitType.java
package rts.units; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.io.Writer; import java.util.ArrayList; import org.jdom.Element; import util.XMLWriter; /** * A general unit definition that could turn out to be anything * @author santi, inspired in the original UnitDefinition class by Jeff Bernard * */ public class UnitType { /** * The unique identifier of this type */ public int ID = 0; /** * The name of this type */ public String name; /** * Cost to produce a unit of this type */ public int cost = 1; /** * Initial Hit Points of units of this type */ public int hp = 1; /** * Minimum damage of the attack from a unit of this type */ public int minDamage = 1; /** * Maximum damage of the attack from a unit of this type */ public int maxDamage = 1; /** * Range of the attack from a unit of this type */ public int attackRange = 1; /** * Time that each action takes to accomplish */ public int produceTime = 10, moveTime = 10, attackTime = 10, harvestTime = 10, returnTime = 10; /** * How many resources the unit can carry. * Each time the harvest action is executed, this is * how many resources does the unit gets */ public int harvestAmount = 1; /** * the radius a unit can see for partially observable game states. */ public int sightRadius = 4; /** * Can this unit type be harvested? */ public boolean isResource = false; /** * Can resources be returned to this unit type? */ public boolean isStockpile = false; /** * Is this a harvester type? */ public boolean canHarvest = false; /** * Can a unit of this type move? */ public boolean canMove = true; /** * Can a unit of this type attack? */ public boolean canAttack = true; /** * Units that this type of unit can produce */ public ArrayList<UnitType> produces = new ArrayList<>(); /** * Which unit types produce a unit of this type */ public ArrayList<UnitType> producedBy = new ArrayList<>(); /** * Returns the hash code of the name * // assume that all unit types have different names: */ public int hashCode() { return name.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (!(o instanceof UnitType)) return false; return name.equals(((UnitType)o).name); } /** * Adds a unit type that a unit of this type can produce * @param ut */ public void produces(UnitType ut) { produces.add(ut); ut.producedBy.add(this); } /** * Creates a temporary instance with just the name and ID from a XML element * @param unittype_e * @return */ static UnitType createStub(Element unittype_e) { UnitType ut = new UnitType(); ut.ID = Integer.parseInt(unittype_e.getAttributeValue("ID")); ut.name = unittype_e.getAttributeValue("name"); return ut; } /** * Creates a temporary instance with just the name and ID from a JSON object * @param o * @return */ static UnitType createStub(JsonObject o) { UnitType ut = new UnitType(); ut.ID = o.getInt("ID",-1); ut.name = o.getString("name",null); return ut; } /** * Updates the attributes of this type from XML * @param unittype_e * @param utt */ void updateFromXML(Element unittype_e, UnitTypeTable utt) { cost = Integer.parseInt(unittype_e.getAttributeValue("cost")); hp = Integer.parseInt(unittype_e.getAttributeValue("hp")); minDamage = Integer.parseInt(unittype_e.getAttributeValue("minDamage")); maxDamage = Integer.parseInt(unittype_e.getAttributeValue("maxDamage")); attackRange = Integer.parseInt(unittype_e.getAttributeValue("attackRange")); produceTime = Integer.parseInt(unittype_e.getAttributeValue("produceTime")); moveTime = Integer.parseInt(unittype_e.getAttributeValue("moveTime")); attackTime = Integer.parseInt(unittype_e.getAttributeValue("attackTime")); harvestTime = Integer.parseInt(unittype_e.getAttributeValue("harvestTime")); returnTime = Integer.parseInt(unittype_e.getAttributeValue("returnTime")); harvestAmount = Integer.parseInt(unittype_e.getAttributeValue("harvestAmount")); sightRadius = Integer.parseInt(unittype_e.getAttributeValue("sightRadius")); isResource = Boolean.parseBoolean(unittype_e.getAttributeValue("isResource")); isStockpile = Boolean.parseBoolean(unittype_e.getAttributeValue("isStockpile")); canHarvest = Boolean.parseBoolean(unittype_e.getAttributeValue("canHarvest")); canMove = Boolean.parseBoolean(unittype_e.getAttributeValue("canMove")); canAttack = Boolean.parseBoolean(unittype_e.getAttributeValue("canAttack")); for(Object o:unittype_e.getChildren("produces")) { Element produces_e = (Element)o; produces.add(utt.getUnitType(produces_e.getAttributeValue("type"))); } for(Object o:unittype_e.getChildren("producedBy")) { Element producedby_e = (Element)o; producedBy.add(utt.getUnitType(producedby_e.getAttributeValue("type"))); } } /** * Updates the attributes of this type from a JSON string * @param JSON * @param utt */ void updateFromJSON(String JSON, UnitTypeTable utt) { JsonObject o = Json.parse(JSON).asObject(); updateFromJSON(o, utt); } /** * Updates the attributes of this type from a JSON object * @param o * @param utt */ void updateFromJSON(JsonObject o, UnitTypeTable utt) { cost = o.getInt("cost", 1); hp = o.getInt("hp", 1); minDamage = o.getInt("minDamage", 1); maxDamage = o.getInt("maxDamage", 1); attackRange = o.getInt("attackRange", 1); produceTime = o.getInt("produceTime", 10); moveTime = o.getInt("moveTime", 10); attackTime = o.getInt("attackTime", 10); harvestTime = o.getInt("produceTime", 10); produceTime = o.getInt("produceTime", 10); harvestAmount = o.getInt("harvestAmount", 10); sightRadius = o.getInt("sightRadius", 10); isResource = o.getBoolean("isResource", false); isStockpile = o.getBoolean("isStockpile", false); canHarvest = o.getBoolean("canHarvest", false); canMove = o.getBoolean("canMove", false); canAttack = o.getBoolean("canAttack", false); JsonArray produces_a = o.get("produces").asArray(); for(JsonValue v:produces_a.values()) { produces.add(utt.getUnitType(v.asString())); } JsonArray producedBy_a = o.get("producedBy").asArray(); for(JsonValue v:producedBy_a.values()) { producedBy.add(utt.getUnitType(v.asString())); } } /** * Writes a XML representation * @param w */ public void toxml(XMLWriter w) { w.tagWithAttributes( this.getClass().getName(), "ID=\""+ID+"\" "+ "name=\""+name+"\" "+ "cost=\""+cost+"\" "+ "hp=\""+hp+"\" "+ "minDamage=\""+minDamage+"\" "+ "maxDamage=\""+maxDamage+"\" "+ "attackRange=\""+attackRange+"\" "+ "produceTime=\""+produceTime+"\" "+ "moveTime=\""+moveTime+"\" "+ "attackTime=\""+attackTime+"\" "+ "harvestTime=\""+harvestTime+"\" "+ "returnTime=\""+returnTime+"\" "+ "harvestAmount=\""+harvestAmount+"\" "+ "sightRadius=\""+sightRadius+"\" "+ "isResource=\""+isResource+"\" "+ "isStockpile=\""+isStockpile+"\" "+ "canHarvest=\""+canHarvest+"\" "+ "canMove=\""+canMove+"\" "+ "canAttack=\""+canAttack+"\"" ); for (UnitType ut : produces) { w.tagWithAttributes("produces", "type=\"" + ut.name + "\""); w.tag("/produces"); } for (UnitType ut : producedBy) { w.tagWithAttributes("producedBy", "type=\"" + ut.name + "\""); w.tag("/producedBy"); } w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { w.write( "{" + "\"ID\":"+ID+", "+ "\"name\":\""+name+"\", "+ "\"cost\":"+cost+", "+ "\"hp\":"+hp+", "+ "\"minDamage\":"+minDamage+", "+ "\"maxDamage\":"+maxDamage+", "+ "\"attackRange\":"+attackRange+", "+ "\"produceTime\":"+produceTime+", "+ "\"moveTime\":"+moveTime+", "+ "\"attackTime\":"+attackTime+", "+ "\"harvestTime\":"+harvestTime+", "+ "\"returnTime\":"+returnTime+", "+ "\"harvestAmount\":"+harvestAmount+", "+ "\"sightRadius\":"+sightRadius+", "+ "\"isResource\":"+isResource+", "+ "\"isStockpile\":"+isStockpile+", "+ "\"canHarvest\":"+canHarvest+", "+ "\"canMove\":"+canMove+", "+ "\"canAttack\":"+canAttack+", " ); boolean first = true; w.write("\"produces\":["); for (UnitType ut : produces) { if (!first) w.write(", "); w.write("\"" + ut.name + "\""); first = false; } first = true; w.write("], \"producedBy\":["); for (UnitType ut : producedBy) { if (!first) w.write(", "); w.write("\"" + ut.name + "\""); first = false; } w.write("]}"); } /** * Creates a unit type from XML * @param e * @param utt * @return */ public static UnitType fromXML(Element e, UnitTypeTable utt) { UnitType ut = new UnitType(); ut.updateFromXML(e, utt); return ut; } /** * Creates a unit type from a JSON string * @param JSON * @param utt * @return */ public static UnitType fromJSON(String JSON, UnitTypeTable utt) { UnitType ut = new UnitType(); ut.updateFromJSON(JSON, utt); return ut; } /** * Creates a unit type from a JSON object * @param o * @param utt * @return */ public static UnitType fromJSON(JsonObject o, UnitTypeTable utt) { UnitType ut = new UnitType(); ut.updateFromJSON(o, utt); return ut; } }
11,084
27.942559
88
java
MicroRTS
MicroRTS-master/src/rts/units/UnitTypeTable.java
package rts.units; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import util.XMLWriter; /** * The unit type table stores the unit types the game can have. * It also determines the attributes of each unit type. * The unit type table determines the balance of the game. * @author santi */ public class UnitTypeTable { /** * Empty type table should not be used! */ public static final int EMPTY_TYPE_TABLE = -1; /** * Version one */ public static final int VERSION_ORIGINAL = 1; /** * Version two (a fine tune of the original) */ public static final int VERSION_ORIGINAL_FINETUNED = 2; /** * A non-deterministic version (damages are random) */ public static final int VERSION_NON_DETERMINISTIC = 3; /** * A conflict resolution policy where move conflicts cancel both moves */ public static final int MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH = 1; // (default) /** * A conflict resolution policy where move conflicts are solved randomly */ public static final int MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM = 2; // (makes game non-deterministic) /** * A conflict resolution policy where move conflicts are solved by * alternating the units trying to move */ public static final int MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING = 3; /** * The list of unit types allowed in the game */ List<UnitType> unitTypes = new ArrayList<>(); /** * Which move conflict resolution is being adopted */ int moveConflictResolutionStrategy = MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH; /** * Creates a UnitTypeTable with version {@link #VERSION_ORIGINAL} and * move conflict resolution as {@link #MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH} */ public UnitTypeTable() { setUnitTypeTable(VERSION_ORIGINAL, MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH); } /** * Creates a unit type table with specified version and move conflict resolution * as {@link #MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH} * @param version */ public UnitTypeTable(int version) { setUnitTypeTable(version, MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH); } /** * Creates a unit type table specifying both the version and the move conflict * resolution strategy * @param version * @param crs the move conflict resolution strategy */ public UnitTypeTable(int version, int crs) { setUnitTypeTable(version, crs); } /** * Sets the version and move conflict resolution strategy to use * and configures the attributes of each unit type depending on the * version * @param version * @param crs the move conflict resolution strategy */ public void setUnitTypeTable(int version, int crs) { moveConflictResolutionStrategy = crs; if (version == EMPTY_TYPE_TABLE) return; // Create the unit types: // RESOURCE: UnitType resource = new UnitType(); resource.name = "Resource"; resource.isResource = true; resource.isStockpile = false; resource.canHarvest = false; resource.canMove = false; resource.canAttack = false; resource.sightRadius = 0; addUnitType(resource); // BASE: UnitType base = new UnitType(); base.name = "Base"; base.cost = 10; base.hp = 10; switch(version) { case VERSION_ORIGINAL: base.produceTime = 250; break; case VERSION_ORIGINAL_FINETUNED: base.produceTime = 200; break; } base.isResource = false; base.isStockpile = true; base.canHarvest = false; base.canMove = false; base.canAttack = false; base.sightRadius = 5; addUnitType(base); // BARRACKS: UnitType barracks = new UnitType(); barracks.name = "Barracks"; barracks.cost = 5; barracks.hp = 4; switch(version) { case VERSION_ORIGINAL: barracks.produceTime = 200; break; case VERSION_ORIGINAL_FINETUNED: case VERSION_NON_DETERMINISTIC: barracks.produceTime = 100; break; } barracks.isResource = false; barracks.isStockpile = false; barracks.canHarvest = false; barracks.canMove = false; barracks.canAttack = false; barracks.sightRadius = 3; addUnitType(barracks); // WORKER: UnitType worker = new UnitType(); worker.name = "Worker"; worker.cost = 1; worker.hp = 1; switch(version) { case VERSION_ORIGINAL: case VERSION_ORIGINAL_FINETUNED: worker.minDamage = worker.maxDamage = 1; break; case VERSION_NON_DETERMINISTIC: worker.minDamage = 0; worker.maxDamage = 2; break; } worker.attackRange = 1; worker.produceTime = 50; worker.moveTime = 10; worker.attackTime = 5; worker.harvestTime = 20; worker.returnTime = 10; worker.isResource = false; worker.isStockpile = false; worker.canHarvest = true; worker.canMove = true; worker.canAttack = true; worker.sightRadius = 3; addUnitType(worker); // LIGHT: UnitType light = new UnitType(); light.name = "Light"; light.cost = 2; light.hp = 4; switch(version) { case VERSION_ORIGINAL: case VERSION_ORIGINAL_FINETUNED: light.minDamage = light.maxDamage = 2; break; case VERSION_NON_DETERMINISTIC: light.minDamage = 1; light.maxDamage = 3; break; } light.attackRange = 1; light.produceTime = 80; light.moveTime = 8; light.attackTime = 5; light.isResource = false; light.isStockpile = false; light.canHarvest = false; light.canMove = true; light.canAttack = true; light.sightRadius = 2; addUnitType(light); // HEAVY: UnitType heavy = new UnitType(); heavy.name = "Heavy"; switch(version) { case VERSION_ORIGINAL: case VERSION_ORIGINAL_FINETUNED: heavy.minDamage = heavy.maxDamage = 4; break; case VERSION_NON_DETERMINISTIC: heavy.minDamage = 0; heavy.maxDamage = 6; break; } heavy.attackRange = 1; heavy.produceTime = 120; switch(version) { case VERSION_ORIGINAL: heavy.moveTime = 12; heavy.hp = 4; heavy.cost = 2; break; case VERSION_ORIGINAL_FINETUNED: case VERSION_NON_DETERMINISTIC: heavy.moveTime = 10; heavy.hp = 8; heavy.cost = 3; break; } heavy.attackTime = 5; heavy.isResource = false; heavy.isStockpile = false; heavy.canHarvest = false; heavy.canMove = true; heavy.canAttack = true; heavy.sightRadius = 2; addUnitType(heavy); // RANGED: UnitType ranged = new UnitType(); ranged.name = "Ranged"; ranged.cost = 2; ranged.hp = 1; switch(version) { case VERSION_ORIGINAL: case VERSION_ORIGINAL_FINETUNED: ranged.minDamage = ranged.maxDamage = 1; break; case VERSION_NON_DETERMINISTIC: ranged.minDamage = 1; ranged.maxDamage = 2; break; } ranged.attackRange = 3; ranged.produceTime = 100; ranged.moveTime = 10; ranged.attackTime = 5; ranged.isResource = false; ranged.isStockpile = false; ranged.canHarvest = false; ranged.canMove = true; ranged.canAttack = true; ranged.sightRadius = 3; addUnitType(ranged); base.produces(worker); barracks.produces(light); barracks.produces(heavy); barracks.produces(ranged); worker.produces(base); worker.produces(barracks); } /** * Adds a new unit type to the game * @param ut */ public void addUnitType(UnitType ut) { ut.ID = unitTypes.size(); unitTypes.add(ut); } /** * Retrieves a unit type by its numeric ID * @param ID * @return */ public UnitType getUnitType(int ID) { return unitTypes.get(ID); } /** * Retrieves a unit type by its name. Returns null if name is not found. * @param name * @return */ public UnitType getUnitType(String name) { for(UnitType ut:unitTypes) { if (ut.name.equals(name)) return ut; } return null; } /** * Returns the list of all unit types * @return */ public List<UnitType> getUnitTypes() { return unitTypes; } /** * Returns the integer corresponding to the move conflict resolution strategy in use * @return */ public int getMoveConflictResolutionStrategy() { return moveConflictResolutionStrategy; } /** * Loop through the list of unit types and return the largest attack range * @return */ public int getMaxAttackRange() { int maxAttackRange = 0; for (UnitType unitType : unitTypes) { if (unitType.attackRange > maxAttackRange) { maxAttackRange = unitType.attackRange; } } return maxAttackRange; } /** * Writes a XML representation of this UnitTypeTable * @param w */ public void toxml(XMLWriter w) { w.tagWithAttributes( this.getClass().getName(), "moveConflictResolutionStrategy=\"" + moveConflictResolutionStrategy + "\"" ); for (UnitType ut : unitTypes) ut.toxml(w); w.tag("/" + this.getClass().getName()); } /** * Writes a JSON representation of this UnitTypeTable * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { boolean first = true; w.write("{\"moveConflictResolutionStrategy\":" + moveConflictResolutionStrategy + ","); w.write("\"unitTypes\":["); for (UnitType ut : unitTypes) { if (!first) w.write(", "); ut.toJSON(w); first = false; } w.write("]}"); } /** * Reads from XML and creates a UnitTypeTable * @param e * @return */ public static UnitTypeTable fromXML(Element e) { UnitTypeTable utt = new UnitTypeTable(EMPTY_TYPE_TABLE); utt.moveConflictResolutionStrategy = Integer.parseInt( e.getAttributeValue("moveConflictResolutionStrategy") ); for (Object o : e.getChildren()) { Element unittype_e = (Element) o; utt.unitTypes.add(UnitType.createStub(unittype_e)); } for (Object o : e.getChildren()) { Element unittype_e = (Element) o; utt.getUnitType(unittype_e.getAttributeValue("name")).updateFromXML(unittype_e, utt); } return utt; } /** * Reads from a JSON string and creates a UnitTypeTable * @param JSON * @return */ public static UnitTypeTable fromJSON(String JSON) { JsonObject o = Json.parse(JSON).asObject(); UnitTypeTable utt = new UnitTypeTable(EMPTY_TYPE_TABLE); utt.moveConflictResolutionStrategy = o.getInt( "moveConflictResolutionStrategy", MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH ); JsonArray a = o.get("unitTypes").asArray(); for (JsonValue v : a.values()) { JsonObject uto = v.asObject(); utt.unitTypes.add(UnitType.createStub(uto)); } for (JsonValue v : a.values()) { JsonObject uto = v.asObject(); utt.getUnitType(uto.getString("name", null)).updateFromJSON(uto, utt); } return utt; } }
12,602
27.905963
107
java
MicroRTS
MicroRTS-master/src/tests/AIComplianceTest.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.abstraction.WorkerRush; import ai.core.AI; import ai.core.ParameterSpecification; import ai.mcts.informedmcts.InformedNaiveMCTS; import ai.mcts.naivemcts.NaiveMCTS; import ai.montecarlo.lsi.LSI; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author santi * * This class checks whether an AI class satisfies the requirements to be run properly by microRTS. Specifically: * - Check that it inherits from the "AI" class * - Check that it has at least one constructor with a single parameter (a UnitTypeTable) * - Check that it has setters and getters for all the parameters declared in the "getParameters" function * */ public class AIComplianceTest { public static void main(String args[]) { complianceTest(WorkerRush.class); complianceTest(NaiveMCTS.class); complianceTest(InformedNaiveMCTS.class); complianceTest(LSI.class); } public static boolean complianceTest(Class c) { System.out.println("Testing " + c.getName() + "..."); List<Class> superclasses = getSuperClasses(c); try { UnitTypeTable utt = new UnitTypeTable(); if (!superclasses.contains(AI.class)) { System.err.println(c.getName() + " does not extend AI.class!"); return false; } AI AI_instance = null; try { Constructor cons = c.getConstructor(UnitTypeTable.class); if (cons==null) { System.err.println(c.getName() + " does not have a base constructor with just the UnitTypeTable!"); return false; } AI_instance = (AI)cons.newInstance(utt); }catch(java.lang.NoSuchMethodException e) { System.err.println(c.getName() + " does not have a base constructor with just the UnitTypeTable!"); return false; } List<ParameterSpecification> parameters = AI_instance.getParameters(); for(ParameterSpecification p:parameters) { System.out.println(" " + p.name + ": " + p.type.getName()); try { Method getter = c.getMethod("get" + p.name); if (getter==null) { System.err.println(c.getName() + " does not have a getter for parameter " + p.name); return false; } }catch(java.lang.NoSuchMethodException e) { System.err.println(c.getName() + " does not have a getter for parameter " + p.name); return false; } try { Method setter = c.getMethod("set" + p.name, p.type); if (setter==null) { System.err.println(c.getName() + " does not have a setter for parameter " + p.name); return false; } }catch(java.lang.NoSuchMethodException e) { System.err.println(c.getName() + " does not have a setter for parameter " + p.name); return false; } } PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); GameState gs = new GameState(pgs, utt); PlayerAction pa = AI_instance.getAction(0, gs); if (pa==null) { System.err.println(c.getName() + " did not generate a proper action!"); return false; } else { System.out.println(pa); } }catch(Exception e) { e.printStackTrace(); return false; } System.out.println(c.getName() + " is compliant with the microRTS requirements."); return true; } public static List<Class> getSuperClasses(Class c) { List<Class> l = new ArrayList<>(); while(c!=null) { l.add(c); c = c.getSuperclass(); } return l; } }
4,718
36.452381
119
java
MicroRTS
MicroRTS-master/src/tests/AbstractTraceGenerationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.abstraction.WorkerRush; import ai.abstraction.AbstractAction; import ai.abstraction.AbstractTrace; import ai.abstraction.AbstractTraceEntry; import ai.abstraction.AbstractionLayerAI; import ai.abstraction.LightRush; import ai.abstraction.pathfinding.BFSPathFinding; import java.io.FileWriter; import rts.*; import rts.units.Unit; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class AbstractTraceGenerationTest { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; boolean gameover = false; AI ai1 = new LightRush(utt, new BFSPathFinding()); AI ai2 = new WorkerRush(utt, new BFSPathFinding()); AbstractTrace trace = new AbstractTrace(utt); AbstractTraceEntry te = new AbstractTraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); do{ PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); if (!pa1.isEmpty() || !pa2.isEmpty()) { te = new AbstractTraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); if (ai1 instanceof AbstractionLayerAI) { AbstractionLayerAI ai1a = (AbstractionLayerAI)ai1; for(Unit u:gs.getUnits()) { AbstractAction aa = ai1a.getAbstractAction(u); if (aa!=null) te.addAbstractActionIfNew(u, aa, trace); } } if (ai2 instanceof AbstractionLayerAI) { AbstractionLayerAI ai2a = (AbstractionLayerAI)ai2; for(Unit u:gs.getUnits()) { AbstractAction aa = ai2a.getAbstractAction(u); if (aa!=null) te.addAbstractActionIfNew(u, aa, trace); } } trace.addEntry(te); } gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); }while(!gameover && gs.getTime()<MAXCYCLES); te = new AbstractTraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); XMLWriter xml = new XMLWriter(new FileWriter("abstracttrace.xml")); trace.toxml(xml); xml.flush(); } }
2,775
33.271605
103
java
MicroRTS
MicroRTS-master/src/tests/CompareAllAIsObservable.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ContinuingAI; import ai.core.PseudoContinuingAI; import ai.*; import ai.portfolio.PortfolioAI; import ai.abstraction.LightRush; import ai.abstraction.RangedRush; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.BFSPathFinding; import ai.abstraction.pathfinding.GreedyPathFinding; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.naivemcts.NaiveMCTS; import ai.mcts.uct.DownsamplingUCT; import ai.mcts.uct.UCT; import ai.mcts.uct.UCTUnitActions; import ai.minimax.ABCD.IDABCD; import ai.minimax.RTMiniMax.IDRTMinimax; import ai.minimax.RTMiniMax.IDRTMinimaxRandomized; import ai.montecarlo.*; import java.io.File; import java.io.PrintStream; import java.util.LinkedList; import java.util.List; import rts.PhysicalGameState; import rts.units.UnitTypeTable; import ai.core.InterruptibleAI; /** * * @author santi */ public class CompareAllAIsObservable { public static void main(String args[]) throws Exception { boolean CONTINUING = true; int TIME = 100; int MAX_ACTIONS = 100; int MAX_PLAYOUTS = -1; int PLAYOUT_TIME = 100; int MAX_DEPTH = 10; int RANDOMIZED_AB_REPEATS = 10; List<AI> bots = new LinkedList<>(); UnitTypeTable utt = new UnitTypeTable(); bots.add(new RandomAI(utt)); bots.add(new RandomBiasedAI()); bots.add(new LightRush(utt, new BFSPathFinding())); bots.add(new RangedRush(utt, new BFSPathFinding())); bots.add(new WorkerRush(utt, new BFSPathFinding())); bots.add(new PortfolioAI(new AI[]{new WorkerRush(utt, new BFSPathFinding()), new LightRush(utt, new BFSPathFinding()), new RangedRush(utt, new BFSPathFinding()), new RandomBiasedAI()}, new boolean[]{true,true,true,false}, TIME, MAX_PLAYOUTS, PLAYOUT_TIME*4, new SimpleSqrtEvaluationFunction3())); bots.add(new IDRTMinimax(TIME, new SimpleSqrtEvaluationFunction3())); bots.add(new IDRTMinimaxRandomized(TIME, RANDOMIZED_AB_REPEATS, new SimpleSqrtEvaluationFunction3())); bots.add(new IDABCD(TIME, MAX_PLAYOUTS, new LightRush(utt, new GreedyPathFinding()), PLAYOUT_TIME, new SimpleSqrtEvaluationFunction3(), false)); bots.add(new MonteCarlo(TIME, PLAYOUT_TIME, MAX_PLAYOUTS, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new MonteCarlo(TIME, PLAYOUT_TIME, MAX_PLAYOUTS, MAX_ACTIONS, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); // by setting "MAX_DEPTH = 1" in the next two bots, this effectively makes them Monte Carlo search, instead of Monte Carlo Tree Search bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new UCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new DownsamplingUCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_ACTIONS, MAX_DEPTH, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new UCTUnitActions(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH*10, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); if (CONTINUING) { // Find out which of the bots can be used in "continuing" mode: List<AI> bots2 = new LinkedList<>(); for(AI bot:bots) { if (bot instanceof AIWithComputationBudget) { if (bot instanceof InterruptibleAI) { bots2.add(new ContinuingAI(bot)); } else { bots2.add(new PseudoContinuingAI((AIWithComputationBudget)bot)); } } else { bots2.add(bot); } } bots = bots2; } PrintStream out = new PrintStream(new File("results.txt")); // Separate the matchs by map: List<PhysicalGameState> maps = new LinkedList<>(); maps.add(PhysicalGameState.load("maps/8x8/basesWorkers8x8.xml",utt)); // Experimenter.runExperimentsPartiallyObservable(bots, maps, 10, 3000, 300, true, out); Experimenter.runExperiments(bots, maps, utt, 10, 3000, 300, true, out); maps.clear(); maps.add(PhysicalGameState.load("maps/12x12/melee12x12mixed12.xml",utt)); Experimenter.runExperiments(bots, maps, utt, 10, 3000, 300, true, out); maps.clear(); maps.add(PhysicalGameState.load("maps/8x8/melee8x8mixed6.xml",utt)); Experimenter.runExperiments(bots, maps, utt, 10, 3000, 300, true, out); maps.clear(); maps.add(PhysicalGameState.load("maps/melee4x4light2.xml",utt)); Experimenter.runExperiments(bots, maps, utt, 10, 3000, 300, true, out); } }
5,617
44.674797
162
java
MicroRTS
MicroRTS-master/src/tests/CompareAllAIsPartiallyObservable.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ContinuingAI; import ai.core.PseudoContinuingAI; import ai.portfolio.PortfolioAI; import ai.*; import ai.abstraction.LightRush; import ai.abstraction.RangedRush; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.BFSPathFinding; import ai.abstraction.pathfinding.GreedyPathFinding; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.naivemcts.NaiveMCTS; import ai.mcts.uct.DownsamplingUCT; import ai.mcts.uct.UCT; import ai.mcts.uct.UCTUnitActions; import ai.minimax.ABCD.IDABCD; import ai.minimax.RTMiniMax.IDRTMinimax; import ai.minimax.RTMiniMax.IDRTMinimaxRandomized; import ai.montecarlo.*; import java.io.File; import java.io.PrintStream; import java.util.LinkedList; import java.util.List; import rts.PhysicalGameState; import rts.units.UnitTypeTable; import ai.core.InterruptibleAI; /** * * @author santi */ public class CompareAllAIsPartiallyObservable { public static void main(String args[]) throws Exception { boolean CONTINUING = true; int TIME = 100; int MAX_ACTIONS = 100; int MAX_PLAYOUTS = -1; int PLAYOUT_TIME = 100; int MAX_DEPTH = 10; int RANDOMIZED_AB_REPEATS = 10; List<AI> bots = new LinkedList<>(); UnitTypeTable utt = new UnitTypeTable(); bots.add(new RandomAI(utt)); bots.add(new RandomBiasedAI()); bots.add(new LightRush(utt, new BFSPathFinding())); bots.add(new RangedRush(utt, new BFSPathFinding())); bots.add(new WorkerRush(utt, new BFSPathFinding())); bots.add(new PortfolioAI(new AI[]{new WorkerRush(utt, new BFSPathFinding()), new LightRush(utt, new BFSPathFinding()), new RangedRush(utt, new BFSPathFinding()), new RandomBiasedAI()}, new boolean[]{true,true,true,false}, TIME, MAX_PLAYOUTS, PLAYOUT_TIME*4, new SimpleSqrtEvaluationFunction3())); bots.add(new IDRTMinimax(TIME, new SimpleSqrtEvaluationFunction3())); bots.add(new IDRTMinimaxRandomized(TIME, RANDOMIZED_AB_REPEATS, new SimpleSqrtEvaluationFunction3())); bots.add(new IDABCD(TIME, MAX_PLAYOUTS, new LightRush(utt, new GreedyPathFinding()), PLAYOUT_TIME, new SimpleSqrtEvaluationFunction3(), false)); bots.add(new MonteCarlo(TIME, PLAYOUT_TIME, MAX_PLAYOUTS, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new MonteCarlo(TIME, PLAYOUT_TIME, MAX_PLAYOUTS, MAX_ACTIONS, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); // by setting "MAX_DEPTH = 1" in the next two bots, this effectively makes them Monte Carlo search, instead of Monte Carlo Tree Search bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new UCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new DownsamplingUCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_ACTIONS, MAX_DEPTH, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new UCTUnitActions(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH*10, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3())); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); if (CONTINUING) { // Find out which of the bots can be used in "continuing" mode: List<AI> bots2 = new LinkedList<>(); for(AI bot:bots) { if (bot instanceof AIWithComputationBudget) { if (bot instanceof InterruptibleAI) { bots2.add(new ContinuingAI(bot)); } else { bots2.add(new PseudoContinuingAI((AIWithComputationBudget)bot)); } } else { bots2.add(bot); } } bots = bots2; } PrintStream out = new PrintStream(new File("results-PO.txt")); // Separate the matchs by map: List<PhysicalGameState> maps = new LinkedList<>(); maps.add(PhysicalGameState.load("maps/8x8/basesWorkers8x8.xml",utt)); Experimenter.runExperimentsPartiallyObservable(bots, maps, utt, 10, 3000, 300, true, out); maps.clear(); maps.add(PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml",utt)); Experimenter.runExperimentsPartiallyObservable(bots, maps, utt, 10, 3000, 300, true, out); } }
5,213
44.736842
162
java
MicroRTS
MicroRTS-master/src/tests/Experimenter.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.LinkedList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.Trace; import rts.TraceEntry; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class Experimenter { public static int DEBUG = 0; public static boolean GC_EACH_FRAME = true; public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize) throws Exception { runExperiments(bots, maps, utt,iterations, max_cycles, max_inactive_cycles, visualize, System.out, -1, false); } public static void runExperimentsPartiallyObservable(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize) throws Exception { runExperiments(bots, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, System.out, -1, true); } public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out) throws Exception { runExperiments(bots, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, out, -1, false); } public static void runExperimentsPartiallyObservable(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out) throws Exception { runExperiments(bots, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, out, -1, true); } public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out, int run_only_those_involving_this_AI, boolean partiallyObservable) throws Exception { runExperiments(bots, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, out, run_only_those_involving_this_AI, false, partiallyObservable); } public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out, int run_only_those_involving_this_AI, boolean skip_self_play, boolean partiallyObservable) throws Exception { runExperiments(bots, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, out, run_only_those_involving_this_AI, skip_self_play, partiallyObservable, false, false, ""); } public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out, int run_only_those_involving_this_AI, boolean skip_self_play, boolean partiallyObservable, boolean saveTrace, boolean saveZip, String traceDir) throws Exception { int wins[][] = new int[bots.size()][bots.size()]; int ties[][] = new int[bots.size()][bots.size()]; int loses[][] = new int[bots.size()][bots.size()]; double win_time[][] = new double[bots.size()][bots.size()]; double tie_time[][] = new double[bots.size()][bots.size()]; double lose_time[][] = new double[bots.size()][bots.size()]; List<AI> bots2 = new LinkedList<>(); for(AI bot:bots) bots2.add(bot.clone()); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (run_only_those_involving_this_AI!=-1 && ai1_idx!=run_only_those_involving_this_AI && ai2_idx!=run_only_those_involving_this_AI) continue; // if (ai1_idx==0 && ai2_idx==0) continue; if (skip_self_play && ai1_idx==ai2_idx) continue; int m=0; for(PhysicalGameState pgs:maps) { for (int i = 0; i < iterations; i++) { //cloning just in case an AI has a memory leak //by using a clone, it is discarded, along with the leaked memory, //after each game, rather than accumulating //over several games AI ai1 = bots.get(ai1_idx).clone(); AI ai2 = bots2.get(ai2_idx).clone(); long lastTimeActionIssued = 0; ai1.reset(); ai2.reset(); GameState gs = new GameState(pgs.clone(),utt); PhysicalGameStateJFrame w = null; if (visualize) w = PhysicalGameStatePanel.newVisualizer(gs, 600, 600, partiallyObservable); out.println("MATCH UP: " + ai1 + " vs " + ai2); boolean gameover = false; Trace trace = null; TraceEntry te; if(saveTrace){ trace = new Trace(utt); te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); } do { if (GC_EACH_FRAME) System.gc(); PlayerAction pa1 = null, pa2 = null; if (partiallyObservable) { pa1 = ai1.getAction(0, new PartiallyObservableGameState(gs,0)); // if (DEBUG>=1) {System.out.println("AI1 done.");out.flush();} pa2 = ai2.getAction(1, new PartiallyObservableGameState(gs,1)); // if (DEBUG>=1) {System.out.println("AI2 done.");out.flush();} } else { pa1 = ai1.getAction(0, gs); if (DEBUG>=1) {System.out.println("AI1 done.");out.flush();} pa2 = ai2.getAction(1, gs); if (DEBUG>=1) {System.out.println("AI2 done.");out.flush();} } if (saveTrace && (!pa1.isEmpty() || !pa2.isEmpty())) { te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } if (gs.issueSafe(pa1)) lastTimeActionIssued = gs.getTime(); // if (DEBUG>=1) {System.out.println("issue action AI1 done: " + pa1);out.flush();} if (gs.issueSafe(pa2)) lastTimeActionIssued = gs.getTime(); // if (DEBUG>=1) {System.out.println("issue action AI2 done:" + pa2);out.flush();} gameover = gs.cycle(); if (DEBUG>=1) {System.out.println("cycle done.");out.flush();} if (w!=null) { w.setStateCloning(gs); w.repaint(); try { Thread.sleep(1); // give time to the window to repaint } catch (Exception e) { e.printStackTrace(); } // if (DEBUG>=1) {System.out.println("repaint done.");out.flush();} } } while (!gameover && (gs.getTime() < max_cycles) && (gs.getTime() - lastTimeActionIssued < max_inactive_cycles)); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); if(saveTrace){ te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); XMLWriter xml; ZipOutputStream zip = null; String filename=ai1.toString()+"Vs"+ai2.toString()+"-"+m+"-"+i; filename=filename.replace("/", ""); filename=filename.replace(")", ""); filename=filename.replace("(", ""); filename=traceDir+"/"+filename; if(saveZip){ zip=new ZipOutputStream(new FileOutputStream(filename+".zip")); zip.putNextEntry(new ZipEntry("game.xml")); xml = new XMLWriter(new OutputStreamWriter(zip)); }else{ xml = new XMLWriter(new FileWriter(filename+".xml")); } trace.toxml(xml); xml.flush(); if(saveZip){ zip.closeEntry(); zip.close(); } } if (w!=null) w.dispose(); int winner = gs.winner(); out.println("Winner: " + winner + " in " + gs.getTime() + " cycles"); out.println(ai1 + " : " + ai1.statisticsString()); out.println(ai2 + " : " + ai2.statisticsString()); out.flush(); if (winner == -1) { ties[ai1_idx][ai2_idx]++; tie_time[ai1_idx][ai2_idx]+=gs.getTime(); ties[ai2_idx][ai1_idx]++; tie_time[ai2_idx][ai1_idx]+=gs.getTime(); } else if (winner == 0) { wins[ai1_idx][ai2_idx]++; win_time[ai1_idx][ai2_idx]+=gs.getTime(); loses[ai2_idx][ai1_idx]++; lose_time[ai2_idx][ai1_idx]+=gs.getTime(); } else if (winner == 1) { loses[ai1_idx][ai2_idx]++; lose_time[ai1_idx][ai2_idx]+=gs.getTime(); wins[ai2_idx][ai1_idx]++; win_time[ai2_idx][ai1_idx]+=gs.getTime(); } } m++; } } } out.println("Wins: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(wins[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Ties: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(ties[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Loses: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(loses[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Win average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (wins[ai1_idx][ai2_idx]>0) { out.print((win_time[ai1_idx][ai2_idx]/wins[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Tie average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (ties[ai1_idx][ai2_idx]>0) { out.print((tie_time[ai1_idx][ai2_idx]/ties[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Lose average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (loses[ai1_idx][ai2_idx]>0) { out.print((lose_time[ai1_idx][ai2_idx]/loses[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.flush(); } }
13,710
49.781481
232
java
MicroRTS
MicroRTS-master/src/tests/ExperimenterAsymmetric.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.BranchingFactorCalculatorDouble; import ai.core.AI; import gui.PhysicalGameStatePanel; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.JFrame; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.Trace; import rts.TraceEntry; import rts.units.UnitTypeTable; import util.RunnableWithTimeOut; import util.XMLWriter; /** * * @author santi */ public class ExperimenterAsymmetric { public static long BRANCHING_CALCULATION_TIMEOUT = 7200000; public static boolean PRINT_BRANCHING_AT_EACH_MOVE = false; static class BranchingCalculatorWithTimeOut { static double branching = 0; static boolean running = false; static double branching(GameState gs, int player, long timeOutMillis) throws Exception { if (running) throw new Exception("Two calls to BranchingCalculatorWithTimeOut in parallel!"); branching = 0; running = true; try { RunnableWithTimeOut.runWithTimeout(new Runnable() { @Override public void run() { try { branching = BranchingFactorCalculatorDouble.branchingFactorByResourceUsageSeparatingFast(gs, player); }catch(Exception e) { e.printStackTrace(); } } }, timeOutMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // System.out.println("BranchingCalculatorWithTimeOut: timeout!"); } running = false; return branching; } } public static void runExperiments(List<AI> bots1, List<AI> bots2, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out) throws Exception { runExperiments(bots1, bots2, maps, utt, iterations, max_cycles, max_inactive_cycles, visualize, out, false, false, ""); } public static void runExperiments(List<AI> bots1, List<AI> bots2, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out, boolean saveTrace, boolean saveZip, String traceDir) throws Exception { int wins[][] = new int[bots1.size()][bots2.size()]; int ties[][] = new int[bots1.size()][bots2.size()]; int loses[][] = new int[bots1.size()][bots2.size()]; double win_time[][] = new double[bots1.size()][bots2.size()]; double tie_time[][] = new double[bots1.size()][bots2.size()]; double lose_time[][] = new double[bots1.size()][bots2.size()]; for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { int m=0; for(PhysicalGameState pgs:maps) { for (int i = 0; i < iterations; i++) { //cloning just in case an AI has a memory leak //by using a clone, it is discarded, along with the leaked memory, //after each game, rather than accumulating //over several games AI ai1 = bots1.get(ai1_idx).clone(); AI ai2 = bots2.get(ai2_idx).clone(); long lastTimeActionIssued = 0; ai1.reset(); ai2.reset(); GameState gs = new GameState(pgs.clone(),utt); JFrame w = null; if (visualize) w = PhysicalGameStatePanel.newVisualizer(gs, 600, 600); out.println("MATCH UP: " + ai1+ " vs " + ai2); System.gc(); boolean gameover = false; Trace trace = null; TraceEntry te; if(saveTrace){ trace = new Trace(utt); te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); } do { if (PRINT_BRANCHING_AT_EACH_MOVE) { String bf1 = (gs.canExecuteAnyAction(0) ? ""+BranchingCalculatorWithTimeOut.branching(gs, 0, BRANCHING_CALCULATION_TIMEOUT):"-"); String bf2 = (gs.canExecuteAnyAction(1) ? ""+BranchingCalculatorWithTimeOut.branching(gs, 1, BRANCHING_CALCULATION_TIMEOUT):"-"); if (!bf1.equals("-") || !bf2.equals("-")) { out.print("branching\t" + bf1 + "\t" + bf2 + "\n"); } } PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); if (saveTrace && (!pa1.isEmpty() || !pa2.isEmpty())) { te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } if (gs.issueSafe(pa1)) lastTimeActionIssued = gs.getTime(); if (gs.issueSafe(pa2)) lastTimeActionIssued = gs.getTime(); gameover = gs.cycle(); if (w!=null){ w.repaint(); try { Thread.sleep(1); // give time to the window to repaint } catch (Exception e) { e.printStackTrace(); } } } while (!gameover && (gs.getTime() < max_cycles) && (gs.getTime() - lastTimeActionIssued < max_inactive_cycles)); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); if(saveTrace){ te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); XMLWriter xml; ZipOutputStream zip = null; String filename=ai1.toString()+"Vs"+ai2.toString()+"-"+m+"-"+i; filename=filename.replace("/", ""); filename=filename.replace(")", ""); filename=filename.replace("(", ""); filename=traceDir+"/"+filename; if(saveZip){ zip=new ZipOutputStream(new FileOutputStream(filename+".zip")); zip.putNextEntry(new ZipEntry("game.xml")); xml = new XMLWriter(new OutputStreamWriter(zip)); }else{ xml = new XMLWriter(new FileWriter(filename+".xml")); } trace.toxml(xml); xml.flush(); if(saveZip){ zip.closeEntry(); zip.close(); } } if (w!=null) w.dispose(); int winner = gs.winner(); out.println("Winner: " + winner + " in " + gs.getTime() + " cycles"); out.println(ai1 + " : " + ai1.statisticsString()); out.println(ai2 + " : " + ai2.statisticsString()); out.flush(); if (winner == -1) { ties[ai1_idx][ai2_idx]++; tie_time[ai1_idx][ai2_idx]+=gs.getTime(); } else if (winner == 0) { wins[ai1_idx][ai2_idx]++; win_time[ai1_idx][ai2_idx]+=gs.getTime(); } else if (winner == 1) { loses[ai1_idx][ai2_idx]++; lose_time[ai1_idx][ai2_idx]+=gs.getTime(); } } m++; } } } out.println("Notice that the results below are only from the perspective of the 'bots1' list."); out.println("If you want a symmetric experimentation, use the 'Experimenter' class"); out.println("Wins: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { out.print(wins[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Ties: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { out.print(ties[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Loses: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { out.print(loses[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Win average time: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { if (wins[ai1_idx][ai2_idx]>0) { out.print((win_time[ai1_idx][ai2_idx]/wins[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Tie average time: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { if (ties[ai1_idx][ai2_idx]>0) { out.print((tie_time[ai1_idx][ai2_idx]/ties[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Lose average time: "); for (int ai1_idx = 0; ai1_idx < bots1.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots2.size(); ai2_idx++) { if (loses[ai1_idx][ai2_idx]>0) { out.print((lose_time[ai1_idx][ai2_idx]/loses[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.flush(); } }
11,601
45.223108
283
java
MicroRTS
MicroRTS-master/src/tests/GameVisualSimulationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.*; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.BFSPathFinding; import gui.PhysicalGameStatePanel; import javax.swing.JFrame; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author santi */ public class GameVisualSimulationTest { public static void main(String[] args) throws Exception { UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); // PhysicalGameState pgs = MapGenerator.basesWorkers8x8Obstacle(); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; int PERIOD = 20; boolean gameover = false; AI ai1 = new WorkerRush(utt, new BFSPathFinding()); AI ai2 = new RandomBiasedAI(); JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640,false,PhysicalGameStatePanel.COLORSCHEME_BLACK); // JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640,false,PhysicalGameStatePanel.COLORSCHEME_WHITE); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do{ if (System.currentTimeMillis()>=nextTimeToUpdate) { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); w.repaint(); nextTimeToUpdate+=PERIOD; } else { try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); System.out.println("Game Over"); } }
2,094
30.742424
117
java
MicroRTS
MicroRTS-master/src/tests/JNIBotClient.java
package tests; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.StringWriter; import java.io.Writer; import java.nio.file.Paths; import ai.core.AI; import ai.jni.Response; import ai.reward.RewardFunctionInterface; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.TraceEntry; import rts.units.UnitTypeTable; /** * Instances of this class each let us run a single environment (or sequence * of them, if we reset() in between) between two players. * * In this client, it is assumed that actions are selected by Java-based bots * for **both** players. See JNIGridnetClient.java for a client where one * player is externally controlled, and JNIGridnetClientSelfPlay.java for one * where both players are externally controlled. * * @author santi and costa */ public class JNIBotClient { PhysicalGameStateJFrame w; public AI ai1; public AI ai2; PhysicalGameState pgs; GameState gs; UnitTypeTable utt; boolean partialObs; public RewardFunctionInterface[] rfs; public String mapPath; String micrortsPath; boolean gameover = false; boolean layerJSON = true; public int renderTheme = PhysicalGameStatePanel.COLORSCHEME_WHITE; // storage double[] rewards; boolean[] dones; Response response; PlayerAction pa1; PlayerAction pa2; /** * * @param a_rfs Reward functions we want to use to compute rewards at every step. * @param a_micrortsPath Path for the microrts root directory (with Java code and maps). * @param a_mapPath Path (under microrts root dir) for map to load. * @param a_ai1 * @param a_ai2 * @param a_utt * @param partial_obs * @throws Exception */ public JNIBotClient(RewardFunctionInterface[] a_rfs, String a_micrortsPath, String a_mapPath, AI a_ai1, AI a_ai2, UnitTypeTable a_utt, boolean partial_obs) throws Exception{ micrortsPath = a_micrortsPath; mapPath = a_mapPath; rfs = a_rfs; utt = a_utt; partialObs = partial_obs; ai1 = a_ai1; ai2 = a_ai2; if (ai1 == null || ai2 == null) { throw new Exception("no ai1 or ai2 was chosen"); } if (micrortsPath.length() != 0) { this.mapPath = Paths.get(micrortsPath, mapPath).toString(); } pgs = PhysicalGameState.load(mapPath, utt); // initialize storage rewards = new double[rfs.length]; dones = new boolean[rfs.length]; response = new Response(null, null, null, null); } public byte[] render(boolean returnPixels) throws Exception { if (w==null) { w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, false, null, renderTheme); } w.setStateCloning(gs); w.repaint(); if (!returnPixels) { return null; } BufferedImage image = new BufferedImage(w.getWidth(), w.getHeight(), BufferedImage.TYPE_3BYTE_BGR); w.paint(image.getGraphics()); WritableRaster raster = image .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); return data.getData(); } public Response gameStep(int player) throws Exception { pa1 = ai1.getAction(player, gs); pa2 = ai2.getAction(1 - player, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); // simulate: gameover = gs.cycle(); if (gameover) { ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); } for (int i = 0; i < rewards.length; i++) { rfs[i].computeReward(player, 1 - player, te, gs); dones[i] = rfs[i].isDone(); rewards[i] = rfs[i].getReward(); } response.set( null, rewards, dones, "{}"); return response; } public String sendUTT() throws Exception { Writer w = new StringWriter(); utt.toJSON(w); return w.toString(); // now it works fine } /** * Resets the environment. * @param player This parameter is unused. * @return Response after reset. * @throws Exception */ public Response reset(int player) throws Exception { ai1 = ai1.clone(); ai1.reset(); ai2 = ai2.clone(); ai2.reset(); pgs = PhysicalGameState.load(mapPath, utt); gs = new GameState(pgs, utt); for (int i = 0; i < rewards.length; i++) { rewards[i] = 0; dones[i] = false; } response.set( null, rewards, dones, "{}"); return response; } public void close() throws Exception { if (w!=null) { w.dispose(); } } }
5,150
28.434286
177
java
MicroRTS
MicroRTS-master/src/tests/JNIGridnetClient.java
package tests; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.StringWriter; import java.io.Writer; import java.nio.file.Paths; import java.util.Arrays; import ai.core.AI; import ai.jni.JNIAI; import ai.jni.JNIInterface; import ai.jni.Response; import ai.reward.RewardFunctionInterface; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.TraceEntry; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * Instances of this class each let us run a single environment (or sequence * of them, if we reset() in between) between two players. * * In this client, it is assumed that actions are selected by external code for * **one** player, where the opponent is controlled directly by a Java-based AI. * See JNIGridnetClientSelfPlay.java for a client where both players are * externally controlled. * * @author santi and costa */ public class JNIGridnetClient { // Settings public RewardFunctionInterface[] rfs; String micrortsPath; public String mapPath; public AI ai2; UnitTypeTable utt; public boolean partialObs = false; // Internal State public PhysicalGameState pgs; public GameState gs; public GameState player1gs, player2gs; boolean gameover = false; boolean layerJSON = true; public int renderTheme = PhysicalGameStatePanel.COLORSCHEME_WHITE; public int maxAttackRadius; PhysicalGameStateJFrame w; public JNIInterface ai1; // Storage // [Y][X][ // 0: do we own a unit without action assignment here? |-- 1 // // 1: can we do a no-op action? | // 2: can we do a move action? | // 3: can we do a harvest action? |-- 6 action types // 4: can we do a return to base with resources action? | // 5: can we do a produce unit action? | // 6: can we do an attack action | // // 7: can we move up/north? | // 8: can we move right/east? |-- 4 move directions // 9: can we move down/south? | // 10: can we move left/west? | // // 11: can we harvest up/north? | // 12: can we harvest right/east? |-- 4 harvest directions // 13: can we harvest down/south? | // 14: can we harvest left/west? | // // 15: can we return resources to base up/north? | // 16: can we return resources to base right/east? |-- 4 return resources to base directions // 17: can we return resources to base down/south? | // 18: can we return resources to base left/west? | // // 19: can we produce unit up/north? | // 20: can we produce unit right/east? |-- 4 produce unit directions // 21: can we produce unit down/south? | // 22: can we produce unit left/west? | // // 23: can we produce a unit of type 0? | // 24: can we produce a unit of type 1? |-- k (= 7) unit types to produce // ...: .... | // 29: can we produce a unit of type 6? | // // 30: can we attack relative position at ...? | // 31: can we attack relative position at ...? |-- (maxAttackRange)^2 relative attack locations // ...: ... | // ] int[][][] masks; double[] rewards; boolean[] dones; Response response; PlayerAction pa1; PlayerAction pa2; /** * * @param a_rfs Reward functions we want to use to compute rewards at every step. * @param a_micrortsPath Path for the microrts root directory (with Java code and maps). * @param a_mapPath Path (under microrts root dir) for map to load. * @param a_ai2 The AI object that should select actions for the opponent (i.e., for the * player that will not be controlled by external/JNI/Python code) * @param a_utt * @param partial_obs * @throws Exception */ public JNIGridnetClient(RewardFunctionInterface[] a_rfs, String a_micrortsPath, String a_mapPath, AI a_ai2, UnitTypeTable a_utt, boolean partial_obs) throws Exception{ micrortsPath = a_micrortsPath; mapPath = a_mapPath; rfs = a_rfs; utt = a_utt; partialObs = partial_obs; maxAttackRadius = utt.getMaxAttackRange() * 2 + 1; ai1 = new JNIAI(100, 0, utt); ai2 = a_ai2; if (ai2 == null) { throw new Exception("no ai2 was chosen"); } if (micrortsPath.length() != 0) { this.mapPath = Paths.get(micrortsPath, mapPath).toString(); } pgs = PhysicalGameState.load(mapPath, utt); // initialize storage masks = new int[pgs.getHeight()][pgs.getWidth()][1+6+4+4+4+4+utt.getUnitTypes().size()+maxAttackRadius*maxAttackRadius]; rewards = new double[rfs.length]; dones = new boolean[rfs.length]; response = new Response(null, null, null, null); } public byte[] render(boolean returnPixels) throws Exception { if (w==null) { w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, partialObs, null, renderTheme); } w.setStateCloning(gs); w.repaint(); if (!returnPixels) { return null; } BufferedImage image = new BufferedImage(w.getWidth(), w.getHeight(), BufferedImage.TYPE_3BYTE_BGR); w.paint(image.getGraphics()); WritableRaster raster = image .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); return data.getData(); } public Response gameStep(int[][] action, int player) throws Exception { if (partialObs) { player1gs = new PartiallyObservableGameState(gs, player); player2gs = new PartiallyObservableGameState(gs, 1 - player); } else { player1gs = gs; player2gs = gs; } pa1 = ai1.getAction(player, player1gs, action); pa2 = ai2.getAction(1 - player, player2gs); gs.issueSafe(pa1); gs.issueSafe(pa2); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); // simulate: gameover = gs.cycle(); if (gameover) { // ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); } for (int i = 0; i < rewards.length; i++) { rfs[i].computeReward(player, 1 - player, te, gs); dones[i] = rfs[i].isDone(); rewards[i] = rfs[i].getReward(); } response.set( ai1.getObservation(player, player1gs), rewards, dones, ai1.computeInfo(player, player2gs)); return response; } /** * @param player * @return Legal actions mask for given player. * @throws Exception */ public int[][][] getMasks(int player) throws Exception { for (int i = 0; i < masks.length; i++) { for (int j = 0; j < masks[0].length; j++) { Arrays.fill(masks[i][j], 0); } } for (Unit u: pgs.getUnits()) { if (u.getPlayer() == player && gs.getActionAssignment(u) == null) { masks[u.getY()][u.getX()][0] = 1; UnitAction.getValidActionArray(u, gs, utt, masks[u.getY()][u.getX()], maxAttackRadius, 1); } } return masks; } /** * @return String representation (in JSON format) of the Unit Type Table * @throws Exception */ public String sendUTT() throws Exception { Writer w = new StringWriter(); utt.toJSON(w); return w.toString(); // now it works fine } public Response reset(int player) throws Exception { ai1.reset(); ai2 = ai2.clone(); ai2.reset(); pgs = PhysicalGameState.load(mapPath, utt); gs = new GameState(pgs, utt); if (partialObs) { player1gs = new PartiallyObservableGameState(gs, player); } else { player1gs = gs; } for (int i = 0; i < rewards.length; i++) { rewards[i] = 0; dones[i] = false; } response.set( ai1.getObservation(player, player1gs), rewards, dones, "{}"); return response; } public void close() throws Exception { if (w!=null) { w.dispose(); } } }
8,741
32.883721
171
java
MicroRTS
MicroRTS-master/src/tests/JNIGridnetClientSelfPlay.java
package tests; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.StringWriter; import java.io.Writer; import java.nio.file.Paths; import java.util.Arrays; import ai.core.AI; import ai.jni.JNIAI; import ai.jni.JNIInterface; import ai.jni.Response; import ai.reward.RewardFunctionInterface; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.TraceEntry; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * Instances of this class each let us run a single environment (or sequence * of them, if we reset() in between) between two players. * * In this client, it is assumed that actions are selected by external code for * **both** players. See JNIGridnetClient.java for a client where only one * player is externally controlled, and the other is a plain Java AI. * * @author santi and costa */ public class JNIGridnetClientSelfPlay { // Settings public RewardFunctionInterface[] rfs; String micrortsPath; public String mapPath; public AI ai2; UnitTypeTable utt; boolean partialObs = false; // Internal State PhysicalGameStateJFrame w; public JNIInterface[] ais = new JNIInterface[2]; // These AIs won't actually play: just convert action formats for us public PhysicalGameState pgs; public GameState gs; public GameState[] playergs = new GameState[2]; boolean gameover = false; boolean layerJSON = true; public int renderTheme = PhysicalGameStatePanel.COLORSCHEME_WHITE; public int maxAttackRadius; public int numPlayers = 2; // Storage // [player][Y][X][ // 0: do we own a unit without action assignment here? |-- 1 // // 1: can we do a no-op action? | // 2: can we do a move action? | // 3: can we do a harvest action? |-- 6 action types // 4: can we do a return to base with resources action? | // 5: can we do a produce unit action? | // 6: can we do an attack action | // // 7: can we move up/north? | // 8: can we move right/east? |-- 4 move directions // 9: can we move down/south? | // 10: can we move left/west? | // // 11: can we harvest up/north? | // 12: can we harvest right/east? |-- 4 harvest directions // 13: can we harvest down/south? | // 14: can we harvest left/west? | // // 15: can we return resources to base up/north? | // 16: can we return resources to base right/east? |-- 4 return resources to base directions // 17: can we return resources to base down/south? | // 18: can we return resources to base left/west? | // // 19: can we produce unit up/north? | // 20: can we produce unit right/east? |-- 4 produce unit directions // 21: can we produce unit down/south? | // 22: can we produce unit left/west? | // // 23: can we produce a unit of type 0? | // 24: can we produce a unit of type 1? |-- k (= 7) unit types to produce // ...: .... | // 29: can we produce a unit of type 6? | // // 30: can we attack relative position at ...? | // 31: can we attack relative position at ...? |-- (maxAttackRange)^2 relative attack locations // ...: ... | // ] int[][][][] masks = new int[2][][][]; double[][] rewards = new double[2][]; boolean[][] dones = new boolean[2][]; Response[] response = new Response[2]; PlayerAction[] pas = new PlayerAction[2]; /** * * @param a_rfs Reward functions we want to use to compute rewards at every step. * @param a_micrortsPath Path for the microrts root directory (with Java code and maps). * @param a_mapPath Path (under microrts root dir) for map to load. * @param a_utt * @param partial_obs * @throws Exception */ public JNIGridnetClientSelfPlay(RewardFunctionInterface[] a_rfs, String a_micrortsPath, String a_mapPath, UnitTypeTable a_utt, boolean partial_obs) throws Exception{ micrortsPath = a_micrortsPath; mapPath = a_mapPath; rfs = a_rfs; utt = a_utt; partialObs = partial_obs; maxAttackRadius = utt.getMaxAttackRange() * 2 + 1; if (micrortsPath.length() != 0) { this.mapPath = Paths.get(micrortsPath, mapPath).toString(); } pgs = PhysicalGameState.load(mapPath, utt); // initialize storage for (int i = 0; i < numPlayers; i++) { ais[i] = new JNIAI(100, 0, utt); masks[i] = new int[pgs.getHeight()][pgs.getWidth()][1+6+4+4+4+4+utt.getUnitTypes().size()+maxAttackRadius*maxAttackRadius]; rewards[i] = new double[rfs.length]; dones[i] = new boolean[rfs.length]; response[i] = new Response(null, null, null, null); } } public byte[] render(boolean returnPixels) throws Exception { if (w==null) { w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, partialObs, null, renderTheme); } w.setStateCloning(gs); w.repaint(); if (!returnPixels) { return null; } BufferedImage image = new BufferedImage(w.getWidth(), w.getHeight(), BufferedImage.TYPE_3BYTE_BGR); w.paint(image.getGraphics()); WritableRaster raster = image .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); return data.getData(); } public void gameStep(int[][] action1, int[][] action2) throws Exception { // FIXME do we really need to create this TraceEntry object at all? TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); for (int i = 0; i < numPlayers; i++) { playergs[i] = gs; if (partialObs) { playergs[i] = new PartiallyObservableGameState(gs, i); } pas[i] = i == 0 ? ais[i].getAction(i, playergs[0], action1) : ais[i].getAction(i, playergs[1], action2); gs.issueSafe(pas[i]); te.addPlayerAction(pas[i].clone()); } // simulate: gameover = gs.cycle(); if (gameover) { // ai1.gameOver(gs.winner()); // ai2.gameOver(gs.winner()); } for (int i = 0; i < numPlayers; i++) { for (int j = 0; j < rfs.length; j++) { rfs[j].computeReward(i, 1 - i, te, gs); rewards[i][j] = rfs[j].getReward(); dones[i][j] = rfs[j].isDone(); } response[i].set( ais[i].getObservation(i, playergs[i]), rewards[i], dones[i], "{}"); } } /** * @param player * @return Legal actions mask for given player. * @throws Exception */ public int[][][] getMasks(int player) throws Exception { for (int i = 0; i < masks[0].length; i++) { for (int j = 0; j < masks[0][0].length; j++) { Arrays.fill(masks[player][i][j], 0); } } for (Unit u: pgs.getUnits()) { if (u.getPlayer() == player && gs.getActionAssignment(u) == null) { masks[player][u.getY()][u.getX()][0] = 1; UnitAction.getValidActionArray(u, gs, utt, masks[player][u.getY()][u.getX()], maxAttackRadius, 1); } } return masks[player]; } /** * @return String representation (in JSON format) of the Unit Type Table * @throws Exception */ public String sendUTT() throws Exception { Writer w = new StringWriter(); utt.toJSON(w); return w.toString(); // now it works fine } public void reset() throws Exception { pgs = PhysicalGameState.load(mapPath, utt); gs = new GameState(pgs, utt); for (int i = 0; i < numPlayers; i++) { playergs[i] = gs; if (partialObs) { playergs[i] = new PartiallyObservableGameState(gs, i); } ais[i].reset(); for (int j = 0; j < rewards.length; j++) { rewards[i][j] = 0; dones[i][j] = false; } response[i].set( ais[i].getObservation(i, playergs[i]), rewards[i], dones[i], "{}"); } // return response; } public Response getResponse(int player) { return response[player]; } public void close() throws Exception { if (w!=null) { w.dispose(); } } }
8,940
34.062745
169
java
MicroRTS
MicroRTS-master/src/tests/JNIGridnetVecClient.java
package tests; import ai.PassiveAI; import ai.core.AI; import ai.jni.Response; import ai.jni.Responses; import ai.reward.RewardFunctionInterface; import rts.units.UnitTypeTable; /** * A vectorized client which lets us run multiple difference environments in * parallel (although, on the Java-side of the implementation, there is no * actual parallelization and input actions are simply processed sequentially). * * @author santi and costa */ public class JNIGridnetVecClient { /** Clients of 1 Python/JNI agent vs. 1 Java bot */ public JNIGridnetClient[] clients; /** Clients of 1 Python/JNI agent vs. 1 Python/JNI agent */ public JNIGridnetClientSelfPlay[] selfPlayClients; /** Clients of 1 Java bot vs. 1 Java bot */ public JNIBotClient[] botClients; public int maxSteps; public int[] envSteps; public RewardFunctionInterface[] rfs; public UnitTypeTable utt; boolean partialObs = false; public String[] mapPaths; // Storage // [player+environment index][Y][X][ // 0: do we own a unit without action assignment here? |-- 1 // // 1: can we do a no-op action? | // 2: can we do a move action? | // 3: can we do a harvest action? |-- 6 action types // 4: can we do a return to base with resources action? | // 5: can we do a produce unit action? | // 6: can we do an attack action | // // 7: can we move up/north? | // 8: can we move right/east? |-- 4 move directions // 9: can we move down/south? | // 10: can we move left/west? | // // 11: can we harvest up/north? | // 12: can we harvest right/east? |-- 4 harvest directions // 13: can we harvest down/south? | // 14: can we harvest left/west? | // // 15: can we return resources to base up/north? | // 16: can we return resources to base right/east? |-- 4 return resources to base directions // 17: can we return resources to base down/south? | // 18: can we return resources to base left/west? | // // 19: can we produce unit up/north? | // 20: can we produce unit right/east? |-- 4 produce unit directions // 21: can we produce unit down/south? | // 22: can we produce unit left/west? | // // 23: can we produce a unit of type 0? | // 24: can we produce a unit of type 1? |-- k (= 7) unit types to produce // ...: .... | // 29: can we produce a unit of type 6? | // // 30: can we attack relative position at ...? | // 31: can we attack relative position at ...? |-- (maxAttackRange)^2 relative attack locations // ...: ... | // ] int[][][][] masks; int[][][][] observation; double[][] reward; boolean[][] done; Response[] rs; Responses responses; double[] terminalReward1; boolean[] terminalDone1; double[] terminalReward2; boolean[] terminalDone2; /** * * @param a_num_selfplayenvs Should be a multiple of 2. The number of * self-play environments (JNI vs. JNI) that will be run is half of this, * since each environment facilitates two agents. * @param a_num_envs The number of environments in which a JNI agent plays * against a Java bot. * @param a_max_steps Maximum duration (in frames) per environment. * @param a_rfs Reward functions we want to use to compute rewards at every step. * @param a_micrortsPath Path for the microrts root directory (with Java code and maps). * @param a_mapPaths Paths (under microrts root dir) for maps to load. The first * a_num_selfplayenvs entries are used for self-play clients, although only those * at indices 0, 2, 4, ... are used (indices 1, 3, ... remain unused). The * next a_num_envs entries are used for clients of JNI agents vs. Java bots. * @param a_ai2s Java bots to use in the JNI agent vs. Java bot environments. * @param a_utt * @param partial_obs * @throws Exception */ public JNIGridnetVecClient(int a_num_selfplayenvs, int a_num_envs, int a_max_steps, RewardFunctionInterface[] a_rfs, String a_micrortsPath, String[] a_mapPaths, AI[] a_ai2s, UnitTypeTable a_utt, boolean partial_obs) throws Exception { maxSteps = a_max_steps; utt = a_utt; rfs = a_rfs; partialObs = partial_obs; mapPaths = a_mapPaths; // initialize clients envSteps = new int[a_num_selfplayenvs + a_num_envs]; selfPlayClients = new JNIGridnetClientSelfPlay[a_num_selfplayenvs/2]; for (int i = 0; i < selfPlayClients.length; i++) { selfPlayClients[i] = new JNIGridnetClientSelfPlay(a_rfs, a_micrortsPath, mapPaths[i*2], a_utt, partialObs); } clients = new JNIGridnetClient[a_num_envs]; for (int i = 0; i < clients.length; i++) { clients[i] = new JNIGridnetClient(a_rfs, a_micrortsPath, mapPaths[a_num_selfplayenvs+i], a_ai2s[i], a_utt, partialObs); } // initialize storage Response r = new JNIGridnetClient(a_rfs, a_micrortsPath, mapPaths[0], new PassiveAI(a_utt), a_utt, partialObs).reset(0); int s1 = a_num_selfplayenvs + a_num_envs; int s2 = r.observation.length; int s3 = r.observation[0].length; int s4 = r.observation[0][0].length; masks = new int[s1][][][]; observation = new int[s1][s2][s3][s4]; reward = new double[s1][rfs.length]; done = new boolean[s1][rfs.length]; terminalReward1 = new double[rfs.length]; terminalDone1 = new boolean[rfs.length]; terminalReward2 = new double[rfs.length]; terminalDone2 = new boolean[rfs.length]; responses = new Responses(null, null, null); rs = new Response[s1]; } /** * Constructor for Java-bot-only environments. * * @param a_max_steps * @param a_rfs * @param a_micrortsPath * @param a_mapPaths * @param a_ai1s * @param a_ai2s * @param a_utt * @param partial_obs * @throws Exception */ public JNIGridnetVecClient(int a_max_steps, RewardFunctionInterface[] a_rfs, String a_micrortsPath, String[] a_mapPaths, AI[] a_ai1s, AI[] a_ai2s, UnitTypeTable a_utt, boolean partial_obs) throws Exception { maxSteps = a_max_steps; utt = a_utt; rfs = a_rfs; partialObs = partial_obs; mapPaths = a_mapPaths; // initialize clients botClients = new JNIBotClient[a_ai2s.length]; for (int i = 0; i < botClients.length; i++) { botClients[i] = new JNIBotClient(a_rfs, a_micrortsPath, mapPaths[i], a_ai1s[i], a_ai2s[i], a_utt, partialObs); } responses = new Responses(null, null, null); rs = new Response[a_ai2s.length]; reward = new double[a_ai2s.length][rfs.length]; done = new boolean[a_ai2s.length][rfs.length]; envSteps = new int[a_ai2s.length]; terminalReward1 = new double[rfs.length]; terminalDone1 = new boolean[rfs.length]; } public Responses reset(int[] players) throws Exception { if (botClients != null) { for (int i = 0; i < botClients.length; i++) { rs[i] = botClients[i].reset(players[i]); } for (int i = 0; i < rs.length; i++) { // observation[i] = rs[i].observation; reward[i] = rs[i].reward; done[i] = rs[i].done; } responses.set(null, reward, done); return responses; } for (int i = 0; i < selfPlayClients.length; i++) { selfPlayClients[i].reset(); rs[i*2] = selfPlayClients[i].getResponse(0); rs[i*2+1] = selfPlayClients[i].getResponse(1); } for (int i = selfPlayClients.length*2; i < players.length; i++) { rs[i] = clients[i-selfPlayClients.length*2].reset(players[i]); } for (int i = 0; i < rs.length; i++) { observation[i] = rs[i].observation; reward[i] = rs[i].reward; done[i] = rs[i].done; } responses.set(observation, reward, done); return responses; } public Responses gameStep(int[][][] action, int[] players) throws Exception { if (botClients != null) { for (int i = 0; i < botClients.length; i++) { rs[i] = botClients[i].gameStep(players[i]); envSteps[i] += 1; if (rs[i].done[0] || envSteps[i] >= maxSteps) { for (int j = 0; j < terminalReward1.length; j++) { terminalReward1[j] = rs[i].reward[j]; terminalDone1[j] = rs[i].done[j]; } botClients[i].reset(players[i]); for (int j = 0; j < terminalReward1.length; j++) { rs[i].reward[j] = terminalReward1[j]; rs[i].done[j] = terminalDone1[j]; } rs[i].done[0] = true; envSteps[i] =0; } } for (int i = 0; i < rs.length; i++) { // observation[i] = rs[i].observation; reward[i] = rs[i].reward; done[i] = rs[i].done; } responses.set(null, reward, done); return responses; } for (int i = 0; i < selfPlayClients.length; i++) { selfPlayClients[i].gameStep(action[i*2], action[i*2+1]); rs[i*2] = selfPlayClients[i].getResponse(0); rs[i*2+1] = selfPlayClients[i].getResponse(1); envSteps[i*2] += 1; envSteps[i*2+1] += 1; if (rs[i*2].done[0] || envSteps[i*2] >= maxSteps) { for (int j = 0; j < terminalReward1.length; j++) { terminalReward1[j] = rs[i*2].reward[j]; terminalDone1[j] = rs[i*2].done[j]; terminalReward2[j] = rs[i*2+1].reward[j]; terminalDone2[j] = rs[i*2+1].done[j]; } selfPlayClients[i].reset(); for (int j = 0; j < terminalReward1.length; j++) { rs[i*2].reward[j] = terminalReward1[j]; rs[i*2].done[j] = terminalDone1[j]; rs[i*2+1].reward[j] = terminalReward2[j]; rs[i*2+1].done[j] = terminalDone2[j]; } rs[i*2].done[0] = true; rs[i*2+1].done[0] = true; envSteps[i*2] =0; envSteps[i*2+1] =0; } } for (int i = selfPlayClients.length*2; i < players.length; i++) { envSteps[i] += 1; rs[i] = clients[i-selfPlayClients.length*2].gameStep(action[i], players[i]); if (rs[i].done[0] || envSteps[i] >= maxSteps) { // TRICKY: note that `clients` already resets the shared `observation` // so we need to set the old reward and done to this response for (int j = 0; j < rs[i].reward.length; j++) { terminalReward1[j] = rs[i].reward[j]; terminalDone1[j] = rs[i].done[j]; } clients[i-selfPlayClients.length*2].reset(players[i]); for (int j = 0; j < rs[i].reward.length; j++) { rs[i].reward[j] = terminalReward1[j]; rs[i].done[j] = terminalDone1[j]; } rs[i].done[0] = true; envSteps[i] = 0; } } for (int i = 0; i < rs.length; i++) { observation[i] = rs[i].observation; reward[i] = rs[i].reward; done[i] = rs[i].done; } responses.set(observation, reward, done); return responses; } /** * @param player * @return Legal actions masks. For self-play clients, returns masks * for both players. For the other clients, only returns masks for * the given player. * @throws Exception */ public int[][][][] getMasks(int player) throws Exception { for (int i = 0; i < selfPlayClients.length; i++) { masks[i*2] = selfPlayClients[i].getMasks(0); masks[i*2+1] = selfPlayClients[i].getMasks(1); } for (int i = selfPlayClients.length*2; i < masks.length; i++) { masks[i] = clients[i-selfPlayClients.length*2].getMasks(player); } return masks; } public void close() throws Exception { if (clients != null) { for (JNIGridnetClient client : clients) { client.close(); } } if (selfPlayClients != null) { for (JNIGridnetClientSelfPlay client : selfPlayClients) { client.close(); } } if (botClients != null) { for (int i = 0; i < botClients.length; i++) { botClients[i].close(); } } } }
13,297
38.577381
165
java
MicroRTS
MicroRTS-master/src/tests/LMCTest.java
/* * This class was contributed by: Antonin Komenda, Alexander Shleyfman and Carmel Domshlak */ package tests; import ai.core.AI; import ai.RandomBiasedAI; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.naivemcts.NaiveMCTS; import ai.montecarlo.lsi.LSI; import ai.montecarlo.lsi.Sampling.AgentOrderingType; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import java.io.OutputStreamWriter; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; import util.XMLWriter; public class LMCTest { public static void main(String args[]) throws Exception { String scenarioFileName = "maps/8x8/basesWorkers8x8.xml"; UnitTypeTable utt = new UnitTypeTable(); // original game (NOOP length = move length) int MAX_GAME_CYCLES = 3000; // game time int SIMULATION_BUDGET = 1000; // count per decision int LOOKAHEAD_CYCLES = 100; // game time AI simulationAi = new RandomBiasedAI(); EvaluationFunction evalFunction = new SimpleSqrtEvaluationFunction3(); // AI ai1 = new RandomAI(); // AI ai1 = new RandomBiasedAI(); // AI ai1 = new WorkerRush(utt, new AStarPathFinding()); // AI ai1 = new LightRush(utt, new AStarPathFinding()); // AI ai1 = new RangedRush(utt, new GreedyPathFinding()); // AI ai1 = new NaiveMonteCarlo(SIMULATION_COUNT, LOOKAHEAD_TIME, 0.33f, 0.2f, simulationAi, evalFunction); // AI ai1 = new LinearMonteCarlo(SIMULATION_COUNT, LOOKAHEAD_TIME, simulationAi, evalFunction); // AI ai1 = new LocalLinearMonteCarlo(SIMULATION_COUNT, LOOKAHEAD_TIME, simulationAi, evalFunction); AI ai1 = new LSI(SIMULATION_BUDGET, LOOKAHEAD_CYCLES, 0.25, LSI.EstimateType.RANDOM_TAIL, LSI.EstimateReuseType.ALL, LSI.GenerateType.PER_AGENT, AgentOrderingType.ENTROPY, LSI.EvaluateType.HALVING, false, LSI.RelaxationType.NONE, 2, false, simulationAi, evalFunction); // HumanAI ai2 = new HumanAI(); // AI ai2 = new RandomBiasedAI(); // AI ai2 = new WorkerRush(utt, new AStarPathFinding()); // AI ai2 = new LightRush(utt, new AStarPathFinding()); // AI ai2 = new RangedRush(utt, new AStarPathFinding()); // by setting "MAX_DEPTH = 1" in the next bot, this effectively makes it Monte Carlo search, instead of Monte Carlo Tree Search AI ai2 = new NaiveMCTS(-1, SIMULATION_BUDGET, LOOKAHEAD_CYCLES, 1, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), evalFunction, true); // AI ai2 = new GenerateEvaluateMonteCarlo(SIMULATION_BUDGET, LOOKAHEAD_CYCLES, // 0.25, EstimateType.RANDOM_TAIL, EstimateReuseType.ALL, // GenerateType.PER_AGENT, AgentOrderingType.ENTROPY, // EvaluateType.HALVING, true, // RelaxationType.NONE, 2, // false, // simulationAi, evalFunction); PhysicalGameState pgs = PhysicalGameState.load(scenarioFileName, utt); GameState gs = new GameState(pgs, utt); XMLWriter xml = new XMLWriter(new OutputStreamWriter(System.out)); pgs.toxml(xml); xml.flush(); PhysicalGameStateJFrame w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, evalFunction); w.repaint(); // for HumanAI //ai2.registerUI(w, 1); boolean gameover = false; do { long timeMillis = System.currentTimeMillis(); PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); timeMillis = System.currentTimeMillis() - timeMillis; if (timeMillis < 50) { Thread.sleep(50 - timeMillis); } // simulate: gameover = gs.cycle(); w.repaint(); } while(!gameover && gs.getTime() < MAX_GAME_CYCLES); System.out.println("Game Over"); String rec = ""; rec += scenarioFileName + "\t"; rec += MAX_GAME_CYCLES + "\t"; rec += SIMULATION_BUDGET + "\t"; rec += LOOKAHEAD_CYCLES + "\t"; rec += simulationAi.getClass().getSimpleName() + "\t"; rec += evalFunction.getClass().getSimpleName() + "\t"; rec += ai1.getClass().getSimpleName() + "\t"; rec += ai2.getClass().getSimpleName() + "\t"; rec += gs.winner() + "\t"; rec += evalFunction.evaluate(0, 1, gs) + "\t"; rec += ai1.statisticsString() + "\t"; rec += ai2.statisticsString() + "\t"; System.out.println(rec); } }
4,747
39.237288
137
java
MicroRTS
MicroRTS-master/src/tests/MapGenerator.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import java.io.FileWriter; import java.io.IOException; import rts.PhysicalGameState; import rts.Player; import rts.units.*; import util.XMLWriter; /** * * @author santi * * This class contains some functions to create basic initial maps for testing. * */ public class MapGenerator { static UnitTypeTable utt; UnitType resourceType; UnitType baseType; UnitType barracksType; UnitType workerType; UnitType lightType; UnitType heavyType; UnitType rangedType; public MapGenerator(UnitTypeTable a_utt) { utt = a_utt; resourceType = utt.getUnitType("Resource"); baseType = utt.getUnitType("Base"); barracksType = utt.getUnitType("Barracks"); workerType = utt.getUnitType("Worker"); lightType = utt.getUnitType("Light"); heavyType = utt.getUnitType("Heavy"); rangedType = utt.getUnitType("Ranged"); } public static void main(String args[]) throws IOException { MapGenerator mg = new MapGenerator(new UnitTypeTable()); // Complete game maps: XMLWriter xml = new XMLWriter(new FileWriter("maps/8x8/bases8x8.xml")); mg.bases8x8().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/basesWorkers8x8.xml")); mg.basesWorkers8x8().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/basesWorkers8x8Obstacle.xml")); mg.basesWorkers8x8Obstacle().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/12x12/basesWorkers12x12.xml")); mg.basesWorkers12x12().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/12x12/complexBasesWorkers12x12.xml")); mg.complexBasesWorkers12x12().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/16x16/basesWorkers16x16.xml")); mg.basesWorkers16x16().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/basesWorkersBarracks8x8.xml")); mg.basesWorkersBarracks8x8().toxml(xml); xml.flush(); // MELEE maps: xml = new XMLWriter(new FileWriter("maps/melee4x4light2.xml")); mg.melee4x4light2().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/melee8x8light4.xml")); mg.melee8x8light4().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/melee8x8Mixed4.xml")); mg.melee8x8Mixed4().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/8x8/melee8x8Mixed6.xml")); mg.melee8x8Mixed6().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/16x16/melee16x16Mixed8.xml")); mg.melee16x16Mixed8().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/12x12/melee12x12Mixed12.xml")); mg.melee12x12Mixed12().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/16x16/melee16x16Mixed12.xml")); mg.melee16x16Mixed12().toxml(xml); xml.flush(); xml = new XMLWriter(new FileWriter("maps/14x12/melee14x12Mixed18.xml")); mg.melee14x12Mixed18().toxml(xml); xml.flush(); } public PhysicalGameState bases8x8() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 20); Unit r1 = new Unit(-1,resourceType,7,7, 20); pgs.addUnit(r0); pgs.addUnit(r1); Unit u0 = new Unit(0,baseType,2,1,0); Unit u1 = new Unit(1,baseType,5,6,0); pgs.addUnit(u0); pgs.addUnit(u1); return pgs; } public PhysicalGameState basesWorkers8x8() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 20); Unit r1 = new Unit(-1,resourceType,7,7, 20); pgs.addUnit(r0); pgs.addUnit(r1); Unit u0 = new Unit(0,baseType,2,1,0); Unit u1 = new Unit(1,baseType,5,6,0); pgs.addUnit(u0); pgs.addUnit(u1); Unit w0 = new Unit(0,workerType, 1,1,0); Unit w1 = new Unit(1,workerType,6,6,0); pgs.addUnit(w0); pgs.addUnit(w1); return pgs; } public PhysicalGameState basesWorkers8x8Obstacle() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 20); Unit r1 = new Unit(-1,resourceType,7,7, 20); pgs.addUnit(r0); pgs.addUnit(r1); Unit u0 = new Unit(0,baseType,2,1,0); Unit u1 = new Unit(1,baseType,5,6,0); pgs.addUnit(u0); pgs.addUnit(u1); Unit w0 = new Unit(0,workerType,1,1,0); Unit w1 = new Unit(1,workerType,6,6,0); pgs.addUnit(w0); pgs.addUnit(w1); pgs.setTerrain(2, 3, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(2, 4, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(3, 3, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(3, 4, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(4, 3, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(4, 4, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(5, 3, PhysicalGameState.TERRAIN_WALL); pgs.setTerrain(5, 4, PhysicalGameState.TERRAIN_WALL); return pgs; } public PhysicalGameState basesWorkers12x12() { PhysicalGameState pgs = new PhysicalGameState(12,12); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 20); Unit r1 = new Unit(-1,resourceType,1,0, 20); Unit r2 = new Unit(-1,resourceType,11,11, 20); Unit r3 = new Unit(-1,resourceType,10,11, 20); pgs.addUnit(r0); pgs.addUnit(r1); pgs.addUnit(r2); pgs.addUnit(r3); Unit u0 = new Unit(0,baseType,1,2,0); Unit u1 = new Unit(1,baseType,10,9,0); pgs.addUnit(u0); pgs.addUnit(u1); Unit w0 = new Unit(0,workerType, 1,1,0); Unit w1 = new Unit(1,workerType,10,10,0); pgs.addUnit(w0); pgs.addUnit(w1); return pgs; } public PhysicalGameState complexBasesWorkers12x12() { PhysicalGameState pgs = new PhysicalGameState(12,12); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 20); Unit r1 = new Unit(-1,resourceType,1,0, 20); Unit r2 = new Unit(-1,resourceType,0,1, 20); Unit r3 = new Unit(-1,resourceType,11,11, 20); Unit r4 = new Unit(-1,resourceType,10,11, 20); Unit r5 = new Unit(-1,resourceType,11,10, 20); pgs.addUnit(r0); pgs.addUnit(r1); pgs.addUnit(r2); pgs.addUnit(r3); pgs.addUnit(r4); pgs.addUnit(r5); Unit u0 = new Unit(0,baseType,1,3,0); Unit u1 = new Unit(0,baseType,3,1,0); Unit u2 = new Unit(1,baseType,10,8,0); Unit u3 = new Unit(1,baseType,8,10,0); pgs.addUnit(u0); pgs.addUnit(u1); pgs.addUnit(u2); pgs.addUnit(u3); Unit w0 = new Unit(0,workerType, 2,2,0); Unit w1 = new Unit(1,workerType, 9,9,0); pgs.addUnit(w0); pgs.addUnit(w1); return pgs; } public PhysicalGameState basesWorkers16x16() { PhysicalGameState pgs = new PhysicalGameState(16,16); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 25); Unit r1 = new Unit(-1,resourceType,0,1, 25); Unit r2 = new Unit(-1,resourceType,15,14, 25); Unit r3 = new Unit(-1,resourceType,15,15, 25); pgs.addUnit(r0); pgs.addUnit(r1); pgs.addUnit(r2); pgs.addUnit(r3); Unit u0 = new Unit(0,baseType,2,2,0); Unit u1 = new Unit(1,baseType,13,13,0); pgs.addUnit(u0); pgs.addUnit(u1); Unit w0 = new Unit(0,workerType,1,1,0); Unit w1 = new Unit(1,workerType,14,14,0); pgs.addUnit(w0); pgs.addUnit(w1); return pgs; } public PhysicalGameState basesWorkersBarracks8x8() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,5); Player p1 = new Player(1,5); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit r0 = new Unit(-1,resourceType,0,0, 10); Unit r1 = new Unit(-1,resourceType,7,7, 10); pgs.addUnit(r0); pgs.addUnit(r1); Unit u0 = new Unit(0,baseType,2,1,0); Unit u1 = new Unit(1,baseType,5,6,0); pgs.addUnit(u0); pgs.addUnit(u1); Unit w0 = new Unit(0,workerType,1,1,0); Unit w1 = new Unit(1,workerType,6,6,0); pgs.addUnit(w0); pgs.addUnit(w1); Unit b0 = new Unit(0,barracksType,4,0,0); Unit b1 = new Unit(1,barracksType,3,7,0); pgs.addUnit(b0); pgs.addUnit(b1); return pgs; } public PhysicalGameState melee4x4light2() { PhysicalGameState pgs = new PhysicalGameState(4,4); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit l0 = new Unit(0,lightType,0,0); Unit l1 = new Unit(0,lightType,0,1); Unit l4 = new Unit(1,lightType,3,2); Unit l5 = new Unit(1,lightType,3,3); pgs.addUnit(l0); pgs.addUnit(l1); pgs.addUnit(l4); pgs.addUnit(l5); return pgs; } public PhysicalGameState melee8x8light4() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit l0 = new Unit(0,lightType,1,1); Unit l1 = new Unit(0,lightType,2,1); Unit l2 = new Unit(0,lightType,1,2); Unit l3 = new Unit(0,lightType,2,2); Unit l4 = new Unit(1,lightType,5,5); Unit l5 = new Unit(1,lightType,5,6); Unit l6 = new Unit(1,lightType,6,5); Unit l7 = new Unit(1,lightType,6,6); pgs.addUnit(l0); pgs.addUnit(l1); pgs.addUnit(l2); pgs.addUnit(l3); pgs.addUnit(l4); pgs.addUnit(l5); pgs.addUnit(l6); pgs.addUnit(l7); return pgs; } public PhysicalGameState melee8x8Mixed4() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); Unit l0 = new Unit(0,heavyType,1,1); Unit l1 = new Unit(0,lightType,2,1); Unit l2 = new Unit(0,heavyType,1,2); Unit l3 = new Unit(0,lightType,2,2); Unit l4 = new Unit(1,lightType,5,5); Unit l5 = new Unit(1,lightType,5,6); Unit l6 = new Unit(1,heavyType,6,5); Unit l7 = new Unit(1,heavyType,6,6); pgs.addUnit(l0); pgs.addUnit(l1); pgs.addUnit(l2); pgs.addUnit(l3); pgs.addUnit(l4); pgs.addUnit(l5); pgs.addUnit(l6); pgs.addUnit(l7); return pgs; } public PhysicalGameState melee8x8Mixed6() { PhysicalGameState pgs = new PhysicalGameState(8,8); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); pgs.addUnit(new Unit(0,lightType,2,0)); pgs.addUnit(new Unit(0,lightType,2,1)); pgs.addUnit(new Unit(0,heavyType,1,0)); pgs.addUnit(new Unit(0,heavyType,1,1)); pgs.addUnit(new Unit(0,rangedType,0,0)); pgs.addUnit(new Unit(0,rangedType,0,1)); pgs.addUnit(new Unit(1,lightType,5,6)); pgs.addUnit(new Unit(1,lightType,5,7)); pgs.addUnit(new Unit(1,heavyType,6,6)); pgs.addUnit(new Unit(1,heavyType,6,7)); pgs.addUnit(new Unit(1,rangedType,7,6)); pgs.addUnit(new Unit(1,rangedType,7,7)); return pgs; } public PhysicalGameState melee16x16Mixed8() { PhysicalGameState pgs = new PhysicalGameState(16,16); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); pgs.addUnit(new Unit(0,lightType,2,1)); pgs.addUnit(new Unit(0,lightType,2,2)); pgs.addUnit(new Unit(0,lightType,2,3)); pgs.addUnit(new Unit(0,lightType,2,4)); pgs.addUnit(new Unit(0,heavyType,1,1)); pgs.addUnit(new Unit(0,heavyType,1,2)); pgs.addUnit(new Unit(0,heavyType,1,3)); pgs.addUnit(new Unit(0,heavyType,1,4)); pgs.addUnit(new Unit(1,lightType,13,11)); pgs.addUnit(new Unit(1,lightType,13,12)); pgs.addUnit(new Unit(1,lightType,13,13)); pgs.addUnit(new Unit(1,lightType,13,14)); pgs.addUnit(new Unit(1,heavyType,14,11)); pgs.addUnit(new Unit(1,heavyType,14,12)); pgs.addUnit(new Unit(1,heavyType,14,13)); pgs.addUnit(new Unit(1,heavyType,14,14)); return pgs; } public PhysicalGameState melee12x12Mixed12() { PhysicalGameState pgs = new PhysicalGameState(12,12); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); pgs.addUnit(new Unit(0,lightType,2,1)); pgs.addUnit(new Unit(0,lightType,2,2)); pgs.addUnit(new Unit(0,lightType,2,3)); pgs.addUnit(new Unit(0,lightType,2,4)); pgs.addUnit(new Unit(0,heavyType,1,1)); pgs.addUnit(new Unit(0,heavyType,1,2)); pgs.addUnit(new Unit(0,heavyType,1,3)); pgs.addUnit(new Unit(0,heavyType,1,4)); pgs.addUnit(new Unit(0,rangedType,0,1)); pgs.addUnit(new Unit(0,rangedType,0,2)); pgs.addUnit(new Unit(0,rangedType,0,3)); pgs.addUnit(new Unit(0,rangedType,0,4)); pgs.addUnit(new Unit(1,lightType,9,7)); pgs.addUnit(new Unit(1,lightType,9,8)); pgs.addUnit(new Unit(1,lightType,9,9)); pgs.addUnit(new Unit(1,lightType,9,10)); pgs.addUnit(new Unit(1,heavyType,10,7)); pgs.addUnit(new Unit(1,heavyType,10,8)); pgs.addUnit(new Unit(1,heavyType,10,9)); pgs.addUnit(new Unit(1,heavyType,10,10)); pgs.addUnit(new Unit(1,rangedType,11,7)); pgs.addUnit(new Unit(1,rangedType,11,8)); pgs.addUnit(new Unit(1,rangedType,11,9)); pgs.addUnit(new Unit(1,rangedType,11,10)); return pgs; } public PhysicalGameState melee16x16Mixed12() { PhysicalGameState pgs = new PhysicalGameState(16,16); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); pgs.addUnit(new Unit(0,lightType,2,1)); pgs.addUnit(new Unit(0,lightType,2,2)); pgs.addUnit(new Unit(0,lightType,2,3)); pgs.addUnit(new Unit(0,lightType,2,4)); pgs.addUnit(new Unit(0,heavyType,1,1)); pgs.addUnit(new Unit(0,heavyType,1,2)); pgs.addUnit(new Unit(0,heavyType,1,3)); pgs.addUnit(new Unit(0,heavyType,1,4)); pgs.addUnit(new Unit(0,rangedType,0,1)); pgs.addUnit(new Unit(0,rangedType,0,2)); pgs.addUnit(new Unit(0,rangedType,0,3)); pgs.addUnit(new Unit(0,rangedType,0,4)); pgs.addUnit(new Unit(1,lightType,13,11)); pgs.addUnit(new Unit(1,lightType,13,12)); pgs.addUnit(new Unit(1,lightType,13,13)); pgs.addUnit(new Unit(1,lightType,13,14)); pgs.addUnit(new Unit(1,heavyType,14,11)); pgs.addUnit(new Unit(1,heavyType,14,12)); pgs.addUnit(new Unit(1,heavyType,14,13)); pgs.addUnit(new Unit(1,heavyType,14,14)); pgs.addUnit(new Unit(1,rangedType,15,11)); pgs.addUnit(new Unit(1,rangedType,15,12)); pgs.addUnit(new Unit(1,rangedType,15,13)); pgs.addUnit(new Unit(1,rangedType,15,14)); return pgs; } public PhysicalGameState melee14x12Mixed18() { PhysicalGameState pgs = new PhysicalGameState(14,12); Player p0 = new Player(0,0); Player p1 = new Player(1,0); pgs.addPlayer(p0); pgs.addPlayer(p1); pgs.addUnit(new Unit(0,lightType,2,1)); pgs.addUnit(new Unit(0,lightType,2,2)); pgs.addUnit(new Unit(0,lightType,2,3)); pgs.addUnit(new Unit(0,lightType,2,4)); pgs.addUnit(new Unit(0,lightType,2,5)); pgs.addUnit(new Unit(0,lightType,2,6)); pgs.addUnit(new Unit(0,heavyType,1,1)); pgs.addUnit(new Unit(0,heavyType,1,2)); pgs.addUnit(new Unit(0,heavyType,1,3)); pgs.addUnit(new Unit(0,heavyType,1,4)); pgs.addUnit(new Unit(0,heavyType,1,5)); pgs.addUnit(new Unit(0,heavyType,1,6)); pgs.addUnit(new Unit(0,rangedType,0,1)); pgs.addUnit(new Unit(0,rangedType,0,2)); pgs.addUnit(new Unit(0,rangedType,0,3)); pgs.addUnit(new Unit(0,rangedType,0,4)); pgs.addUnit(new Unit(0,rangedType,0,5)); pgs.addUnit(new Unit(0,rangedType,0,6)); pgs.addUnit(new Unit(1,lightType,11,5)); pgs.addUnit(new Unit(1,lightType,11,6)); pgs.addUnit(new Unit(1,lightType,11,7)); pgs.addUnit(new Unit(1,lightType,11,8)); pgs.addUnit(new Unit(1,lightType,11,9)); pgs.addUnit(new Unit(1,lightType,11,10)); pgs.addUnit(new Unit(1,heavyType,12,5)); pgs.addUnit(new Unit(1,heavyType,12,6)); pgs.addUnit(new Unit(1,heavyType,12,7)); pgs.addUnit(new Unit(1,heavyType,12,8)); pgs.addUnit(new Unit(1,heavyType,12,9)); pgs.addUnit(new Unit(1,heavyType,12,10)); pgs.addUnit(new Unit(1,rangedType,13,5)); pgs.addUnit(new Unit(1,rangedType,13,6)); pgs.addUnit(new Unit(1,rangedType,13,7)); pgs.addUnit(new Unit(1,rangedType,13,8)); pgs.addUnit(new Unit(1,rangedType,13,9)); pgs.addUnit(new Unit(1,rangedType,13,10)); return pgs; } }
19,331
31.877551
87
java
MicroRTS
MicroRTS-master/src/tests/MapVisualizationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import gui.PhysicalGameStatePanel; import java.io.OutputStreamWriter; import javax.swing.JFrame; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class MapVisualizationTest { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/8x8/basesWorkers8x8Obstacle.xml", utt); GameState gs = new GameState(pgs, utt); XMLWriter xml = new XMLWriter(new OutputStreamWriter(System.out)); pgs.toxml(xml); xml.flush(); OutputStreamWriter jsonwriter = new OutputStreamWriter(System.out); pgs.toJSON(jsonwriter); jsonwriter.flush(); JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640); JFrame w2 = PhysicalGameStatePanel.newVisualizer(new PartiallyObservableGameState(gs,0),640,640, true); JFrame w3 = PhysicalGameStatePanel.newVisualizer(gs,640,640,false,PhysicalGameStatePanel.COLORSCHEME_WHITE); } }
1,282
30.292683
116
java
MicroRTS
MicroRTS-master/src/tests/POGameVisualSimulationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.*; import ai.abstraction.LightRush; import ai.abstraction.pathfinding.BFSPathFinding; import gui.PhysicalGameStatePanel; import java.io.OutputStreamWriter; import javax.swing.JFrame; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; import util.XMLWriter; /** * * @author santi */ public class POGameVisualSimulationTest { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); // PhysicalGameState pgs = MapGenerator.basesWorkers8x8Obstacle(); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; int PERIOD = 20; boolean gameover = false; // AI ai1 = new RandomAI(); // AI ai1 = new WorkerRush(UnitTypeTable.utt, new BFSPathFinding()); AI ai1 = new LightRush(utt, new BFSPathFinding()); // AI ai1 = new RangedRush(UnitTypeTable.utt, new GreedyPathFinding()); // AI ai1 = new ContinuingNaiveMC(PERIOD, 200, 0.33f, 0.2f, new RandomBiasedAI(), new SimpleEvaluationFunction()); AI ai2 = new RandomBiasedAI(); // AI ai2 = new LightRush(); XMLWriter xml = new XMLWriter(new OutputStreamWriter(System.out)); pgs.toxml(xml); xml.flush(); JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640, true); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do{ if (System.currentTimeMillis()>=nextTimeToUpdate) { PlayerAction pa1 = ai1.getAction(0, new PartiallyObservableGameState(gs,0)); PlayerAction pa2 = ai2.getAction(1, new PartiallyObservableGameState(gs,1)); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); w.repaint(); nextTimeToUpdate+=PERIOD; } else { try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); System.out.println("Game Over"); } }
2,574
32.441558
121
java
MicroRTS
MicroRTS-master/src/tests/PlayGameWithMouseTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import ai.core.AI; import ai.*; import ai.core.ContinuingAI; import ai.evaluation.SimpleEvaluationFunction; import ai.mcts.naivemcts.NaiveMCTS; import gui.MouseController; import gui.PhysicalGameStateMouseJFrame; import gui.PhysicalGameStatePanel; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author santi */ public class PlayGameWithMouseTest { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 10000; int PERIOD = 100; boolean gameover = false; PhysicalGameStatePanel pgsp = new PhysicalGameStatePanel(gs); PhysicalGameStateMouseJFrame w = new PhysicalGameStateMouseJFrame("Game State Visuakizer (Mouse)",640,640,pgsp); // PhysicalGameStateMouseJFrame w = new PhysicalGameStateMouseJFrame("Game State Visuakizer (Mouse)",400,400,pgsp); AI ai1 = new MouseController(w); // AI ai2 = new PassiveAI(); // AI ai2 = new RandomBiasedAI(); // AI ai2 = new LightRush(utt, new AStarPathFinding()); AI ai2 = new ContinuingAI(new NaiveMCTS(PERIOD, -1, 100, 20, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), new SimpleEvaluationFunction(), true)); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do{ if (System.currentTimeMillis()>=nextTimeToUpdate) { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); w.repaint(); nextTimeToUpdate+=PERIOD; } else { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); System.out.println("Game Over"); } }
2,411
33.457143
150
java
MicroRTS
MicroRTS-master/src/tests/PlayerActionGenerationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests; import java.util.List; import rts.*; import rts.units.UnitTypeTable; /** * * @author santi */ public class PlayerActionGenerationTest { public static void main(String args[]) { UnitTypeTable utt = new UnitTypeTable(); MapGenerator mg = new MapGenerator(utt); PhysicalGameState pgs = mg.melee8x8light4(); GameState gs = new GameState(pgs, utt); for(Player p:pgs.getPlayers()) { List<PlayerAction> pal = gs.getPlayerActions(p.getID()); System.out.println("Player actions for " + p + ": " + pal.size() + " actions"); for(PlayerAction pa:pal) { System.out.println(" - " + pa); } } } }
843
25.375
91
java
MicroRTS
MicroRTS-master/src/tests/RunConfigurableExperiments.java
package tests; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.stream.Stream; import ai.RandomAI; import ai.RandomBiasedAI; import ai.abstraction.HeavyRush; import ai.abstraction.LightRush; import ai.abstraction.RangedRush; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.FloodFillPathFinding; import ai.abstraction.pathfinding.PathFinding; import ai.ahtn.AHTNAI; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ContinuingAI; import ai.core.PseudoContinuingAI; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleEvaluationFunction; import ai.mcts.naivemcts.NaiveMCTS; import ai.mcts.uct.DownsamplingUCT; import ai.mcts.uct.UCT; import ai.mcts.uct.UCTUnitActions; import ai.minimax.ABCD.IDABCD; import ai.minimax.RTMiniMax.IDRTMinimax; import ai.minimax.RTMiniMax.IDRTMinimaxRandomized; import ai.montecarlo.MonteCarlo; import ai.portfolio.PortfolioAI; import ai.portfolio.portfoliogreedysearch.PGSAI; import ai.puppet.BasicConfigurableScript; import ai.puppet.PuppetNoPlan; import ai.puppet.PuppetSearchAB; import ai.puppet.PuppetSearchMCTS; import ai.puppet.SingleChoiceConfigurableScript; import rts.PhysicalGameState; import rts.units.UnitTypeTable; import ai.core.InterruptibleAI; public class RunConfigurableExperiments { private static boolean CONTINUING = true; private static int TIME = 100; private static int MAX_ACTIONS = 100; private static int MAX_PLAYOUTS = -1; private static int PLAYOUT_TIME = 100; private static int MAX_DEPTH = 10; private static int RANDOMIZED_AB_REPEATS = 10; private static int PUPPET_PLAN_TIME = 5000; private static int PUPPET_PLAN_PLAYOUTS = -1; private static List<AI> bots1 = new LinkedList<>(); private static List<AI> bots2 = new LinkedList<>(); private static List<PhysicalGameState> maps = new LinkedList<>(); static UnitTypeTable utt = new UnitTypeTable( UnitTypeTable.VERSION_ORIGINAL_FINETUNED, UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH); public static PathFinding getPathFinding() { // return new BFSPathFinding(); // return new AStarPathFinding(); return new FloodFillPathFinding(); } public static EvaluationFunction getEvaluationFunction() { return new SimpleEvaluationFunction(); // return new SimpleOptEvaluationFunction(); // return new LanchesterEvaluationFunction(); } public static void loadMaps(String mapFileName) throws IOException { if (mapFileName.endsWith(".txt")) { try (Stream<String> lines = Files.lines(Paths.get(mapFileName), Charset.defaultCharset())) { lines.forEachOrdered(line -> { try { if (!line.startsWith("#") && !line.isEmpty()) { maps.add(PhysicalGameState.load(line, utt)); } } catch (Exception ex) { throw new RuntimeException(ex); } }); } } else if (mapFileName.endsWith(".xml")) { try { maps.add(PhysicalGameState.load(mapFileName, utt)); } catch (Exception ex) { throw new RuntimeException(ex); } } else { throw new IllegalArgumentException("Map file name must end in .txt " + "(for a list of maps) or .xml (for a single map)."); } } public static AI getBot(String botName) { switch (botName) { case "RandomAI": return new RandomAI(utt); case "RandomBiasedAI": return new RandomBiasedAI(); case "LightRush": return new LightRush(utt, getPathFinding()); case "RangedRush": return new RangedRush(utt, getPathFinding()); case "HeavyRush": return new HeavyRush(utt, getPathFinding()); case "WorkerRush": return new WorkerRush(utt, getPathFinding()); case "BasicConfigurableScript": return new BasicConfigurableScript(utt, getPathFinding()); case "SingleChoiceConfigurableScript": return new SingleChoiceConfigurableScript(getPathFinding(), new AI[]{new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new HeavyRush(utt, getPathFinding())}); case "PortfolioAI": return new PortfolioAI(new AI[]{new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new RandomBiasedAI()}, new boolean[]{true, true, true, false}, TIME, MAX_PLAYOUTS, PLAYOUT_TIME * 4, getEvaluationFunction()); case "PGSAI": return new PGSAI(TIME, MAX_PLAYOUTS, PLAYOUT_TIME * 4, 1, 0, getEvaluationFunction(), utt, getPathFinding()); case "IDRTMinimax": return new IDRTMinimax(TIME, getEvaluationFunction()); case "IDRTMinimaxRandomized": return new IDRTMinimaxRandomized(TIME, RANDOMIZED_AB_REPEATS, getEvaluationFunction()); case "IDABCD": return new IDABCD(TIME, MAX_PLAYOUTS, new WorkerRush(utt, getPathFinding()), PLAYOUT_TIME, getEvaluationFunction(), false); case "MonteCarlo1": return new MonteCarlo(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, new RandomBiasedAI(), getEvaluationFunction()); case "MonteCarlo2": return new MonteCarlo(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_ACTIONS, new RandomBiasedAI(), getEvaluationFunction()); // by setting "MAX_DEPTH = 1" in the next two bots, this effectively makes them Monte Carlo search, instead of Monte Carlo Tree Search case "NaiveMCTS1"://MonteCarlo return new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), getEvaluationFunction(), true); case "NaiveMCTS2"://epsilon-greedy MonteCarlo return new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 1, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), getEvaluationFunction(), true); case "UCT": return new UCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, new RandomBiasedAI(), getEvaluationFunction()); case "DownsamplingUCT": return new DownsamplingUCT(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_ACTIONS, MAX_DEPTH, new RandomBiasedAI(), getEvaluationFunction()); case "UCTUnitActions": return new UCTUnitActions(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH * 10, new RandomBiasedAI(), getEvaluationFunction()); case "NaiveMCTS3"://NaiveMCTS return new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 0.33f, 0.0f, 0.75f, new RandomBiasedAI(), getEvaluationFunction(), true); case "NaiveMCTS4"://epsilon-greedy MCTS return new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, MAX_DEPTH, 1.00f, 0.0f, 0.25f, new RandomBiasedAI(), getEvaluationFunction(), true); case "AHTN-LL": try { return new AHTNAI("ahtn/microrts-ahtn-definition-lowest-level.lisp", TIME, MAX_PLAYOUTS, PLAYOUT_TIME, getEvaluationFunction(), new RandomBiasedAI()); } catch (Exception e) { throw new RuntimeException(e); } case "AHTN-LLPF": try { return new AHTNAI("ahtn/microrts-ahtn-definition-low-level.lisp", TIME, MAX_PLAYOUTS, PLAYOUT_TIME, getEvaluationFunction(), new RandomBiasedAI()); } catch (Exception e) { throw new RuntimeException(e); } case "AHTN-P": try { return new AHTNAI("ahtn/microrts-ahtn-definition-portfolio.lisp", TIME, MAX_PLAYOUTS, PLAYOUT_TIME, getEvaluationFunction(), new RandomBiasedAI()); } catch (Exception e) { throw new RuntimeException(e); } case "AHTN-F": try { return new AHTNAI("ahtn/microrts-ahtn-definition-flexible-portfolio.lisp", TIME, MAX_PLAYOUTS, PLAYOUT_TIME, getEvaluationFunction(), new RandomBiasedAI()); } catch (Exception e) { throw new RuntimeException(e); } case "AHTN-FST": try { return new AHTNAI("ahtn/microrts-ahtn-definition-flexible-single-target-portfolio.lisp", TIME, MAX_PLAYOUTS, PLAYOUT_TIME, getEvaluationFunction(), new RandomBiasedAI()); } catch (Exception e) { throw new RuntimeException(e); } case "PuppetABCDSingle": return new PuppetSearchAB( TIME, MAX_PLAYOUTS, PUPPET_PLAN_TIME, PUPPET_PLAN_PLAYOUTS, PLAYOUT_TIME, new SingleChoiceConfigurableScript(getPathFinding(), new AI[]{ new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new HeavyRush(utt, getPathFinding()),}), getEvaluationFunction()); case "PuppetABCDSingleNoPlan": return new PuppetNoPlan( new PuppetSearchAB( TIME, MAX_PLAYOUTS, -1, -1, PLAYOUT_TIME, new SingleChoiceConfigurableScript(getPathFinding(), new AI[]{ new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new HeavyRush(utt, getPathFinding()),}), getEvaluationFunction()) ); case "PuppetABCDBasic": return new PuppetSearchAB( TIME, MAX_PLAYOUTS, PUPPET_PLAN_TIME, PUPPET_PLAN_PLAYOUTS, PLAYOUT_TIME, new BasicConfigurableScript(utt, getPathFinding()), getEvaluationFunction()); case "PuppetABCDBasicNoPlan": return new PuppetNoPlan( new PuppetSearchAB( TIME, MAX_PLAYOUTS, -1, -1, PLAYOUT_TIME, new BasicConfigurableScript(utt, getPathFinding()), getEvaluationFunction()) ); case "PuppetMCTSSingle": return new PuppetSearchMCTS( TIME, MAX_PLAYOUTS, PUPPET_PLAN_TIME, PUPPET_PLAN_PLAYOUTS, PLAYOUT_TIME, PLAYOUT_TIME, new RandomBiasedAI(), new SingleChoiceConfigurableScript(getPathFinding(), new AI[]{new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new HeavyRush(utt, getPathFinding())}), getEvaluationFunction()); case "PuppetMCTSSingleNoPlan": return new PuppetNoPlan(new PuppetSearchMCTS( TIME, MAX_PLAYOUTS, -1, -1, PLAYOUT_TIME, PLAYOUT_TIME, new RandomBiasedAI(), new SingleChoiceConfigurableScript(getPathFinding(), new AI[]{new WorkerRush(utt, getPathFinding()), new LightRush(utt, getPathFinding()), new RangedRush(utt, getPathFinding()), new HeavyRush(utt, getPathFinding())}), getEvaluationFunction()) ); case "PuppetMCTSBasic": return new PuppetSearchMCTS( TIME, MAX_PLAYOUTS, PUPPET_PLAN_TIME, PUPPET_PLAN_PLAYOUTS, PLAYOUT_TIME, PLAYOUT_TIME, new RandomBiasedAI(), new BasicConfigurableScript(utt, getPathFinding()), getEvaluationFunction()); case "PuppetMCTSBasicNoPlan": return new PuppetNoPlan( new PuppetSearchMCTS( TIME, MAX_PLAYOUTS, -1, -1, PLAYOUT_TIME, PLAYOUT_TIME, new RandomBiasedAI(), new BasicConfigurableScript(utt, getPathFinding()), getEvaluationFunction()) ); default: throw new RuntimeException("AI not found"); } } public static void loadBots1(String botFileName) throws IOException { try (Stream<String> lines = Files.lines(Paths.get(botFileName), Charset.defaultCharset())) { lines.forEachOrdered(line -> { try { if (!line.startsWith("#") && !line.isEmpty()) { bots1.add(getBot(line)); } } catch (Exception ex) { throw new RuntimeException(ex); } }); } } public static void loadBots2(String botFileName) throws IOException { try (Stream<String> lines = Files.lines(Paths.get(botFileName), Charset.defaultCharset())) { lines.forEachOrdered(line -> { try { if (!line.startsWith("#") && !line.isEmpty()) { bots2.add(getBot(line)); } } catch (Exception ex) { throw new RuntimeException(ex); } }); } } public static void processBots(List<AI> bots) throws Exception { if (CONTINUING) { // Find out which of the bots can be used in "continuing" mode: List<AI> botstemp = new LinkedList<>(); for (AI bot : bots) { if (bot instanceof AIWithComputationBudget) { if (bot instanceof InterruptibleAI) { botstemp.add(new ContinuingAI(bot)); } else { botstemp.add(new PseudoContinuingAI((AIWithComputationBudget) bot)); } } else { botstemp.add(bot); } } bots.clear(); bots.addAll(botstemp); } } //Arguments: bots1file (bots2file|-) mapsfile resultsfile iterations (traceDir) public static void main(String args[]) throws Exception { boolean asymetric = !args[1].equals("-"); loadBots1(args[0]); if (asymetric) { loadBots2(args[1]); } processBots(bots1); if (asymetric) { processBots(bots2); } loadMaps(args[2]); PrintStream out = new PrintStream(new File(args[3])); int iterations = Integer.parseInt(args[4]); String traceDir = null; boolean saveTrace = false; boolean saveZip = false; if (args.length >= 6) { saveTrace = true; saveZip = true; traceDir = args[5]; } if (true) { if (asymetric) { ExperimenterAsymmetric.runExperiments(bots1, bots2, maps, utt, iterations, 3000, 300, false, out, saveTrace, saveZip, traceDir); } else { Experimenter.runExperiments(bots1, maps, utt, iterations, 3000, 300, false, out, -1, true, false, saveTrace, saveZip, traceDir); } } else {// Separate the matches by map: for (PhysicalGameState map : maps) { if (asymetric) { ExperimenterAsymmetric.runExperiments(bots1, bots2, Collections.singletonList(map), utt, iterations, 3000, 300, false, out, saveTrace, saveZip, traceDir); } else { Experimenter.runExperiments(bots1, Collections.singletonList(map), utt, iterations, 3000, 300, false, out, -1, true, false, saveTrace, saveZip, traceDir); } } } } }
18,149
44.717884
146
java
MicroRTS
MicroRTS-master/src/tests/bayesianmodels/GenerateTrainingTraces.java
package tests.bayesianmodels; import ai.core.AI; import ai.*; import ai.abstraction.HeavyRush; import ai.abstraction.LightRush; import ai.abstraction.RangedRush; import ai.abstraction.WorkerRush; import ai.abstraction.pathfinding.AStarPathFinding; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.naivemcts.NaiveMCTS; import ai.montecarlo.lsi.LSI; import ai.montecarlo.lsi.Sampling; import gui.PhysicalGameStateJFrame; import gui.PhysicalGameStatePanel; import java.io.File; import java.io.FileWriter; import java.io.PrintStream; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.Trace; import rts.TraceEntry; import rts.units.UnitTypeTable; import util.XMLWriter; public class GenerateTrainingTraces { public static int DEBUG = 0; public static void main(String args[]) throws Exception { AI randomAI = new RandomBiasedAI(); EvaluationFunction ef = new SimpleSqrtEvaluationFunction3(); UnitTypeTable utt = new UnitTypeTable(); int TIME = -1; int PLAYOUT_TIME = 100; int EXPERIMENT_ITERATIONS = 1; int MAX_PLAYOUTS = 500; List<AI> bots = new LinkedList<>(); // Rushes: bots.add(new WorkerRush(utt, new AStarPathFinding())); bots.add(new LightRush(utt, new AStarPathFinding())); bots.add(new HeavyRush(utt, new AStarPathFinding())); bots.add(new RangedRush(utt, new AStarPathFinding())); // LSI: bots.add(new LSI(MAX_PLAYOUTS, PLAYOUT_TIME, 0.75, LSI.EstimateType.RANDOM_TAIL, LSI.EstimateReuseType.ALL, LSI.GenerateType.PER_AGENT, Sampling.AgentOrderingType.ENTROPY, LSI.EvaluateType.HALVING, false, LSI.RelaxationType.NONE, 2, false, randomAI, ef)); // NaiveMCTS up to depth 8: bots.add(new NaiveMCTS(TIME, MAX_PLAYOUTS, PLAYOUT_TIME, 16, 0.33f, 0.0f, 0.4f, new RandomBiasedAI(), new SimpleSqrtEvaluationFunction3(), true)); String mapnames[] = {"maps/8x8/OneBaseWorker8x8.xml", "maps/8x8/TwoBasesWorkers8x8.xml", "maps/8x8/ThreeBasesWorkers8x8.xml", "maps/8x8/FourBasesWorkers8x8.xml", "maps/12x12/OneBaseWorker12x12.xml", "maps/12x12/TwoBasesWorkers12x12.xml", "maps/12x12/ThreeBasesWorkers12x12.xml", "maps/12x12/FourBasesWorkers12x12.xml", }; PrintStream out = new PrintStream(new File("learningtracegeneration-"+MAX_PLAYOUTS+".txt")); List<PhysicalGameState> maps = new LinkedList<>(); for(String mapname:mapnames) maps.add(PhysicalGameState.load(mapname,utt)); runExperiments(bots, maps, utt, EXPERIMENT_ITERATIONS, 3000, 300, false, out, -1, false, false,"learningtrace-"+MAX_PLAYOUTS); } public static void runExperiments(List<AI> bots, List<PhysicalGameState> maps, UnitTypeTable utt, int iterations, int max_cycles, int max_inactive_cycles, boolean visualize, PrintStream out, int run_only_those_involving_this_AI, boolean skip_self_play, boolean partiallyObservable, String tracePrefix) throws Exception { int wins[][] = new int[bots.size()][bots.size()]; int ties[][] = new int[bots.size()][bots.size()]; int loses[][] = new int[bots.size()][bots.size()]; double win_time[][] = new double[bots.size()][bots.size()]; double tie_time[][] = new double[bots.size()][bots.size()]; double lose_time[][] = new double[bots.size()][bots.size()]; List<AI> bots2 = new LinkedList<>(); for(AI bot:bots) bots2.add(bot.clone()); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (run_only_those_involving_this_AI!=-1 && ai1_idx!=run_only_those_involving_this_AI && ai2_idx!=run_only_those_involving_this_AI) continue; // if (ai1_idx==0 && ai2_idx==0) continue; if (skip_self_play && ai1_idx==ai2_idx) continue; for(PhysicalGameState pgs:maps) { for (int i = 0; i < iterations; i++) { AI ai1 = bots.get(ai1_idx); AI ai2 = bots2.get(ai2_idx); long lastTimeActionIssued = 0; ai1.reset(); ai2.reset(); GameState gs = new GameState(pgs.clone(),utt); Trace trace = new Trace(utt); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); PhysicalGameStateJFrame w = null; if (visualize) w = PhysicalGameStatePanel.newVisualizer(gs, 600, 600, partiallyObservable); out.println("MATCH UP: " + ai1+ " vs " + ai2); boolean gameover = false; do { System.gc(); PlayerAction pa1 = null, pa2 = null; if (partiallyObservable) { pa1 = ai1.getAction(0, new PartiallyObservableGameState(gs,0)); // if (DEBUG>=1) {System.out.println("AI1 done.");out.flush();} pa2 = ai2.getAction(1, new PartiallyObservableGameState(gs,1)); // if (DEBUG>=1) {System.out.println("AI2 done.");out.flush();} } else { pa1 = ai1.getAction(0, gs); if (DEBUG>=1) {System.out.println("AI1 done.");out.flush();} pa2 = ai2.getAction(1, gs); if (DEBUG>=1) {System.out.println("AI2 done.");out.flush();} } if (!pa1.isEmpty() || !pa2.isEmpty()) { te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } if (gs.issueSafe(pa1)) lastTimeActionIssued = gs.getTime(); // if (DEBUG>=1) {System.out.println("issue action AI1 done: " + pa1);out.flush();} if (gs.issueSafe(pa2)) lastTimeActionIssued = gs.getTime(); // if (DEBUG>=1) {System.out.println("issue action AI2 done:" + pa2);out.flush();} gameover = gs.cycle(); if (DEBUG>=1) {System.out.println("cycle done.");out.flush();} if (w!=null) { w.setStateCloning(gs); w.repaint(); try { Thread.sleep(1); // give time to the window to repaint } catch (Exception e) { e.printStackTrace(); } // if (DEBUG>=1) {System.out.println("repaint done.");out.flush();} } } while (!gameover && (gs.getTime() < max_cycles) && (gs.getTime() - lastTimeActionIssued < max_inactive_cycles)); te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); String fileName = tracePrefix+"-map"+maps.indexOf(pgs)+"-AI"+ai1_idx+"-AI"+ai2_idx+"-"+i+".xml"; System.out.println("Saving trace: " + fileName); XMLWriter xml = new XMLWriter(new FileWriter(fileName)); trace.toxml(xml); xml.flush(); if (w!=null) w.dispose(); int winner = gs.winner(); out.println("Winner: " + winner + " in " + gs.getTime() + " cycles"); out.println(ai1 + " : " + ai1.statisticsString()); out.println(ai2 + " : " + ai2.statisticsString()); out.flush(); if (winner == -1) { ties[ai1_idx][ai2_idx]++; tie_time[ai1_idx][ai2_idx]+=gs.getTime(); ties[ai2_idx][ai1_idx]++; tie_time[ai2_idx][ai1_idx]+=gs.getTime(); } else if (winner == 0) { wins[ai1_idx][ai2_idx]++; win_time[ai1_idx][ai2_idx]+=gs.getTime(); loses[ai2_idx][ai1_idx]++; lose_time[ai2_idx][ai1_idx]+=gs.getTime(); } else if (winner == 1) { loses[ai1_idx][ai2_idx]++; lose_time[ai1_idx][ai2_idx]+=gs.getTime(); wins[ai2_idx][ai1_idx]++; win_time[ai2_idx][ai1_idx]+=gs.getTime(); } } } } } out.println("Wins: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(wins[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Ties: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(ties[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Loses: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { out.print(loses[ai1_idx][ai2_idx] + ", "); } out.println(""); } out.println("Win average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (wins[ai1_idx][ai2_idx]>0) { out.print((win_time[ai1_idx][ai2_idx]/wins[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Tie average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (ties[ai1_idx][ai2_idx]>0) { out.print((tie_time[ai1_idx][ai2_idx]/ties[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.println("Lose average time: "); for (int ai1_idx = 0; ai1_idx < bots.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < bots.size(); ai2_idx++) { if (loses[ai1_idx][ai2_idx]>0) { out.print((lose_time[ai1_idx][ai2_idx]/loses[ai1_idx][ai2_idx]) + ", "); } else { out.print("-, "); } } out.println(""); } out.flush(); } }
12,523
46.984674
195
java
MicroRTS
MicroRTS-master/src/tests/bayesianmodels/PretrainNaiveBayesModels.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tests.bayesianmodels; import ai.machinelearning.bayes.ActionInterdependenceModel; import ai.machinelearning.bayes.BayesianModel; import ai.machinelearning.bayes.BayesianModelByUnitTypeWithDefaultModel; import ai.machinelearning.bayes.CalibratedNaiveBayes; import ai.machinelearning.bayes.TrainingInstance; import ai.machinelearning.bayes.featuregeneration.FeatureGenerator; import ai.machinelearning.bayes.featuregeneration.FeatureGeneratorSimple; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.jdom.input.SAXBuilder; import rts.GameState; import rts.Trace; import rts.TraceEntry; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * * @author santi */ public class PretrainNaiveBayesModels { public static int CALIBRATED_NAIVE_BAYES = 0; public static int ACTION_INTERDEPENDENCE_MODEL = 1; public static int CALIBRATED_NAIVE_BAYES_BY_UNIT_TYPE = 2; public static int ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE = 3; // Note: to run this method, you first need to generate traces, and place them in the appropriate folders // traces are generated with tests.bayesianmodels.GenerateTrainingTraces.java" public static void main(String args[]) throws Exception { pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI0", "data/bayesianmodels/pretrained/ActionInterdependenceModel-WR.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI1", "data/bayesianmodels/pretrained/ActionInterdependenceModel-LR.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI2", "data/bayesianmodels/pretrained/ActionInterdependenceModel-HR.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI3", "data/bayesianmodels/pretrained/ActionInterdependenceModel-RR.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI4", "data/bayesianmodels/pretrained/ActionInterdependenceModel-LSI500.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-500","AI5", "data/bayesianmodels/pretrained/ActionInterdependenceModel-NaiveMCTS500.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-10000","AI4", "data/bayesianmodels/pretrained/ActionInterdependenceModel-LSI10000.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); pretrain("data/bayesianmodels/trainingdata/learning-traces-10000","AI5", "data/bayesianmodels/pretrained/ActionInterdependenceModel-NaiveMCTS10000.xml", ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE, new FeatureGeneratorSimple()); } public static void pretrain(String tracesFolder, String AIname, String outputFileName, int model_type, FeatureGenerator fg) throws Exception { UnitTypeTable utt = new UnitTypeTable(); // List<Trace> traces = FeatureGeneration.loadTraces(tracesFolder, utt); // System.out.println(traces.size() + " traces loaded."); // List<TrainingInstance> instances = FeatureGeneration.generateInstances(traces); List<TrainingInstance> instances = generateInstances(tracesFolder, AIname); System.out.println(instances.size() + " instances generated."); // translate to feature vectors: // translate to feature vectors: List<List<Object>> features = new ArrayList<>(); for(TrainingInstance ti:instances) { features.add(fg.generateFeatures(ti)); } int nfeatures = features.get(0).size(); int []Xsizes = new int[nfeatures]; List<int []> X_l = new ArrayList<>(); for(List<Object> feature_vector:features) { int []x = new int[feature_vector.size()]; for(int i = 0;i<feature_vector.size();i++) { x[i] = (Integer)feature_vector.get(i); if (x[i] >= Xsizes[i]) Xsizes[i] = x[i]+1; } X_l.add(x); } List<UnitAction> allPossibleActions = BayesianModel.generateAllPossibleUnitActions(utt); System.out.println(allPossibleActions.size() + " labels: " + allPossibleActions); List<Integer> Y_l = new ArrayList<>(); for(TrainingInstance ti:instances) { int idx = allPossibleActions.indexOf(ti.ua); if (idx<0) throw new Exception("Undefined action " + ti.ua); Y_l.add(idx); } System.out.println("Dataset generated, ready to learn"); BayesianModel model = null; if (model_type == CALIBRATED_NAIVE_BAYES) { model = new CalibratedNaiveBayes(Xsizes, allPossibleActions.size(), BayesianModel.ESTIMATION_LAPLACE, 0.0, utt, fg, "CNB"); } else if (model_type == ACTION_INTERDEPENDENCE_MODEL) { model = new ActionInterdependenceModel(Xsizes, allPossibleActions.size(), BayesianModel.ESTIMATION_LAPLACE, 0.0, utt, fg, "AIM"); } else if (model_type == CALIBRATED_NAIVE_BAYES_BY_UNIT_TYPE) { model = new BayesianModelByUnitTypeWithDefaultModel(utt, new CalibratedNaiveBayes(Xsizes, allPossibleActions.size(), BayesianModel.ESTIMATION_LAPLACE, 0.0, utt, fg, "CNB"), "CNB"); } else if (model_type == ACTION_INTERDEPENDENCE_MODEL_BY_UNIT_TYPE) { model = new BayesianModelByUnitTypeWithDefaultModel(utt, new ActionInterdependenceModel(Xsizes, allPossibleActions.size(), BayesianModel.ESTIMATION_LAPLACE, 0.0, utt, fg, "AIM"), "AIM"); } model.featureSelectionByCrossValidation(X_l, Y_l, instances); model.train(X_l, Y_l, instances); model.calibrateProbabilities(X_l, Y_l, instances); XMLWriter w = new XMLWriter(new FileWriter(outputFileName)); model.save(w); w.close(); } public static List<TrainingInstance> generateInstances(String tracesFolder, String targetAIID) throws Exception { List<TrainingInstance> instances = new ArrayList<>(); File folder = new File(tracesFolder); for(File file:folder.listFiles()) { String fileName = file.getAbsolutePath(); if (fileName.endsWith(".xml")) { String justFileName = file.getName(); StringTokenizer st = new StringTokenizer(justFileName,"-"); st.nextToken(); String map = st.nextToken(); if (!map.startsWith("map")) map = st.nextToken(); String ai1 = st.nextToken(); String ai2 = st.nextToken(); // System.out.println(ai1 + " vs " + ai2); int playerToLearnFrom = -1; if (ai1.equals(targetAIID)) playerToLearnFrom = 0; if (ai2.equals(targetAIID)) playerToLearnFrom = 1; if (playerToLearnFrom>=0) { Trace t = new Trace(new SAXBuilder().build(fileName).getRootElement()); for(TraceEntry te:t.getEntries()) { GameState gs = t.getGameStateAtCycle(te.getTime()); for(Pair<Unit,UnitAction> tmp:te.getActions()) { if (tmp.m_a.getUnitActions(gs).size()>1) { if (tmp.m_a.getPlayer()==playerToLearnFrom) { TrainingInstance ti = new TrainingInstance(gs, tmp.m_a.getID(), tmp.m_b); // verify action is possible: List<UnitAction> ual = tmp.m_a.getUnitActions(gs); if (!ual.contains(tmp.m_b)) { System.out.println("invalid instance...: " + tmp.m_b); } else { instances.add(ti); } } } } } } } } return instances; } }
8,857
54.710692
234
java
MicroRTS
MicroRTS-master/src/tests/bayesianmodels/TestPretrainedBayesianModel.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tests.bayesianmodels; import ai.machinelearning.bayes.ActionInterdependenceModel; import ai.machinelearning.bayes.BayesianModel; import ai.machinelearning.bayes.BayesianModelByUnitTypeWithDefaultModel; import ai.machinelearning.bayes.TrainingInstance; import ai.machinelearning.bayes.featuregeneration.FeatureGenerator; import ai.machinelearning.bayes.featuregeneration.FeatureGeneratorSimple; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import org.jdom.input.SAXBuilder; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; /* * * @author santi */ public class TestPretrainedBayesianModel { // note: before running this method, you need to generte traces public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); FeatureGenerator fg = new FeatureGeneratorSimple(); // test(new BayesianModelByUnitTypeWithDefaultModel(new SAXBuilder().build( // "data/bayesianmodels/pretrained/ActionInterdependenceModel-WR.xml").getRootElement(), utt, // new ActionInterdependenceModel(null, 0, 0, 0, utt, fg)), // "data/bayesianmodels/trainingdata/learning-traces-500","AI0", utt, fg); test(new BayesianModelByUnitTypeWithDefaultModel(new SAXBuilder().build( "data/bayesianmodels/pretrained/ActionInterdependenceModel-WR.xml").getRootElement(), utt, new ActionInterdependenceModel(null, 0, 0, 0, utt, fg, ""), "AIM_WR"), "data/bayesianmodels/trainingdata/learning-traces-500","AI0", utt, fg); } public static void test(BayesianModel model, String tracesFolder, String AIname, UnitTypeTable utt, FeatureGenerator fg) throws Exception { List<TrainingInstance> instances = PretrainNaiveBayesModels.generateInstances(tracesFolder, AIname); System.out.println(instances.size() + " instances generated."); // translate to feature vectors: List<List<Object>> features = new ArrayList<>(); for(TrainingInstance ti:instances) { features.add(fg.generateFeatures(ti)); } int nfeatures = features.get(0).size(); int []Xsizes = new int[nfeatures]; List<int []> X_l = new ArrayList<>(); for(List<Object> feature_vector:features) { int []x = new int[feature_vector.size()]; for(int i = 0;i<feature_vector.size();i++) { x[i] = (Integer)feature_vector.get(i); if (x[i] >= Xsizes[i]) Xsizes[i] = x[i]+1; } X_l.add(x); } List<UnitAction> allPossibleActions = generateAllPossibleUnitActions(utt); System.out.println(allPossibleActions.size() + " labels: " + allPossibleActions); List<Integer> Y_l = new ArrayList<>(); for(TrainingInstance ti:instances) { int idx = allPossibleActions.indexOf(ti.ua); if (idx<0) throw new Exception("Undefined action " + ti.ua); Y_l.add(idx); } System.out.println(" /------------ start testing " + tracesFolder + " - " + AIname + " --------------\\ "); crossValidation(model, X_l, Y_l, instances, allPossibleActions, 10, true, false); System.out.println(" \\------------ end testing " + tracesFolder + " - " + AIname + " --------------/ "); } public static double crossValidation(BayesianModel model, List<int []> X_l, List<Integer> Y_l, List<TrainingInstance> instances, List<UnitAction> allPossibleActions, int nfolds, boolean DEBUG, boolean calibrate) throws Exception { Random r = new Random(); List<Integer> folds[] = new List[nfolds]; int nfeatures = X_l.get(0).length; int []Xsizes = new int[nfeatures]; int Ysize = 0; UnitTypeTable utt = instances.get(0).gs.getUnitTypeTable(); for(int i = 0;i<nfolds;i++) { folds[i] = new ArrayList<>(); } for(int i = 0;i<X_l.size();i++) { int fold = r.nextInt(nfolds); folds[fold].add(i); for(int j = 0;j<nfeatures;j++) { if (X_l.get(i)[j] >= Xsizes[j]) Xsizes[j] = X_l.get(i)[j]+1; } if (Y_l.get(i) >= Ysize) Ysize = Y_l.get(i)+1; } if (DEBUG) System.out.println("Xsizes: " + Arrays.toString(Xsizes)); if (DEBUG) System.out.println("Ysize: " + Ysize); double correct_per_unit[] = new double[utt.getUnitTypes().size()]; double total_per_unit[] = new double[utt.getUnitTypes().size()]; double loglikelihood_per_unit[] = new double[utt.getUnitTypes().size()]; for(int fold = 0;fold<nfolds;fold++) { if (DEBUG) System.out.println("Evaluating fold " + (fold+1) + "/" + nfolds + ":"); // prepare training and test set: List<int []> X_training = new ArrayList<>(); List<Integer> Y_training = new ArrayList<>(); List<TrainingInstance> i_training = new ArrayList<>(); List<int []> X_test = new ArrayList<>(); List<Integer> Y_test = new ArrayList<>(); List<TrainingInstance> i_test = new ArrayList<>(); for(int i = 0;i<nfolds;i++) { if (i==fold) { for(int idx:folds[i]) { X_test.add(X_l.get(idx)); Y_test.add(Y_l.get(idx)); i_test.add(instances.get(idx)); } } else { for(int idx:folds[i]) { X_training.add(X_l.get(idx)); Y_training.add(Y_l.get(idx)); i_training.add(instances.get(idx)); } } } if (DEBUG) System.out.println(" training/test split is " + X_training.size() + "/" + X_test.size()); // train the model: model.clearTraining(); model.train(X_training, Y_training, i_training); if (calibrate) model.calibrateProbabilities(X_training, Y_training, i_training); /* model.save(new XMLWriter(new FileWriter(model.getClass().getSimpleName() + ".xml"))); Element e = new SAXBuilder().build(model.getClass().getSimpleName() + ".xml").getRootElement(); // model = new OldNaiveBayes(e); // model = new SimpleNaiveBayesByUnitType(e, utt); // model = new NaiveBayesCorrectedByActionSet(e, allPossibleActions); // model = new NaiveBayesByUnitTypeCorrectedByActionSet(e, allPossibleActions, utt); */ // test the model: int fold_correct_per_unit[] = new int[utt.getUnitTypes().size()]; int fold_total_per_unit[] = new int[utt.getUnitTypes().size()]; double fold_loglikelihood_per_unit[] = new double[utt.getUnitTypes().size()]; double numPossibleActionsAccum = 0; for(int i = 0;i<X_test.size();i++) { Unit u = i_test.get(i).u; List<UnitAction> possibleUnitActions = u.getUnitActions(i_test.get(i).gs); List<Integer> possibleUnitActionIndexes = new ArrayList<>(); for(UnitAction ua : possibleUnitActions) { if (ua.getType()==UnitAction.TYPE_ATTACK_LOCATION) { ua = new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, ua.getLocationX() - u.getX(), ua.getLocationY() - u.getY()); } int idx = allPossibleActions.indexOf(ua); if (idx<0) throw new Exception("Unknown action: " + ua); possibleUnitActionIndexes.add(idx); } if (possibleUnitActions.size()>1) { numPossibleActionsAccum += possibleUnitActions.size(); // double predicted_distribution[] = ((SimpleNaiveBayes)model).predictDistribution(X_test.get(i), i_test.get(i), true); // double predicted_distribution_nocorrection[] = ((SimpleNaiveBayes)model).predictDistribution(X_test.get(i), i_test.get(i), false); double predicted_distribution[] = model.predictDistribution(X_test.get(i), i_test.get(i)); // double predicted_distribution[] = model.predictDistribution(X_test.get(i), u.getType()); // double predicted_distribution[] = model.predictDistribution(X_test.get(i)); // double predicted_distribution[] = new double[allPossibleActions.size()]; // for(int j = 0;j<predicted_distribution.length;j++) predicted_distribution[j] = r.nextDouble(); predicted_distribution = model.filterByPossibleActionIndexes(predicted_distribution, possibleUnitActionIndexes); // predicted_distribution_nocorrection = filterByPossibleActions(predicted_distribution_nocorrection, possibleUnitActionIndexes); int actual_y = Y_test.get(i); if (!possibleUnitActionIndexes.contains(actual_y)) { // System.out.println("Game State\n" + i_test.get(i).gs); // System.out.println("Unit\n" + i_test.get(i).u); // System.out.println("Action\n" + i_test.get(i).ua); // throw new Exception("actual action in the dataset is not possible!"); System.out.println("Actual action in the dataset is not possible!"); continue; } int predicted_y = -1; // int predicted_y_nocorrection = -1; Collections.shuffle(possibleUnitActions); // shuffle it, just in case there are ties, to prevent action ordering bias for(int idx:possibleUnitActionIndexes) { if (predicted_y==-1) { predicted_y = idx; } else { if (predicted_distribution[idx]>predicted_distribution[predicted_y]) predicted_y = idx; } /* if (predicted_y_nocorrection==-1) { predicted_y_nocorrection = idx; } else { if (predicted_distribution_nocorrection[idx]>predicted_distribution_nocorrection[predicted_y_nocorrection]) predicted_y_nocorrection = idx; } */ } /* if (predicted_y != predicted_y_nocorrection) { System.out.println(Arrays.toString(predicted_distribution)); System.out.println(Arrays.toString(predicted_distribution_nocorrection)); System.out.println(predicted_y); System.out.println(predicted_y_nocorrection); System.exit(0); } */ // if (u.getType().name.equals("Worker")) System.out.println(allPossibleActions.get(actual_y) + " -> " + allPossibleActions.get(predicted_y) + " " + Arrays.toString(predicted_distribution)); if (predicted_y == actual_y) fold_correct_per_unit[u.getType().ID]++; fold_total_per_unit[u.getType().ID]++; double loglikelihood = Math.log(predicted_distribution[actual_y]); // double loglikelihood_nocorrection = Math.log(predicted_distribution_nocorrection[actual_y]); if (Double.isInfinite(loglikelihood)) { System.out.println(Arrays.toString(predicted_distribution)); System.out.println(possibleUnitActionIndexes); System.out.println(actual_y + " : " + allPossibleActions.get(actual_y)); System.exit(1); } fold_loglikelihood_per_unit[u.getType().ID] += loglikelihood; // System.out.println(loglikelihood + "\t" + loglikelihood_nocorrection); } } double fold_accuracy_per_unit[] = new double[utt.getUnitTypes().size()]; if (DEBUG) System.out.println("Average possible actions: " + numPossibleActionsAccum/X_test.size()); for(int i = 0;i<utt.getUnitTypes().size();i++) { fold_accuracy_per_unit[i] = fold_correct_per_unit[i]/(double)fold_total_per_unit[i]; if (DEBUG) System.out.println("Fold accuracy ("+utt.getUnitTypes().get(i).name+"): " + fold_accuracy_per_unit[i] + " (" + fold_correct_per_unit[i] + "/" + fold_total_per_unit[i] + ")"); correct_per_unit[i] += fold_correct_per_unit[i]; total_per_unit[i] += fold_total_per_unit[i]; } for(int i = 0;i<utt.getUnitTypes().size();i++) { if (DEBUG) System.out.println("Fold loglikelihood ("+utt.getUnitTypes().get(i).name+"): " + fold_loglikelihood_per_unit[i] + " (average: " + fold_loglikelihood_per_unit[i]/fold_total_per_unit[i] + ")"); loglikelihood_per_unit[i] += fold_loglikelihood_per_unit[i]; } } if (DEBUG) System.out.println(" ---------- "); double correct = 0; double total = 0; double loglikelihood = 0; for(int i = 0;i<utt.getUnitTypes().size();i++) { double accuracy_per_unit = correct_per_unit[i]/(double)total_per_unit[i]; if (DEBUG) System.out.println("Final accuracy ("+utt.getUnitTypes().get(i).name+"): " + accuracy_per_unit + " (" + correct_per_unit[i] + "/" + total_per_unit[i] + ")"); correct += correct_per_unit[i]; total += total_per_unit[i]; } for(int i = 0;i<utt.getUnitTypes().size();i++) { if (DEBUG) System.out.println("Final loglikelihood ("+utt.getUnitTypes().get(i).name+"): " + loglikelihood_per_unit[i] + " (average: " + loglikelihood_per_unit[i]/total_per_unit[i] + ")"); loglikelihood += loglikelihood_per_unit[i]; } double accuracy = correct/total; if (DEBUG) System.out.println("Final accuracy: " + accuracy); if (DEBUG) System.out.println("Final loglikelihood: " + loglikelihood + " (average " + (loglikelihood/total) + ")"); // return accuracy; return loglikelihood/total; } public static List<UnitAction> generateAllPossibleUnitActions(UnitTypeTable utt) { List<UnitAction> l = new ArrayList<>(); int directions[] = {UnitAction.DIRECTION_UP, UnitAction.DIRECTION_RIGHT, UnitAction.DIRECTION_DOWN, UnitAction.DIRECTION_LEFT}; l.add(new UnitAction(UnitAction.TYPE_NONE, 10)); for(int d:directions) l.add(new UnitAction(UnitAction.TYPE_MOVE, d)); for(int d:directions) l.add(new UnitAction(UnitAction.TYPE_HARVEST, d)); for(int d:directions) l.add(new UnitAction(UnitAction.TYPE_RETURN, d)); for(int d:directions) { for(UnitType ut:utt.getUnitTypes()) l.add(new UnitAction(UnitAction.TYPE_PRODUCE, d, ut)); } for(int ox = -3;ox<=3;ox++) { for(int oy = -3;oy<=3;oy++) { int d = (ox*ox) + (oy*oy); if (d>0 && d<=9) { l.add(new UnitAction(UnitAction.TYPE_ATTACK_LOCATION, ox, oy)); } } } return l; } }
16,240
52.60066
218
java
MicroRTS
MicroRTS-master/src/tests/rts/PhysicalGameStateTest.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tests.rts; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import rts.units.Unit; import rts.units.UnitTypeTable; import rts.PhysicalGameState; /** * * @author marcelo */ public class PhysicalGameStateTest { /** * Test of ResetAllUnitsHP method, of class PhysicalGameState. * @throws java.lang.Exception */ public void testResetAllUnitsHP() throws Exception { System.out.println("ResetAllUnitsHP"); byte[] encoded = Files.readAllBytes(Paths.get("utts/TestUnitTypeTable.json")); String jsonString = new String(encoded, StandardCharsets.UTF_8); UnitTypeTable utt = UnitTypeTable.fromJSON(jsonString); PhysicalGameState pgs = PhysicalGameState.load("maps/8x8/basesWorkers8x8.xml", utt); pgs.resetAllUnitsHP(); for(Unit u : pgs.getUnits()){ if (u.getHitPoints() != u.getType().hp) throw new Exception("testResetAllUnitsHP test failed!"); } } }
1,230
28.309524
108
java
MicroRTS
MicroRTS-master/src/tests/sockets/RunClientExample.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests.sockets; import ai.core.AI; import ai.*; import ai.socket.SocketAI; import gui.PhysicalGameStatePanel; import javax.swing.JFrame; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author santi * * Once you have the server running (for example, run "RunServerExample.java"), * set the proper IP and port in the variable below, and run this file. * One of the AIs (ai1) is run remotely using the server. * * Notice that as many AIs as needed can connect to the same server. For * example, uncomment line 44 below and comment 45, to see two AIs using the same server. * */ public class RunClientExample { public static void main(String args[]) throws Exception { String serverIP = "127.0.0.1"; int serverPort = 9898; UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load("maps/16x16/basesWorkers16x16.xml", utt); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; int PERIOD = 20; boolean gameover = false; // SocketAI.DEBUG = 1; // AI ai1 = new SocketAI(100,0, serverIP, serverPort, SocketAI.LANGUAGE_XML, utt); AI ai1 = new SocketAI(100,0, serverIP, serverPort, SocketAI.LANGUAGE_JSON, utt); // AI ai2 = new SocketAI(100,0, serverIP, serverPort, SocketAI.LANGUAGE_XML, utt); AI ai2 = new RandomBiasedAI(); ai1.reset(); ai2.reset(); JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640,false,PhysicalGameStatePanel.COLORSCHEME_BLACK); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do{ if (System.currentTimeMillis()>=nextTimeToUpdate) { PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); w.repaint(); nextTimeToUpdate+=PERIOD; } else { try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); } }
2,556
31.782051
115
java
MicroRTS
MicroRTS-master/src/tests/sockets/RunServerExample.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tests.sockets; import ai.abstraction.WorkerRush; import ai.core.AIWithComputationBudget; import ai.socket.JSONSocketWrapperAI; import rts.units.UnitTypeTable; /** * * @author santi * * Run this file first in the computer where you want the server to * be running. * */ public class RunServerExample { public static void main(String args[]) throws Exception { AIWithComputationBudget ai = new WorkerRush(new UnitTypeTable()); int port = 9898; // XMLSocketWrapperAI.DEBUG = 1; // XMLSocketWrapperAI.runServer(ai, port); JSONSocketWrapperAI.DEBUG = 1; JSONSocketWrapperAI.runServer(ai, port); } }
861
25.9375
79
java
MicroRTS
MicroRTS-master/src/tests/trace/TraceGenerationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests.trace; import ai.core.AI; import ai.abstraction.WorkerRush; import ai.*; import ai.abstraction.pathfinding.BFSPathFinding; import java.io.FileWriter; import java.io.Writer; import rts.*; import rts.units.UnitTypeTable; import tests.MapGenerator; import util.XMLWriter; /** * * @author santi */ public class TraceGenerationTest { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); MapGenerator mg = new MapGenerator(utt); PhysicalGameState pgs = mg.basesWorkers8x8Obstacle(); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; boolean gameover = false; AI ai1 = new RandomBiasedAI(); AI ai2 = new WorkerRush(utt, new BFSPathFinding()); Trace trace = new Trace(utt); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); do{ PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); if (!pa1.isEmpty() || !pa2.isEmpty()) { te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); XMLWriter xml = new XMLWriter(new FileWriter("trace.xml")); trace.toxml(xml); xml.flush(); Writer w = new FileWriter("trace.json"); trace.toJSON(w); w.flush(); } }
2,087
28.408451
87
java
MicroRTS
MicroRTS-master/src/tests/trace/TraceVisualizationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests.trace; import gui.TraceVisualizer; import java.io.FileInputStream; import java.util.zip.ZipInputStream; import javax.swing.*; import org.jdom.input.SAXBuilder; import rts.*; /** * * @author santi */ public class TraceVisualizationTest { public static void main(String []args) throws Exception { boolean zip = false; Trace t; if(zip){ ZipInputStream zipIs=new ZipInputStream(new FileInputStream(args[0])); zipIs.getNextEntry(); t = new Trace(new SAXBuilder().build(zipIs).getRootElement()); }else{ t = new Trace(new SAXBuilder().build(args[0]).getRootElement()); } JFrame tv = TraceVisualizer.newWindow("Demo", 800, 600, t, 1); tv.show(); System.out.println("Trace winner: " + t.winner()); } }
891
20.756098
74
java
MicroRTS
MicroRTS-master/src/tests/trace/ZipTraceGenerationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests.trace; import ai.core.AI; import ai.abstraction.WorkerRush; import ai.*; import ai.abstraction.pathfinding.BFSPathFinding; import rts.*; import rts.units.UnitTypeTable; import tests.MapGenerator; /** * * @author santi */ public class ZipTraceGenerationTest { public static void main(String[] args) throws Exception { UnitTypeTable utt = new UnitTypeTable(); MapGenerator mg = new MapGenerator(utt); PhysicalGameState pgs = mg.basesWorkers8x8Obstacle(); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 5000; boolean gameover = false; AI ai1 = new RandomBiasedAI(); AI ai2 = new WorkerRush(utt, new BFSPathFinding()); Trace trace = new Trace(utt); TraceEntry te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); trace.addEntry(te); do{ PlayerAction pa1 = ai1.getAction(0, gs); PlayerAction pa2 = ai2.getAction(1, gs); if (!pa1.isEmpty() || !pa2.isEmpty()) { te = new TraceEntry(gs.getPhysicalGameState().clone(),gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); }while(!gameover && gs.getTime()<MAXCYCLES); ai1.gameOver(gs.winner()); ai2.gameOver(gs.winner()); te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); trace.toZip("trace.zip"); System.out.println("Done."); } }
1,872
28.265625
87
java
MicroRTS
MicroRTS-master/src/tests/trace/ZipTraceVisualizationTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tests.trace; import javax.swing.JFrame; import gui.TraceVisualizer; import rts.Trace; /** * * @author santi */ public class ZipTraceVisualizationTest { public static void main(String []args) throws Exception { Trace t = Trace.fromZip(args[0]); JFrame tv = TraceVisualizer.newWindow("Demo", 800, 600, t, 1); tv.show(); System.out.println("Trace winner: " + t.winner()); } }
530
17.964286
65
java
MicroRTS
MicroRTS-master/src/tournaments/FixedOpponentsTournament.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tournaments; import ai.core.AI; import java.io.File; import java.io.Writer; import java.util.List; import rts.PhysicalGameState; import rts.units.UnitTypeTable; /** * * @author santi * @author douglasrizzo */ public class FixedOpponentsTournament extends Tournament { public FixedOpponentsTournament(List<AI> AIs, List<AI> opponentAIs) { super(AIs, opponentAIs); } public void runTournament(List<String> maps, int iterations, int maxGameLength, int timeBudget, int iterationsBudget, long preAnalysisBudgetFirstTimeInAMap, long preAnalysisBudgetRestOfTimes, boolean fullObservability, boolean timeoutCheck, boolean runGC, boolean preAnalysis, UnitTypeTable utt, String traceOutputfolder, Writer out, Writer progress, String folderForReadWriteFolders) throws Exception { if (progress != null) { progress.write(getClass().getName()+": Starting tournament\n"); } out.write(getClass().getName()+"\n"); out.write("AIs\n"); for (AI ai : AIs) { out.write("\t" + ai.toString() + "\n"); } out.write("opponent AIs\n"); for (AI opponentAI : opponentAIs) { out.write("\t" + opponentAI.toString() + "\n"); } out.write("maps\n"); for (String map : maps) { out.write("\t" + map + "\n"); } out.write("iterations\t" + iterations + "\n"); out.write("maxGameLength\t" + maxGameLength + "\n"); out.write("timeBudget\t" + timeBudget + "\n"); out.write("iterationsBudget\t" + iterationsBudget + "\n"); out.write("fullObservability\t" + fullObservability + "\n"); out.write("timeoutCheck\t" + timeoutCheck + "\n"); out.write("runGC\t" + runGC + "\n"); out.write("iteration\tmap\tai1\tai2\ttime\twinner\tcrashed\ttimedout\n"); out.flush(); // create all the read/write folders: String readWriteFolders[] = new String[AIs.size()]; for (int i = 0; i < AIs.size(); i++) { readWriteFolders[i] = folderForReadWriteFolders + "/AI" + i + "readWriteFolder"; File f = new File(readWriteFolders[i]); f.mkdir(); } boolean firstPreAnalysis[][] = new boolean[AIs.size()][maps.size()]; for (int i = 0; i < AIs.size(); i++) { for (int j = 0; j < maps.size(); j++) { firstPreAnalysis[i][j] = true; } } String opponentReadWriteFolders[] = new String[opponentAIs.size()]; for (int i = 0; i < opponentAIs.size(); i++) { opponentReadWriteFolders[i] = folderForReadWriteFolders + "/opponentAI" + i + "readWriteFolder"; File f = new File(opponentReadWriteFolders[i]); f.mkdir(); } boolean opponentFirstPreAnalysis[][] = new boolean[opponentAIs.size()][maps.size()]; for (int i = 0; i < opponentAIs.size(); i++) { for (int j = 0; j < maps.size(); j++) { opponentFirstPreAnalysis[i][j] = true; } } for (int iteration = 0; iteration < iterations; iteration++) { for (int map_idx = 0; map_idx < maps.size(); map_idx++) { PhysicalGameState pgs = PhysicalGameState.load(maps.get(map_idx), utt); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { playSingleGame(maxGameLength, timeBudget, iterationsBudget, preAnalysisBudgetFirstTimeInAMap, preAnalysisBudgetRestOfTimes, fullObservability, timeoutCheck, runGC, preAnalysis, utt, traceOutputfolder, out, progress, readWriteFolders, firstPreAnalysis, iteration, map_idx, pgs, ai1_idx, ai2_idx); } } } } printEndSummary(maps, iterations, out, progress); } }
4,666
38.550847
140
java
MicroRTS
MicroRTS-master/src/tournaments/LoadTournamentAIs.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tournaments; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import ai.core.AIWithComputationBudget; /** * * @author santi */ public class LoadTournamentAIs { public static List<Class> loadTournamentAIsFromFolder(String path) throws Exception { List<Class> cl = new ArrayList<>(); File f = new File(path); if (f.isDirectory()) { for(File f2:f.listFiles()) { if (f2.getName().endsWith(".jar")) { cl.addAll(loadTournamentAIsFromJAR(f2.getAbsolutePath())); } } } return cl; } public static List<Class> loadTournamentAIsFromJAR(String jarPath) throws IOException, ClassNotFoundException { ClassLoader loader = URLClassLoader.newInstance(new URL[]{new File(jarPath).toURI().toURL()}, LoadTournamentAIs.class.getClassLoader() ); List<Class> cs = new ArrayList<>(); URL jar = new File(jarPath).toURI().toURL(); ZipInputStream zip = new ZipInputStream(jar.openStream()); while(true) { ZipEntry e = zip.getNextEntry(); if (e == null) break; String name = e.getName(); if (name.endsWith(".class")) { try { Class<?> c = loader.loadClass(name.substring(0, name.length() - 6).replace('/', '.')); if (!Modifier.isAbstract(c.getModifiers()) && isTournamentAIClass(c)) cs.add(c); } catch (final NoClassDefFoundError error) { System.err.println("Skipping class which could not be loaded: " + name); if (name.equals("org/jdom/xpath/JaxenXPath$NSContext.class")) { System.err.println("NOTE: this is a common error when packaging all of MicroRTS inside the .jar file with your bot(s)!"); } } } } return cs; } public static boolean isTournamentAIClass(Class c) { if (c == AIWithComputationBudget.class) return true; c = c.getSuperclass(); if (c!=null) return isTournamentAIClass(c); return false; } }
2,620
32.177215
136
java
MicroRTS
MicroRTS-master/src/tournaments/RoundRobinTournament.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tournaments; import ai.core.AI; import java.io.File; import java.io.Writer; import java.util.List; import rts.PhysicalGameState; import rts.units.UnitTypeTable; /** * * @author santi * @author douglasrizzo */ public class RoundRobinTournament extends Tournament{ public RoundRobinTournament(List<AI> AIs) { super(AIs); } public void runTournament(int playOnlyGamesInvolvingThisAI, List<String> maps, int iterations, int maxGameLength, int timeBudget, int iterationsBudget, long preAnalysisBudgetFirstTimeInAMap, long preAnalysisBudgetRestOfTimes, boolean fullObservability, boolean selfMatches, boolean timeoutCheck, boolean runGC, boolean preAnalysis, UnitTypeTable utt, String traceOutputfolder, Writer out, Writer progress, String folderForReadWriteFolders) throws Exception { if (progress != null) { progress.write(getClass().getName()+": Starting tournament\n"); } out.write(getClass().getName()+"\n"); out.write("AIs\n"); for (AI ai : AIs) { out.write("\t" + ai.toString() + "\n"); } out.write("maps\n"); for (String map : maps) { out.write("\t" + map + "\n"); } out.write("iterations\t" + iterations + "\n"); out.write("maxGameLength\t" + maxGameLength + "\n"); out.write("timeBudget\t" + timeBudget + "\n"); out.write("iterationsBudget\t" + iterationsBudget + "\n"); out.write("pregameAnalysisBudget\t" + preAnalysisBudgetFirstTimeInAMap + "\t" + preAnalysisBudgetRestOfTimes + "\n"); out.write("preAnalysis\t" + preAnalysis + "\n"); out.write("fullObservability\t" + fullObservability + "\n"); out.write("timeoutCheck\t" + timeoutCheck + "\n"); out.write("runGC\t" + runGC + "\n"); out.write("iteration\tmap\tai1\tai2\ttime\twinner\tcrashed\ttimedout\n"); out.flush(); // create all the read/write folders: String readWriteFolders[] = new String[AIs.size()]; for(int i = 0;i<AIs.size();i++) { readWriteFolders[i] = folderForReadWriteFolders + "/AI" + i + "readWriteFolder"; File f = new File(readWriteFolders[i]); f.mkdir(); } boolean firstPreAnalysis[][] = new boolean[AIs.size()][maps.size()]; for (int i = 0; i < AIs.size(); i++) { for (int j = 0; j < maps.size(); j++) { firstPreAnalysis[i][j] = true; } } for (int iteration = 0; iteration < iterations; iteration++) { for (int map_idx = 0; map_idx < maps.size(); map_idx++) { PhysicalGameState pgs = PhysicalGameState.load(maps.get(map_idx), utt); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < AIs.size(); ai2_idx++) { if (!selfMatches && ai1_idx == ai2_idx) continue; if (playOnlyGamesInvolvingThisAI != -1) { if (ai1_idx != playOnlyGamesInvolvingThisAI && ai2_idx != playOnlyGamesInvolvingThisAI) continue; } playSingleGame(maxGameLength, timeBudget, iterationsBudget, preAnalysisBudgetFirstTimeInAMap, preAnalysisBudgetRestOfTimes, fullObservability, timeoutCheck, runGC, preAnalysis, utt, traceOutputfolder, out, progress, readWriteFolders, firstPreAnalysis, iteration, map_idx, pgs, ai1_idx, ai2_idx); } } } } printEndSummary(maps,iterations, out, progress); } }
4,452
40.616822
125
java
MicroRTS
MicroRTS-master/src/tournaments/Tournament.java
package tournaments; import ai.core.AI; import ai.core.AIWithComputationBudget; import ai.core.ContinuingAI; import ai.core.InterruptibleAI; import rts.GameState; import rts.PartiallyObservableGameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.Trace; import rts.TraceEntry; import rts.units.UnitTypeTable; import util.XMLWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author douglasrizzo */ class Tournament { private static int TIMEOUT_CHECK_TOLERANCE = 20; private static boolean USE_CONTINUING_ON_INTERRUPTIBLE = true; List<AI> AIs; List<AI> opponentAIs; private int[][] wins; private int[][] ties; private int[][] AIcrashes; private int[][] opponentAIcrashes; private int[][] AItimeout; private int[][] opponentAItimeout; private double[][] accumTime; Tournament(List<AI> AIs, List<AI> opponentAIs){ this.AIs = AIs; this.opponentAIs = opponentAIs; wins = new int[AIs.size()][opponentAIs.size()]; ties = new int[AIs.size()][opponentAIs.size()]; AIcrashes = new int[AIs.size()][opponentAIs.size()]; opponentAIcrashes = new int[AIs.size()][opponentAIs.size()]; AItimeout = new int[AIs.size()][opponentAIs.size()]; opponentAItimeout = new int[AIs.size()][opponentAIs.size()]; accumTime = new double[AIs.size()][opponentAIs.size()]; } Tournament(List<AI> AIs){ this(AIs, AIs); } void playSingleGame(int maxGameLength, int timeBudget, int iterationsBudget, long preAnalysisBudgetFirstTimeInAMap, long preAnalysisBudgetRestOfTimes, boolean fullObservability, boolean timeoutCheck, boolean runGC, boolean preAnalysis, UnitTypeTable utt, String traceOutputfolder, Writer out, Writer progress, String[] readWriteFolders, boolean[][] firstPreAnalysis, int iteration, int map_idx, PhysicalGameState pgs, int ai1_idx, int ai2_idx) throws Exception { // variables to keep track of time ussage amongst the AIs: int numTimes1 = 0; int numTimes2 = 0; double averageTime1 = 0; double averageTime2 = 0; int numberOfTimeOverBudget1 = 0; int numberOfTimeOverBudget2 = 0; double averageTimeOverBudget1 = 0; double averageTimeOverBudget2 = 0; int numberOfTimeOverTwiceBudget1 = 0; int numberOfTimeOverTwiceBudget2 = 0; double averageTimeOverTwiceBudget1 = 0; double averageTimeOverTwiceBudget2 = 0; AI ai1 = this.AIs.get(ai1_idx).clone(); AI ai2 = this.opponentAIs.get(ai2_idx).clone(); if (ai1 instanceof AIWithComputationBudget) { ((AIWithComputationBudget) ai1).setTimeBudget(timeBudget); ((AIWithComputationBudget) ai1).setIterationsBudget(iterationsBudget); } if (ai2 instanceof AIWithComputationBudget) { ((AIWithComputationBudget) ai2).setTimeBudget(timeBudget); ((AIWithComputationBudget) ai2).setIterationsBudget(iterationsBudget); } if (USE_CONTINUING_ON_INTERRUPTIBLE) { if (ai1 instanceof InterruptibleAI) ai1 = new ContinuingAI(ai1); if (ai2 instanceof InterruptibleAI) ai2 = new ContinuingAI(ai2); } ai1.reset(); ai2.reset(); GameState gs = new GameState(pgs.clone(), utt); if (progress != null) progress.write("MATCH UP: " + ai1 + " vs " + ai2 + "\n"); if (preAnalysis && firstPreAnalysis != null) { preAnalysisSingleAI(preAnalysisBudgetFirstTimeInAMap, preAnalysisBudgetRestOfTimes, progress, readWriteFolders[ai1_idx], firstPreAnalysis[ai1_idx], map_idx, ai1, gs); preAnalysisSingleAI(preAnalysisBudgetFirstTimeInAMap, preAnalysisBudgetRestOfTimes, progress, readWriteFolders[ai2_idx], firstPreAnalysis[ai2_idx], map_idx, ai2, gs); } boolean gameover = false; int crashed = -1; int timedout = -1; Trace trace = null; TraceEntry te; if (traceOutputfolder != null) { trace = new Trace(utt); te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); } do { PlayerAction pa1 = null; PlayerAction pa2 = null; long AI1start = 0, AI2start = 0, AI1end = 0, AI2end = 0; if (runGC) System.gc(); try { AI1start = System.currentTimeMillis(); pa1 = ai1.getAction(0, fullObservability ? gs : new PartiallyObservableGameState(gs, 0)); AI1end = System.currentTimeMillis(); } catch (Exception e) { if (progress != null) { progress.write(e + "\n"); progress.write(Arrays.toString(e.getStackTrace()) + "\n"); } crashed = 0; break; } if (runGC) System.gc(); try { AI2start = System.currentTimeMillis(); pa2 = ai2.getAction(1, fullObservability ? gs : new PartiallyObservableGameState(gs, 1)); AI2end = System.currentTimeMillis(); } catch (Exception e) { if (progress != null) { progress.write(e + "\n"); progress.write(Arrays.toString(e.getStackTrace()) + "\n"); } crashed = 1; break; } { long AI1time = AI1end - AI1start; long AI2time = AI2end - AI2start; numTimes1++; numTimes2++; averageTime1 += AI1time; averageTime2 += AI2time; if (AI1time > timeBudget) { numberOfTimeOverBudget1++; averageTimeOverBudget1 += AI1time; if (AI1time > timeBudget * 2) { numberOfTimeOverTwiceBudget1++; averageTimeOverTwiceBudget1 += AI1time; } } if (AI2time > timeBudget) { numberOfTimeOverBudget2++; averageTimeOverBudget2 += AI2time; if (AI2time > timeBudget * 2) { numberOfTimeOverTwiceBudget2++; averageTimeOverTwiceBudget2 += AI2time; } } if (timeoutCheck) { if (AI1time > timeBudget + TIMEOUT_CHECK_TOLERANCE) { timedout = 0; break; } if (AI2time > timeBudget + TIMEOUT_CHECK_TOLERANCE) { timedout = 1; break; } } } if (traceOutputfolder != null && (!pa1.isEmpty() || !pa2.isEmpty())) { te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); te.addPlayerAction(pa1.clone()); te.addPlayerAction(pa2.clone()); trace.addEntry(te); } gs.issueSafe(pa1); gs.issueSafe(pa2); gameover = gs.cycle(); } while (!gameover && (gs.getTime() < maxGameLength)); if (traceOutputfolder != null) { File folder = new File(traceOutputfolder); if (!folder.exists()) folder.mkdirs(); te = new TraceEntry(gs.getPhysicalGameState().clone(), gs.getTime()); trace.addEntry(te); XMLWriter xml; ZipOutputStream zip = null; String filename = ai1_idx + "-vs-" + ai2_idx + "-" + map_idx + "-" + iteration; filename = filename.replace("/", ""); filename = filename.replace(")", ""); filename = filename.replace("(", ""); filename = traceOutputfolder + "/" + filename; zip = new ZipOutputStream(new FileOutputStream(filename + ".zip")); zip.putNextEntry(new ZipEntry("game.xml")); xml = new XMLWriter(new OutputStreamWriter(zip)); trace.toxml(xml); xml.flush(); zip.closeEntry(); zip.close(); } int winner = -1; if (crashed != -1) { winner = 1 - crashed; if (crashed == 0) { this.AIcrashes[ai1_idx][ai2_idx]++; } if (crashed == 1) { opponentAIcrashes[ai1_idx][ai2_idx]++; } } else if (timedout != -1) { winner = 1 - timedout; if (timedout == 0) { this.AItimeout[ai1_idx][ai2_idx]++; } if (timedout == 1) { this.opponentAItimeout[ai1_idx][ai2_idx]++; } } else { winner = gs.winner(); } ai1.gameOver(winner); ai2.gameOver(winner); out.write(iteration + "\t" + map_idx + "\t" + ai1_idx + "\t" + ai2_idx + "\t" + gs.getTime() + "\t" + winner + "\t" + crashed + "\t" + timedout + "\n"); out.flush(); if (progress != null) { progress.write("Winner: " + winner + " in " + gs.getTime() + " cycles\n"); progress.write(ai1 + " : " + ai1.statisticsString() + "\n"); progress.write(ai2 + " : " + ai2.statisticsString() + "\n"); progress.write("AI1 time usage, average: " + (averageTime1 / numTimes1) + ", # times over budget: " + numberOfTimeOverBudget1 + " (avg " + (averageTimeOverBudget1 / numberOfTimeOverBudget1) + ") , # times over 2*budget: " + numberOfTimeOverTwiceBudget1 + " (avg " + (averageTimeOverTwiceBudget1 / numberOfTimeOverTwiceBudget1) + ")\n"); progress.write("AI2 time usage, average: " + (averageTime2 / numTimes2) + ", # times over budget: " + numberOfTimeOverBudget2 + " (avg " + (averageTimeOverBudget2 / numberOfTimeOverBudget2) + ") , # times over 2*budget: " + numberOfTimeOverTwiceBudget2 + " (avg " + (averageTimeOverTwiceBudget2 / numberOfTimeOverTwiceBudget2) + ")\n"); progress.flush(); } if (winner == -1) { this.ties[ai1_idx][ai2_idx]++; } else if (winner == 0) { this.wins[ai1_idx][ai2_idx]++; } else if (winner == 1) { } accumTime[ai1_idx][ai2_idx] += gs.getTime(); } private static void preAnalysisSingleAI(long preAnalysisBudgetFirstTimeInAMap, long preAnalysisBudgetRestOfTimes, Writer progress, String readWriteFolder, boolean[] firstPreAnalysis, int map_idx, AI ai1, GameState gs) throws Exception { long preTime1 = preAnalysisBudgetRestOfTimes; if (firstPreAnalysis[map_idx]) { preTime1 = preAnalysisBudgetFirstTimeInAMap; firstPreAnalysis[map_idx] = false; } long pre_start1 = System.currentTimeMillis(); ai1.preGameAnalysis(gs, preTime1, readWriteFolder); long pre_end1 = System.currentTimeMillis(); if (progress != null) { progress.write("preGameAnalysis player 1 took " + (pre_end1 - pre_start1) + "\n"); if ((pre_end1 - pre_start1) > preTime1) progress.write("TIMEOUT PLAYER 1!\n"); } } void printEndSummary(List<String> maps, int iterations, Writer out, Writer progress) throws IOException { out.write("Wins:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(wins[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.write("Ties:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(ties[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.write("Average Game Length:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(accumTime[ai1_idx][ai2_idx] / (maps.size() * iterations) + "\t"); } out.write("\n"); } out.write("AI crashes:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(AIcrashes[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.write("opponent AI crashes:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(opponentAIcrashes[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.write("AI timeout:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(AItimeout[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.write("opponent AI timeout:\n"); for (int ai1_idx = 0; ai1_idx < AIs.size(); ai1_idx++) { for (int ai2_idx = 0; ai2_idx < opponentAIs.size(); ai2_idx++) { out.write(opponentAItimeout[ai1_idx][ai2_idx] + "\t"); } out.write("\n"); } out.flush(); if (progress != null) progress.write(this.getClass().getName()+": tournament ended\n"); progress.flush(); } }
14,160
40.65
240
java
MicroRTS
MicroRTS-master/src/util/CartesianProduct.java
/* * This class was contributed by: Antonin Komenda, Alexander Shleyfman and Carmel Domshlak */ package util; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; public class CartesianProduct<E> { private final List<List<E>> domains = new ArrayList<>(); /** * Constructs a Cartesian product generator. * * @param definitionsOfDomains the inner set represent domain of i-th variable */ public CartesianProduct(List<Set<E>> definitionsOfDomains) { if(definitionsOfDomains.size() == 0) { throw new IllegalArgumentException("There has to be at least one domain!"); } for(Set<E> set : definitionsOfDomains) { domains.add(new ArrayList<>(set)); } } /** * Returns i-th element of the Cartesian product based on the domain definition. * * For all {@code i >= size()} the method returns {@code null}; * * @param i index * @return i-th particular element of the Cartesian product */ public List<E> element(int i) { LinkedList<E> result = new LinkedList<>(); for(List<E> currentDomain : domains) { int currentSize = currentDomain.size(); int currentIndex = i % currentSize; i /= currentSize; result.add(currentDomain.get(currentIndex)); } if(i > 0) { // index overflow => stop generating result = null; } return result; } /** * Returns the size of the Cartesian product, i.e., number of elements. * * @return size of the Cartesian product */ public int size() { int result = 1; for(List<E> currentDomain : domains) { result *= currentDomain.size(); } return result; } }
1,861
24.162162
90
java
MicroRTS
MicroRTS-master/src/util/Pair.java
package util; public class Pair<T1,T2> { public T1 m_a; public T2 m_b; public Pair(T1 a,T2 b) { m_a = a; m_b = b; } public String toString() { return "<" + m_a + "," + m_b + ">"; } }
235
12.882353
43
java
MicroRTS
MicroRTS-master/src/util/RunnableWithTimeOut.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package util; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * * This code was taken from this page: http://stackoverflow.com/questions/5715235/java-set-timeout-on-a-certain-block-of-code * From an answer from Neeme Praks * */ public class RunnableWithTimeOut { public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception { runWithTimeout(new Callable<Object>() { public Object call() throws Exception { runnable.run(); return null; } }, timeout, timeUnit); } public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<T> future = executor.submit(callable); executor.shutdown(); // This does not cancel the already-scheduled task. try { return future.get(timeout, timeUnit); } catch (TimeoutException e) { // remove this if you do not want to cancel the job in progress // or set the argument to 'false' if you do not want to interrupt the thread future.cancel(true); throw e; } catch (ExecutionException e) { // unwrap the root cause Throwable t = e.getCause(); if(t instanceof Error) { throw (Error) t; } else if(t instanceof Exception) { throw (Exception) e; } else { throw new IllegalStateException(t); } } } }
2,065
34.62069
126
java
MicroRTS
MicroRTS-master/src/util/Sampler.java
/******************************************************************************** Organization : Drexel University Institute : Computer Science Department Authors : Santiago Ontanon Class : Sampler Function : This class contains methods to sample from a given distribution. Including support for exploration vs exploitation. *********************************************************************************/ package util; import java.util.LinkedList; import java.util.List; import java.util.Random; public class Sampler { static Random generator = new Random(); /* * Returns a random element in the distribution */ public static int random(double[] distribution) { return generator.nextInt(distribution.length); } /* * Returns a random element in the distribution */ public static int random(List<Double> distribution) { return generator.nextInt(distribution.size()); } /* * Returns the element with maximum probability (ties are resolved randomly) */ public static int max(double[] distribution) throws Exception { List<Integer> best = new LinkedList<>(); double max = distribution[0]; for(int i = 0; i < distribution.length; i++) { double f = distribution[i]; if(f == max) { best.add(i); } else { if(f > max) { best.clear(); best.add(i); max = f; } } } if(best.size() > 0) { return best.get(generator.nextInt(best.size())); } throw new Exception("Input distribution empty in Sampler.max!"); } /* * Returns the element with maximum probability (ties are resolved randomly) */ public static int max(List<Double> distribution) throws Exception { List<Integer> best = new LinkedList<>(); double max = distribution.get(0); for(int i = 0; i < distribution.size(); i++) { double f = distribution.get(i); if(f == max) { best.add(i); } else { if(f > max) { best.clear(); best.add(i); max = f; } } } if(best.size() > 0) { return best.get(generator.nextInt(best.size())); } throw new Exception("Input distribution empty in Sampler.max!"); } /* * Returns the score with maximum probability (ties are resolved randomly) */ public static Double maxScore(double[] distribution) { List<Integer> best = new LinkedList<>(); double max = distribution[0]; for(int i = 0; i < distribution.length; i++) { double f = distribution[i]; if(f == max) { best.add(i); } else { if(f > max) { best.clear(); best.add(i); max = f; } } } return max; } /* * Returns an element in the distribution, using the weights as their relative probabilities */ public static int weighted(double[] distribution) throws Exception { double total = 0, accum = 0, tmp; for(double f : distribution) { total += f; } if(total == 0) return random(distribution); tmp = generator.nextDouble() * total; for(int i = 0; i < distribution.length; i++) { accum += distribution[i]; if(accum >= tmp) { return i; } } throw new Exception("Input distribution empty in Sampler.weighted!"); } /* * Returns an element in the distribution, using the weights as their relative probabilities */ public static Object weighted(List<Double> distribution, List<?> outputs) throws Exception { double total = 0, accum = 0, tmp; for(double f : distribution) { total += f; } if(total == 0) return outputs.get(generator.nextInt(outputs.size())); tmp = generator.nextDouble() * total; for(int i = 0; i < distribution.size(); i++) { accum += distribution.get(i); if(accum >= tmp) { return outputs.get(i); } } throw new Exception("Input distribution empty in Sampler.weighted!"); } /* * Returns an element in the distribution following the probabilities, but using 'e' as the exploration factor. * For instance: * If "e" = 1.0, then it has the same effect as the "max" method * If "e" = 0.5, then it has the same effect as the "weighted" method * If "e" = 0, then it has the same effect as the "random" method */ public static int explorationWeighted(double[] distribution, double e) throws Exception { /* * exponent = 1/(1-e)-1 */ double exponent = 0; double quotient = 1 - e; if(quotient != 0) { exponent = 1 / quotient - 1; } else { exponent = 1000; } double[] exponentiated = new double[distribution.length]; for(int i = 0; i < distribution.length; i++) { exponentiated[i] = Math.pow(distribution[i], exponent); } return weighted(exponentiated); } public static int eGreedy(List<Double> distribution, double e) throws Exception { if(generator.nextDouble() < e) { // explore: return random(distribution); } else { // exploit: return max(distribution); } } /* // Example: public static void main(String args[]) { int histo[] = {0, 0, 0, 0, 0}; List<Double> d = new LinkedList<Double>(); d.add(0.1); d.add(0.5); d.add(0.89); d.add(0.9); d.add(0.9); try { for (int i = 0; i < 1000; i++) { histo[random(d)]++; } System.out.println("Random: [" + histo[0] + "," + histo[1] + "," + histo[2] + "," + histo[3] + "," + histo[4] + "]"); histo[0] = histo[1] = histo[2] = histo[3] = histo[4] = 0; for (int i = 0; i < 1000; i++) { histo[max(d)]++; } System.out.println("Max: [" + histo[0] + "," + histo[1] + "," + histo[2] + "," + histo[3] + "," + histo[4] + "]"); histo[0] = histo[1] = histo[2] = histo[3] = histo[4] = 0; for (int i = 0; i < 1000; i++) { histo[weighted(d)]++; } System.out.println("Weighted: [" + histo[0] + "," + histo[1] + "," + histo[2] + "," + histo[3] + "," + histo[4] + "]"); histo[0] = histo[1] = histo[2] = histo[3] = histo[4] = 0; for (double e = 0; e <= 1.0; e += 0.015625) { for (int i = 0; i < 1000; i++) { histo[explorationWeighted(d, e)]++; } System.out.println("explorationWeighted(" + e + "): [" + histo[0] + "," + histo[1] + "," + histo[2] + "," + histo[3] + "," + histo[4] + "]"); histo[0] = histo[1] = histo[2] = histo[3] = histo[4] = 0; } } catch (Exception e) { e.printStackTrace(); } } */ }
7,668
29.799197
161
java
MicroRTS
MicroRTS-master/src/util/XMLWriter.java
package util; /* Copyright 2010 Santiago Ontanon and Ashwin Ram */ import java.io.IOException; import java.io.Writer; /** * XMLWriter is a class used to easily output XML. * * @author Andrew Trusty */ public class XMLWriter { private static final int tabsize = 2; private String lineSeparator = "\n"; /** * Number of spaces indentation currently being used. */ private int spaces; /** * The PrintWriter used to output the XML. */ private Writer writer; /** * XMLWriter constructor. * * @param w Writer to use for XML output. */ public XMLWriter(Writer w) { writer = w; spaces = 0; } /** * XMLWriter constructor. * * @param w Writer to use for XML output. * @param a_lineSeparator is the character to be used to separate lines */ public XMLWriter(Writer w, String a_lineSeparator) { writer = w; lineSeparator = a_lineSeparator; spaces = 0; } /** * Reset the number of spaces being used for indentation. */ public void resetTab() { spaces = 0; } /** * Increase the indentation by the tabsize. */ public void tab() { spaces += tabsize; } /** * Decrease the indentation by the tabsize. */ private void untab() { spaces -= tabsize; } /** * Write out indentation. */ private void indent() { for(int i = 0; i < spaces; ++i) try { writer.write(" "); } catch (IOException e) { e.printStackTrace(); } } /** * Set the number of tabs to use. * @param t the number of tabs */ public void setTab(int t) { if(t >= 0) spaces += t * tabsize; } /** * Public XML writing methods. */ public void tag(String tagname, Object val) { tag(tagname, val.toString()); } public void tag(String tagname, String value) { indent(); try { writer.write("<" + tagname + ">" + value + "</" + tagname + ">" + lineSeparator); } catch (IOException e) { e.printStackTrace(); } } public void tag(String tagname, int value) { tag(tagname, "" + value); } public void tag(String tagname, long value) { tag(tagname, "" + value); } public void tag(String tagname, double value) { tag(tagname, "" + value); } /** * Writes an opening or closing tag and increased or decreases the * indentation depending on if it is an opening or closing tag. * * @param tagname the tag to write, a closing tag should start with '/' */ public void tag(String tagname) { if(tagname.charAt(0) == '/') untab(); indent(); try { writer.write("<" + tagname + ">" + lineSeparator); } catch (IOException e) { e.printStackTrace(); } if(tagname.charAt(0) != '/') tab(); } public void tagWithAttributes(String tagname, String attributesString) { if(tagname.charAt(0) == '/') untab(); indent(); try { writer.write("<" + tagname + " " + attributesString + ">" + lineSeparator); } catch (IOException e) { e.printStackTrace(); } if(tagname.charAt(0) != '/') tab(); } /** * Writes the given string assuming it is raw XML. Appends a newline. * * @param xml string to write */ public void rawXML(String xml) { // indent(); try { writer.write(xml); } catch (IOException e) { e.printStackTrace(); } } /** * Close the Writer used to output the XML. */ public void close() { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Flush the XML output. */ public void flush() { try { writer.flush(); } catch (IOException e) { e.printStackTrace(); } } public Writer getWriter() { return writer; } }
4,277
20.938462
93
java
MicroRTS
MicroRTS-master/test/microrts/TestLoadingMaps.java
package microrts; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.List; import org.junit.Test; import rts.PhysicalGameState; import rts.units.UnitTypeTable; /** * Unit test to check that all map files can be loaded. * * @author Dennis Soemers */ public class TestLoadingMaps { @Test @SuppressWarnings("static-method") public void testLoadMaps() throws Exception { final UnitTypeTable utt = new UnitTypeTable(); final File mapsRootDir = new File("maps"); assertTrue(mapsRootDir.exists() && mapsRootDir.isDirectory()); final List<File> mapDirs = new ArrayList<File>(); mapDirs.add(mapsRootDir); while (!mapDirs.isEmpty()) { final File mapDir = mapDirs.remove(mapDirs.size() - 1); final File[] files = mapDir.listFiles(); for (final File file : files) { if (file.isDirectory()) { mapDirs.add(file); } else { final String path = file.getAbsolutePath(); if (!path.endsWith(".DS_Store")) { System.out.println("Testing map: " + path + "..."); assertTrue(path.endsWith(".xml")); assertNotNull(PhysicalGameState.load(path, utt)); } } } } } }
1,250
22.166667
64
java
null
wenet-main/runtime/android/app/src/androidTest/java/com/mobvoi/wenet/ExampleInstrumentedTest.java
package com.mobvoi.wenet; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.mobvoi.wenet", appContext.getPackageName()); } }
746
27.730769
93
java
null
wenet-main/runtime/android/app/src/main/java/com/mobvoi/wenet/MainActivity.java
package com.mobvoi.wenet; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Process; import android.util.Log; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class MainActivity extends AppCompatActivity { private final int MY_PERMISSIONS_RECORD_AUDIO = 1; private static final String LOG_TAG = "WENET"; private static final int SAMPLE_RATE = 16000; // The sampling rate private static final int MAX_QUEUE_SIZE = 2500; // 100 seconds audio, 1 / 0.04 * 100 private static final List<String> resource = Arrays.asList( "final.zip", "units.txt", "ctc.ort", "decoder.ort", "encoder.ort" ); private boolean startRecord = false; private AudioRecord record = null; private int miniBufferSize = 0; // 1280 bytes 648 byte 40ms, 0.04s private final BlockingQueue<short[]> bufferQueue = new ArrayBlockingQueue<>(MAX_QUEUE_SIZE); public static void assetsInit(Context context) throws IOException { AssetManager assetMgr = context.getAssets(); // Unzip all files in resource from assets to context. // Note: Uninstall the APP will remove the resource files in the context. for (String file : assetMgr.list("")) { if (resource.contains(file)) { File dst = new File(context.getFilesDir(), file); if (!dst.exists() || dst.length() == 0) { Log.i(LOG_TAG, "Unzipping " + file + " to " + dst.getAbsolutePath()); InputStream is = assetMgr.open(file); OutputStream os = new FileOutputStream(dst); byte[] buffer = new byte[4 * 1024]; int read; while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } os.flush(); } } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == MY_PERMISSIONS_RECORD_AUDIO) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i(LOG_TAG, "record permission is granted"); initRecorder(); } else { Toast.makeText(this, "Permissions denied to record audio", Toast.LENGTH_LONG).show(); Button button = findViewById(R.id.button); button.setEnabled(false); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestAudioPermissions(); try { assetsInit(this); } catch (IOException e) { Log.e(LOG_TAG, "Error process asset files to file path"); } TextView textView = findViewById(R.id.textView); textView.setText(""); Recognize.init(getFilesDir().getPath()); Button button = findViewById(R.id.button); button.setText("Start Record"); button.setOnClickListener(view -> { if (!startRecord) { startRecord = true; Recognize.reset(); startRecordThread(); startAsrThread(); Recognize.startDecode(); button.setText("Stop Record"); } else { startRecord = false; Recognize.setInputFinished(); button.setText("Start Record"); } button.setEnabled(false); }); } private void requestAudioPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO); } else { initRecorder(); } } private void initRecorder() { // buffer size in bytes 1280 miniBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (miniBufferSize == AudioRecord.ERROR || miniBufferSize == AudioRecord.ERROR_BAD_VALUE) { Log.e(LOG_TAG, "Audio buffer can't initialize!"); return; } record = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, miniBufferSize); if (record.getState() != AudioRecord.STATE_INITIALIZED) { Log.e(LOG_TAG, "Audio Record can't initialize!"); return; } Log.i(LOG_TAG, "Record init okay"); } private void startRecordThread() { new Thread(() -> { VoiceRectView voiceView = findViewById(R.id.voiceRectView); record.startRecording(); Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO); while (startRecord) { short[] buffer = new short[miniBufferSize / 2]; int read = record.read(buffer, 0, buffer.length); voiceView.add(calculateDb(buffer)); try { if (AudioRecord.ERROR_INVALID_OPERATION != read) { bufferQueue.put(buffer); } } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } Button button = findViewById(R.id.button); if (!button.isEnabled() && startRecord) { runOnUiThread(() -> button.setEnabled(true)); } } record.stop(); voiceView.zero(); }).start(); } private double calculateDb(short[] buffer) { double energy = 0.0; for (short value : buffer) { energy += value * value; } energy /= buffer.length; energy = (10 * Math.log10(1 + energy)) / 100; energy = Math.min(energy, 1.0); return energy; } private void startAsrThread() { new Thread(() -> { // Send all data while (startRecord || bufferQueue.size() > 0) { try { short[] data = bufferQueue.take(); // 1. add data to C++ interface Recognize.acceptWaveform(data); // 2. get partial result runOnUiThread(() -> { TextView textView = findViewById(R.id.textView); textView.setText(Recognize.getResult()); }); } catch (InterruptedException e) { Log.e(LOG_TAG, e.getMessage()); } } // Wait for final result while (true) { // get result if (!Recognize.getFinished()) { runOnUiThread(() -> { TextView textView = findViewById(R.id.textView); textView.setText(Recognize.getResult()); }); } else { runOnUiThread(() -> { Button button = findViewById(R.id.button); button.setEnabled(true); }); break; } } }).start(); } }
7,223
31.836364
95
java
null
wenet-main/runtime/android/app/src/main/java/com/mobvoi/wenet/Recognize.java
package com.mobvoi.wenet; public class Recognize { static { System.loadLibrary("wenet"); } public static native void init(String modelDir); public static native void reset(); public static native void acceptWaveform(short[] waveform); public static native void setInputFinished(); public static native boolean getFinished(); public static native void startDecode(); public static native String getResult(); }
434
24.588235
61
java
null
wenet-main/runtime/android/app/src/main/java/com/mobvoi/wenet/VoiceRectView.java
package com.mobvoi.wenet; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.util.AttributeSet; import android.view.View; import androidx.core.content.ContextCompat; import java.util.Arrays; /** * 自定义的音频模拟条形图 Created by shize on 2016/9/5. */ public class VoiceRectView extends View { // 音频矩形的数量 private int mRectCount; // 音频矩形的画笔 private Paint mRectPaint; // 渐变颜色的两种 private int topColor, downColor; // 音频矩形的宽和高 private int mRectWidth, mRectHeight; // 偏移量 private int offset; // 频率速度 private int mSpeed; private double[] mEnergyBuffer = null; public VoiceRectView(Context context) { this(context, null); } public VoiceRectView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VoiceRectView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setPaint(context, attrs); } public void setPaint(Context context, AttributeSet attrs) { // 将属性存储到TypedArray中 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.VoiceRect); mRectPaint = new Paint(); // 添加矩形画笔的基础颜色 mRectPaint.setColor(ta.getColor(R.styleable.VoiceRect_RectTopColor, ContextCompat.getColor(context, R.color.top_color))); // 添加矩形渐变色的上面部分 topColor = ta.getColor(R.styleable.VoiceRect_RectTopColor, ContextCompat.getColor(context, R.color.top_color)); // 添加矩形渐变色的下面部分 downColor = ta.getColor(R.styleable.VoiceRect_RectDownColor, ContextCompat.getColor(context, R.color.down_color)); // 设置矩形的数量 mRectCount = ta.getInt(R.styleable.VoiceRect_RectCount, 10); mEnergyBuffer = new double[mRectCount]; // 设置重绘的时间间隔,也就是变化速度 mSpeed = ta.getInt(R.styleable.VoiceRect_RectSpeed, 300); // 每个矩形的间隔 offset = ta.getInt(R.styleable.VoiceRect_RectOffset, 0); // 回收TypeArray ta.recycle(); } @Override protected void onSizeChanged(int w, int h, int oldW, int oldH) { super.onSizeChanged(w, h, oldW, oldH); // 渐变效果 LinearGradient mLinearGradient; // 画布的宽 int mWidth; // 获取画布的宽 mWidth = getWidth(); // 获取矩形的最大高度 mRectHeight = getHeight(); // 获取单个矩形的宽度(减去的部分为到右边界的间距) mRectWidth = (mWidth - offset) / mRectCount; // 实例化一个线性渐变 mLinearGradient = new LinearGradient( 0, 0, mRectWidth, mRectHeight, topColor, downColor, Shader.TileMode.CLAMP ); // 添加进画笔的着色器 mRectPaint.setShader(mLinearGradient); } public void add(double energy) { if (mEnergyBuffer.length - 1 >= 0) { System.arraycopy(mEnergyBuffer, 1, mEnergyBuffer, 0, mEnergyBuffer.length - 1); } mEnergyBuffer[mEnergyBuffer.length - 1] = energy; } public void zero() { Arrays.fill(mEnergyBuffer, 0); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); double mRandom; float currentHeight; for (int i = 0; i < mRectCount; i++) { // 由于只是简单的案例就不监听音频输入,随机模拟一些数字即可 mRandom = Math.random(); //if (i < 1 || i > mRectCount - 2) mRandom = 0; currentHeight = (float) (mRectHeight * mEnergyBuffer[i]); // 矩形的绘制是从左边开始到上、右、下边(左右边距离左边画布边界的距离,上下边距离上边画布边界的距离) canvas.drawRect( (float) (mRectWidth * i + offset), (mRectHeight - currentHeight) / 2, (float) (mRectWidth * (i + 1)), mRectHeight / 2 + currentHeight / 2, mRectPaint ); } // 使得view延迟重绘 postInvalidateDelayed(mSpeed); } }
3,672
26.207407
85
java
null
wenet-main/runtime/android/app/src/test/java/com/mobvoi/wenet/ExampleUnitTest.java
package com.mobvoi.wenet; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
377
21.235294
81
java
multeval
multeval-master/src/jbleu/JBLEU.java
package jbleu; import java.util.*; import jbleu.util.*; import com.google.common.base.*; import com.google.common.collect.*; // this is a reimplementation of NIST's MT eval 13b // minus the problematic pre-processing and SGML handling public class JBLEU { // TODO: Support BLEU other than BLEU=4 private static final int N = 4; public static final String VERSION = "0.1.1"; public int verbosity = 0; public JBLEU() { } public JBLEU(int verbosity) { this.verbosity = verbosity; } public static int pickReference(List<String> hyp, List<List<String>> refs, int verbosity) { int hypLen = hyp.size(); int selectedRefLen = Integer.MAX_VALUE; int selectedRef = -1; // TODO: "Closest" or "least harsh"? // TODO: Use "least harsh" to break ties betweeen references of equal closeness... int curDist = Integer.MAX_VALUE; int i = 0; for(List<String> ref : refs) { // for now, always use closest ref int myDist = Math.abs(hypLen - ref.size()); if (myDist < curDist) { selectedRefLen = ref.size(); selectedRef = i; curDist = myDist; } else if (myDist == curDist) { // break ties based on having a more optimistic brevity penalty (shorter reference) if (ref.size() < selectedRefLen) { selectedRefLen = ref.size(); selectedRef = i; curDist = myDist; if (verbosity >= 2) { System.err.println(String.format("jBLEU: Picking more optimistic reference for brevity penalty: hyp_len = %d; ref_len = %d; distance = %d", hypLen, ref.size(), myDist)); } } } i++; } return selectedRef; } public void stats(List<String> hyp, List<List<String>> refs, int[] result) { assert result.length == 9; assert refs.size() > 0; // 1) choose reference length int selectedRef = pickReference(hyp, refs, verbosity); int selectedRefLen = refs.get(selectedRef).size(); // TODO: Integer-ify everything inside Ngram? Or is there too much // overhead there? // 2) determine the bag of n-grams we can score against // build a simple tries Multiset<Ngram> clippedRefNgrams = HashMultiset.create(); for(List<String> ref : refs) { Multiset<Ngram> refNgrams = HashMultiset.create(); for(int order = 1; order <= N; order++) { for(int i = 0; i <= ref.size() - order; i++) { List<String> toks = ref.subList(i, i + order); Ngram ngram = new Ngram(toks); refNgrams.add(ngram); } } // clip n-grams by taking the maximum number of counts for any given reference for(Ngram ngram : refNgrams) { int clippedCount = Math.max(refNgrams.count(ngram), clippedRefNgrams.count(ngram)); clippedRefNgrams.setCount(ngram, clippedCount); } } // 3) now match n-grams int[] attempts = new int[N]; int[] matches = new int[N]; for(int order = 1; order <= N; order++) { for(int i = 0; i <= hyp.size() - order; i++) { List<String> toks = hyp.subList(i, i + order); Ngram ngram = new Ngram(toks); boolean found = clippedRefNgrams.remove(ngram); ++attempts[order - 1]; if (found) { ++matches[order - 1]; } } } // 4) assign sufficient stats System.arraycopy(attempts, 0, result, 0, N); System.arraycopy(matches, 0, result, N, N); result[N*2] = selectedRefLen; } private static double getAttemptedNgrams(int[] suffStats, int j) { return suffStats[j]; } private static double getMatchingNgrams(int[] suffStats, int j) { return suffStats[j + N]; } private static double getRefWords(int[] suffStats) { return suffStats[N * 2]; } public double score(int[] suffStats) { return score(suffStats, null); } // ############################################################################################################################### // # Default method used to compute the BLEU score, using smoothing. // # Note that the method used can be overridden using the '--no-smoothing' // command-line argument // # The smoothing is computed by taking 1 / ( 2^k ), instead of 0, for each // precision score whose matching n-gram count is null // # k is 1 for the first 'n' value for which the n-gram match count is null // # For example, if the text contains: // # - one 2-gram match // # - and (consequently) two 1-gram matches // # the n-gram count for each individual precision score would be: // # - n=1 => prec_count = 2 (two unigrams) // # - n=2 => prec_count = 1 (one bigram) // # - n=3 => prec_count = 1/2 (no trigram, taking 'smoothed' value of 1 / ( // 2^k ), with k=1) // # - n=4 => prec_count = 1/4 (no fourgram, taking 'smoothed' value of 1 / // ( 2^k ), with k=2) // ############################################################################################################################### // segment-level bleu smoothing is done by default and is similar to that of // bleu-1.04.pl (IBM) // // if allResults is non-null it must be of length N+1 and it // will contain bleu1, bleu2, bleu3, bleu4, brevity penalty public double score(int[] suffStats, double[] allResults) { Preconditions.checkArgument(suffStats.length == N * 2 + 1, "BLEU sufficient stats must be of length N*2+1"); final double brevityPenalty; double refWords = getRefWords(suffStats); double hypWords = getAttemptedNgrams(suffStats, 0); if (hypWords < refWords) { brevityPenalty = Math.exp(1.0 - refWords / hypWords); } else { brevityPenalty = 1.0; } assert brevityPenalty >= 0.0; assert brevityPenalty <= 1.0; if (verbosity >= 1) { System.err.println(String.format("jBLEU: Brevity penalty = %.6f (ref_words = %.0f, hyp_words = %.0f)", brevityPenalty, refWords, hypWords)); } if (allResults != null) { assert allResults.length == N + 1; allResults[N] = brevityPenalty; } double score = 0.0; double smooth = 1.0; for(int j = 0; j < N; j++) { double attemptedNgramsJ = getAttemptedNgrams(suffStats, j); double matchingNgramsJ = getMatchingNgrams(suffStats, j); final double iscore; if (attemptedNgramsJ == 0) { iscore = 0.0; if (verbosity >= 1) System.err.println(String.format("jBLEU: %d-grams: raw 0/0 = 0 %%", j+1)); } else if (matchingNgramsJ == 0) { smooth *= 2; double smoothedPrecision = 1.0 / (smooth * attemptedNgramsJ); iscore = Math.log(smoothedPrecision); if (verbosity >= 1) System.err.println(String.format("jBLEU: %d-grams: %.0f/%.0f = %.2f %% (smoothed) :: raw = %.2f %%", j+1, matchingNgramsJ, attemptedNgramsJ, smoothedPrecision * 100, matchingNgramsJ / attemptedNgramsJ * 100)); } else { double precisionAtJ = matchingNgramsJ / attemptedNgramsJ; iscore = Math.log(precisionAtJ); if (verbosity >= 1) System.err.println(String.format("jBLEU: %d-grams: %.0f/%.0f = %.2f %% (unsmoothed)", j+1, matchingNgramsJ, attemptedNgramsJ, precisionAtJ * 100)); } // TODO: Allow non-uniform weights instead of just the "baseline" // 1/4 from Papenini double ngramOrderWeight = 0.25; score += iscore * ngramOrderWeight; if (allResults != null) { assert allResults.length == N + 1; allResults[j] = brevityPenalty * Math.exp(score); } // assert Math.exp(iscore * ngramOrderWeight) <= 1.0 : // String.format("ERROR for order %d-grams iscore: %f -> %f :: %s", // j+1, iscore, Math.exp(iscore * ngramOrderWeight), // Arrays.toString(suffStats)); // assert Math.exp(score * ngramOrderWeight) <= 1.0; } double totalScore = brevityPenalty * Math.exp(score); if (totalScore > 1.0) { System.err.println("BLEU: Thresholding out of range score: " + totalScore + "; stats: " + Arrays.toString(suffStats)); totalScore = 1.0; } else if (totalScore < 0.0) { System.err.println("BLEU: Thresholding out of range score: " + totalScore); totalScore = 0.0; } return totalScore; } public static int getSuffStatCount() { // attempted 1-4 gram counts // matching 1-4 gram counts // length of selected reference for brevity penalty return N * 2 + 1; } public static void main(String[] args) { JBLEU bleu = new JBLEU(); int[] result = new int[JBLEU.getSuffStatCount()]; List<String> hyp = Lists.newArrayList(Splitter.on(' ').split("This is a hypothesis sentence .")); List<List<String>> refs = new ArrayList<List<String>>(); refs.add(Lists.newArrayList(Splitter.on(' ').split("This is the first reference sentence ."))); refs.add(Lists.newArrayList(Splitter.on(' ').split("This is the second reference sentence ."))); bleu.stats(hyp, refs, result); System.err.println(Arrays.toString(result)); System.err.println(bleu.score(result)); } }
9,017
35.808163
230
java
multeval
multeval-master/src/jbleu/util/HashUtil.java
package jbleu.util; public class HashUtil { /* This method was written by Doug Lea with assistance from members of JCP * JSR-166 Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain As of 2010/06/11, this * method is identical to the (package private) hash method in OpenJDK 7's * java.util.HashMap class. It was in turn lifted from Google Guava's Hashing * class. */ static int smear(int hashCode) { hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4); } }
603
39.266667
79
java
multeval
multeval-master/src/jbleu/util/Ngram.java
package jbleu.util; import java.util.*; // TODO: Potentially use integers instead of Strings, if overhead is worth it public class Ngram { private List<String> toks; private int hash = 0; public Ngram(List<String> toks) { this.toks = toks; } public int hashCode() { if (hash == 0) { for(String tok : toks) { hash ^= HashUtil.smear(tok.hashCode()); } } return hash; } public boolean equals(Object obj) { if (obj instanceof Ngram) { // TODO: Slow Ngram other = (Ngram) obj; return toks.equals(other.toks); } else { throw new RuntimeException("Comparing n-gram to non-n-gram"); } } public String toString() { return toks.toString(); } }
737
18.421053
77
java
multeval
multeval-master/src/jbleu/util/TrieCursor.java
package jbleu.util; import java.util.*; public class TrieCursor<T, V> { public final V value; private Map<T, TrieCursor<T, V>> next; public TrieCursor(V value) { this.value = value; } // null if not found public TrieCursor<T, V> match(T ext) { if (next == null) { return null; } else { return next.get(ext); } } public TrieCursor<T, V> extend(T ext, V val) { if (next == null) { next = new HashMap<T, TrieCursor<T, V>>(); } TrieCursor<T, V> match = match(ext); if (match == null) { match = new TrieCursor<T, V>(val); next.put(ext, match); } return match; } public String toString() { return value.toString(); } }
716
17.384615
48
java
multeval
multeval-master/src/multeval/HypothesisManager.java
package multeval; import java.io.*; import java.util.*; import multeval.util.*; import com.google.common.base.*; import com.google.common.io.*; /** System index 0 is the baseline system. Sentences having extra whitespace have that whitespace normalized first during loadSentences() for both references and hypotheses. * * @author jon */ public class HypothesisManager { // indices: iHyp, iRef private List<List<String>> allRefs = new ArrayList<List<String>>(); // indices: iSys, oOpt, iHyp private List<List<List<String>>> allHyps = new ArrayList<List<List<String>>>(); private int numHyps = -1; private int numRefs = -1; private int numOptRuns = -1; private int numSystems = -1; public int getNumHyps() { return numHyps; } public int getNumOptRuns() { return numOptRuns; } public int getNumRefs() { return numRefs; } public void loadData(String[] hypFilesBaseline, String[][] hypFilesBySys, String[] refFiles) throws IOException { // first, load system hypotheses numSystems = hypFilesBySys.length + 1; // include baseline allHyps.clear(); loadHyps(hypFilesBaseline, "baseline"); for(int iSys = 0; iSys < hypFilesBySys.length; iSys++) { loadHyps(hypFilesBySys[iSys], "" + (iSys + 1)); } numRefs = refFiles.length; allRefs = loadRefs(refFiles, numHyps); } public static List<List<String>> loadRefs(String[] refFiles, int numHypsHint) throws IOException { // TODO: Auto-detect laced refs? List<List<String>> allRefs = new ArrayList<List<String>>(); int numRefs = refFiles.length; while(allRefs.size() <= numHypsHint) { allRefs.add(new ArrayList<String>(numRefs)); } for(String refFile : refFiles) { List<String> oneRefPerHyp = loadSentences(refFile, "non-laced references"); if (numHypsHint != oneRefPerHyp.size()) { throw new RuntimeException("Non-parallel inputs detected. Expected " + numHypsHint + " references, but got " + oneRefPerHyp.size()); } for(int iHyp = 0; iHyp < oneRefPerHyp.size(); iHyp++) { String ref = oneRefPerHyp.get(iHyp); allRefs.get(iHyp).add(ref); } } return allRefs; } private void loadHyps(String[] hypFiles, String sys) throws IOException { if (numOptRuns == -1) { numOptRuns = hypFiles.length; } else { if (numOptRuns != hypFiles.length) { throw new RuntimeException("Non-parallel number of optimization runs. Expected " + numOptRuns + " but got " + hypFiles.length); } } List<List<String>> sysHypsForAllOptRuns = new ArrayList<List<String>>(); allHyps.add(sysHypsForAllOptRuns); for(int iOpt = 0; iOpt < numOptRuns; iOpt++) { List<String> hypsForOptRun = loadSentences(hypFiles[iOpt], "Hypotheses for system " + sys + " opt run " + (iOpt + 1)); sysHypsForAllOptRuns.add(hypsForOptRun); if (numHyps == -1) { numHyps = hypsForOptRun.size(); } else { if (numHyps != hypsForOptRun.size()) { throw new RuntimeException("Non-parallel inputs detected. Expected " + numHyps + " hypotheses, but got " + hypsForOptRun.size()); } } } } public static List<String> loadSentences(String hypFile, String forWhat) throws IOException { File file = new File(hypFile); // TODO: Say what system (or reference) this is for System.err.println("Reading " + forWhat + " file " + file.getAbsolutePath()); List<String> sentences = Files.readLines(file, Charsets.UTF_8); // normalize any "double" whitespace, if it exists for(int i = 0; i < sentences.size(); i++) { String sent = sentences.get(i); sent = StringUtils.normalizeWhitespace(sent); // if(StringUtils.hasRedundantWhitespace(sent)) { // System.err.println("Normalizing extraneous whitespace: "); // // } sentences.set(i, sent); } return sentences; } public int getNumSystems() { return numSystems; } public List<String> getHypotheses(int iSys, int iOpt) { // TODO: More informative error messages w/ bounds checking return allHyps.get(iSys).get(iOpt); } public String getHypothesis(int iSys, int iOpt, int iHyp) { return getHypotheses(iSys, iOpt).get(iHyp); } public List<String> getReferences(int iHyp) { // TODO: More informative error messages w/ bounds checking return allRefs.get(iHyp); } public List<List<String>> getAllReferences() { return allRefs; } }
4,530
29.409396
173
java
multeval
multeval-master/src/multeval/Module.java
package multeval; import jannopts.ConfigurationException; import jannopts.Configurator; import java.io.FileNotFoundException; import java.io.IOException; public interface Module { public void run(Configurator opts) throws ConfigurationException, FileNotFoundException, IOException, InterruptedException; public Iterable<Class<?>> getDynamicConfigurables(); }
368
23.6
89
java
multeval
multeval-master/src/multeval/MultEval.java
package multeval; import jannopts.ConfigurationException; import jannopts.Configurator; import java.io.IOException; import java.io.FileInputStream; import java.util.Properties; import java.util.ArrayList; import java.util.List; import java.util.Map; import multeval.metrics.BLEU; import multeval.metrics.Length; import multeval.metrics.Metric; import multeval.metrics.TER; import com.google.common.collect.ImmutableMap; public class MultEval { // case sensitivity option? both? use punctuation? // report length! public static Map<String, Metric<?>> KNOWN_METRICS = ImmutableMap.<String, Metric<?>> builder() .put("bleu", new BLEU()) .put("meteor", new multeval.metrics.METEOR()) .put("ter", new TER()) .put("length", new Length()) .build(); static List<Metric<?>> loadMetrics(String[] metricNames, Configurator opts) throws ConfigurationException { // 1) activate config options so that we fail-fast List<Metric<?>> metrics = new ArrayList<Metric<?>>(); for (String metricName : metricNames) { System.err.println("Loading metric: " + metricName); Metric<?> metric = KNOWN_METRICS.get(metricName.toLowerCase()); if (metric == null) { throw new RuntimeException("Unknown metric: " + metricName + "; Known metrics are: " + KNOWN_METRICS.keySet()); } // add metric options on-the-fly as needed opts.activateDynamicOptions(metric.getClass()); metrics.add(metric); } // 2) load metric resources, etc. for (Metric<?> metric : metrics) { metric.configure(opts); } return metrics; } private static final ImmutableMap<String, Module> MODULES = new ImmutableMap.Builder<String, Module>().put("eval", new MultEvalModule()) .put("nbest", new NbestModule()) .build(); static int initThreads(final List<Metric<?>> metrics, int threads) { if (threads == 0) { threads = Runtime.getRuntime().availableProcessors(); } System.err.println("Using " + threads + " threads"); return threads; } private static String loadVersion() throws IOException { Properties props = new Properties(); FileInputStream in = new FileInputStream("constants"); props.load(in); in.close(); String version = props.getProperty("version"); return version; } public static void main(String[] args) throws ConfigurationException, IOException, InterruptedException { String version = loadVersion(); System.err.println(String.format("MultEval V%s\n", version) + "By Jonathan Clark\n" + "Using Libraries: METEOR (Michael Denkowski) and TER (Matthew Snover)\n"); if (args.length == 0 || !MODULES.keySet().contains(args[0])) { System.err.println("Usage: program <module_name> <module_options>"); System.err.println("Available modules: " + MODULES.keySet().toString()); System.exit(1); } else { String moduleName = args[0]; Module module = MODULES.get(moduleName); Configurator opts = new Configurator().withModuleOptions(moduleName, module.getClass()); // add "dynamic" options, which might be activated later // by the specified switch values for (Class<?> c : module.getDynamicConfigurables()) { opts.allowDynamicOptions(c); } try { opts.readFrom(args); opts.configure(module); } catch (ConfigurationException e) { opts.printUsageTo(System.err); System.err.println("ERROR: " + e.getMessage() + "\n"); System.exit(1); } module.run(opts); } } }
3,568
28.991597
105
java
multeval
multeval-master/src/multeval/MultEvalModule.java
package multeval; import jannopts.ConfigurationException; import jannopts.Configurator; import jannopts.Option; import jannopts.util.StringUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import multeval.ResultsManager.Type; import multeval.analysis.DiffRanker; import multeval.analysis.SentFormatter; import multeval.metrics.BLEU; import multeval.metrics.METEORStats; import multeval.metrics.Metric; import multeval.metrics.SuffStats; import multeval.metrics.TER; import multeval.output.AsciiTable; import multeval.output.LatexTable; import multeval.parallel.MetricWorkerPool; import multeval.significance.BootstrapResampler; import multeval.significance.StratifiedApproximateRandomizationTest; import multeval.util.CollectionUtils; import multeval.util.MathUtils; import multeval.util.SuffStatUtils; import multeval.util.Triple; import com.google.common.base.Stopwatch; import com.google.common.base.Supplier; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multiset; import com.google.common.collect.Multiset.Entry; public class MultEvalModule implements Module { @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level (Integer: 0-1)", defaultValue = "0") public int verbosity; @Option(shortName = "o", longName = "metrics", usage = "Space-delimited list of metrics to use. Any of: bleu, meteor, ter, length", defaultValue = "bleu meteor ter length", arrayDelim = " ") public String[] metricNames; @Option(shortName = "B", longName = "hyps-baseline", usage = "Space-delimited list of files containing tokenized, fullform hypotheses, one per line", arrayDelim = " ") public String[] hypFilesBaseline; // each element of the array is a system that the user designated with a // number. each string element contains a space-delimited list of // hypothesis files with each file containing hypotheses from one // optimizer run @Option(shortName = "H", longName = "hyps-sys", usage = "Space-delimited list of files containing tokenized, fullform hypotheses, one per line", arrayDelim = " ", numberable = true) public String[] hypFilesBySys; @Option(shortName = "R", longName = "refs", usage = "Space-delimited list of files containing tokenized, fullform references, one per line", arrayDelim = " ") public String[] refFiles; @Option(shortName = "b", longName = "boot-samples", usage = "Number of bootstrap replicas to draw during bootstrap resampling to estimate standard deviation for each system", defaultValue = "10000") private int numBootstrapSamples; @Option(shortName = "s", longName = "ar-shuffles", usage = "Number of shuffles to perform to estimate p-value during approximate randomization test system *PAIR*", defaultValue = "10000") private int numShuffles; @Option(shortName = "L", longName = "latex", usage = "Latex-formatted table including measures that are commonly (or should be commonly) reported", required = false) private String latexOutFile; @Option(shortName = "F", longName = "fullLatexDoc", usage = "Output a fully compilable Latex document instead of just the table alone", required = false, defaultValue = "false") private boolean fullLatexDoc; @Option(shortName = "r", longName = "rankDir", usage = "Rank hypotheses of median optimization run of each system with regard to improvement/decline over median baseline system and output to the specified directory for analysis", required = false) private String rankDir; @Option(shortName = "S", longName = "sentLevelDir", usage = "Score the hypotheses of each system at the sentence-level and output to the specified directory for analysis", required = false) private String sentLevelDir; @Option(shortName = "D", longName = "debug", usage = "Show debugging output?", required = false, defaultValue = "false") private boolean debug; @Option(shortName = "t", longName = "threads", usage = "How many threads should we use? Thread-unsafe metrics will be run in a separate thread. (Zero means all available cores)", required = false, defaultValue = "0") private int threads; // TODO: Lowercasing option @Override public Iterable<Class<?>> getDynamicConfigurables() { return ImmutableList.<Class<?>> of(BLEU.class, multeval.metrics.METEOR.class, TER.class); } @Override public void run(Configurator opts) throws ConfigurationException, FileNotFoundException, InterruptedException { List<Metric<?>> metrics = MultEval.loadMetrics(metricNames, opts); this.threads = MultEval.initThreads(metrics, threads); // 1) load hyps and references // first index is opt run, second is hyp int numSystems = hypFilesBySys == null ? 0 : hypFilesBySys.length; String[][] hypFilesBySysSplit = new String[numSystems][]; for (int i = 0; i < numSystems; i++) { hypFilesBySysSplit[i] = StringUtils.split(hypFilesBySys[i], " ", Integer.MAX_VALUE); } HypothesisManager data = new HypothesisManager(); try { data.loadData(hypFilesBaseline, hypFilesBySysSplit, refFiles); } catch (IOException e) { System.err.println("Error while loading data."); e.printStackTrace(); System.exit(1); } // 2) collect sufficient stats for each metric selected Stopwatch watch = new Stopwatch(); watch.start(); SuffStatManager suffStats = collectSuffStats(metrics, data); watch.stop(); System.err.println("Collected suff stats in " + watch.toString(3)); String[] metricNames = new String[metrics.size()]; for (int i = 0; i < metricNames.length; i++) { metricNames[i] = metrics.get(i).toString(); } String[] sysNames = new String[data.getNumSystems()]; sysNames[0] = "baseline"; for (int i = 1; i < sysNames.length; i++) { sysNames[i] = "system " + i; } ResultsManager results = new ResultsManager(metricNames, sysNames, data.getNumOptRuns()); // 3) evaluate each system and report the average scores runOverallEval(metrics, data, suffStats, results); runOOVAnalysis(metrics, data, suffStats, results); // output sentence-level scores, if requested runSentScores(metrics, data, suffStats, results); // run diff ranking, if requested (MUST be run after overall eval, // which computes median systems) runDiffRankEval(metrics, data, suffStats, results); // 4) run bootstrap resampling for each system, for each // optimization run watch.reset(); watch.start(); runBootstrapResampling(metrics, data, suffStats, results); watch.stop(); System.err.println("Performed bootstrap resampling in " + watch.toString(3)); // 5) run AR -- FOR EACH SYSTEM PAIR watch.reset(); watch.start(); runApproximateRandomization(metrics, data, suffStats, results); watch.stop(); if(data.getNumSystems() > 1) { System.err.println("Performed approximate randomization in " + watch.toString(3)); } // 6) output pretty table if (latexOutFile != null) { LatexTable table = new LatexTable(); File file = new File(latexOutFile); System.err.println("Writing Latex table to " + file.getAbsolutePath()); PrintWriter out = new PrintWriter(file); table.write(results, metrics, out, fullLatexDoc); out.close(); } AsciiTable table = new AsciiTable(); table.write(results, System.out); // 7) show statistics such as most frequent OOV's length, brevity // penalty, etc. } private void runSentScores(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) throws FileNotFoundException { if (sentLevelDir != null) { File dir = new File(sentLevelDir); dir.mkdirs(); System.err.println("Outputting sentence level scores to: " + dir.getAbsolutePath()); final String[] submetricNames = NbestModule.getSubmetricNames(metrics); SentFormatter formatter = new SentFormatter(metricNames, submetricNames); List<List<String>> refs = data.getAllReferences(); for (int iSys = 0; iSys < data.getNumSystems(); iSys++) { for (int iOpt = 0; iOpt < data.getNumOptRuns(); iOpt++) { File outFile = new File(dir, String.format("sys%d.opt%d", (iSys + 1), (iOpt+1))); double[][] sentMetricScores = getSentLevelScores(metrics, data, suffStats, iSys, iOpt); double[][] sentSubmetricScores = getSentLevelSubmetricScores(metrics, data, suffStats, iSys, iOpt); List<String> hyps = data.getHypotheses(iSys, iOpt); PrintWriter out = new PrintWriter(outFile); formatter.write(hyps, refs, sentMetricScores, sentSubmetricScores, out); out.close(); } } } } private void runDiffRankEval(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) throws FileNotFoundException { if (rankDir != null) { File rankOutDir = new File(rankDir); rankOutDir.mkdirs(); System.err.println("Outputting ranked hypotheses to: " + rankOutDir.getAbsolutePath()); DiffRanker ranker = new DiffRanker(metricNames); List<List<String>> refs = data.getAllReferences(); int iBaselineSys = 0; for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { int iBaselineMedianIdx = results.get(iMetric, iBaselineSys, Type.MEDIAN_IDX).intValue(); List<String> hypsMedianBaseline = data.getHypotheses(iBaselineSys, iBaselineMedianIdx); // we must always recalculate all metric scores since // the median system might change based on which metric // we're sorting by double[][] sentMetricScoresBaseline = getSentLevelScores(metrics, data, suffStats, iBaselineSys, iBaselineMedianIdx); for (int iSys = 1; iSys < data.getNumSystems(); iSys++) { File outFile = new File(rankOutDir, String.format("sys%d.sortedby.%s", (iSys + 1), metricNames[iMetric])); int iSysMedianIdx = results.get(iMetric, iSys, Type.MEDIAN_IDX).intValue(); List<String> hypsMedianSys = data.getHypotheses(iSys, iSysMedianIdx); double[][] sentMetricScoresSys = getSentLevelScores(metrics, data, suffStats, iSys, iSysMedianIdx); PrintWriter out = new PrintWriter(outFile); ranker.write(hypsMedianBaseline, hypsMedianSys, refs, sentMetricScoresBaseline, sentMetricScoresSys, iMetric, out); out.close(); } } } } private double[][] getSentLevelSubmetricScores(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, int iSys, int iOpt) { int nSubmetrics = 0; for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { nSubmetrics += metrics.get(iMetric).getSubmetricNames().length; } double[][] result = new double[data.getNumHyps()][nSubmetrics]; for (int iHyp = 0; iHyp < data.getNumHyps(); iHyp++) { int iSubmetric = 0; for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { Metric<?> metric = metrics.get(iMetric); SuffStats<?> stats = suffStats.getStats(iMetric, iSys, iOpt, iHyp); for (double sub : metric.scoreSubmetricsStats(stats)) { result[iHyp][iSubmetric] = sub; iSubmetric++; } } } return result; } private double[][] getSentLevelScores(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, int iSys, int iOpt) { double[][] result = new double[data.getNumHyps()][metrics.size()]; for (int iHyp = 0; iHyp < data.getNumHyps(); iHyp++) { for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { Metric<?> metric = metrics.get(iMetric); SuffStats<?> stats = suffStats.getStats(iMetric, iSys, iOpt, iHyp); result[iHyp][iMetric] = metric.scoreStats(stats); // System.err.println("hyp " + (iHyp + 1) + ": " + // result[iHyp][iMetric]); } } return result; } private void runApproximateRandomization(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) throws InterruptedException { int iBaselineSys = 0; for (int iSys = 1; iSys < data.getNumSystems(); iSys++) { System.err.println("Performing approximate randomization to estimate p-value between baseline system and system " + (iSys + 1) + " (of " + data.getNumSystems() + ")"); // index 1: metric, index 2: hypothesis, inner array: suff stats List<List<SuffStats<?>>> suffStatsBaseline = suffStats.getStatsAllOptForSys(iBaselineSys); List<List<SuffStats<?>>> suffStatsSysI = suffStats.getStatsAllOptForSys(iSys); StratifiedApproximateRandomizationTest ar = new StratifiedApproximateRandomizationTest(threads, metrics, suffStatsBaseline, suffStatsSysI, data.getNumHyps(), data.getNumOptRuns(), debug); double[] pByMetric = ar.getTwoSidedP(numShuffles); for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { results.report(iMetric, iSys, Type.P_VALUE, pByMetric[iMetric]); } } } private SuffStatManager collectSuffStats(List<Metric<?>> metrics, final HypothesisManager data) throws InterruptedException { final SuffStatManager suffStats = new SuffStatManager(metrics.size(), data.getNumSystems(), data.getNumOptRuns(), data.getNumHyps()); // parallelize at the hypothesis level for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { final int iMetricF = iMetric; final Metric<?> metricMaster = metrics.get(iMetric); System.err.println("Collecting sufficient statistics for metric: " + metricMaster.toString()); MetricWorkerPool<Triple<Integer, Integer, Integer>, Metric<?>> work = new MetricWorkerPool<Triple<Integer, Integer, Integer>, Metric<?>>( threads, new Supplier<Metric<?>>() { @Override public Metric<?> get() { return metricMaster.threadClone(); } }) { @Override public void doWork(Metric<?> metricCopy, Triple<Integer, Integer, Integer> trip) { int iSys = trip.first; int iOpt = trip.second; int iHyp = trip.third; String hyp = data.getHypothesis(iSys, iOpt, iHyp); List<String> refs = data.getReferences(iHyp); SuffStats<?> stats = metricCopy.stats(hyp, refs); suffStats.saveStats(iMetricF, iSys, iOpt, iHyp, stats); } }; work.start(); for (int iSys = 0; iSys < data.getNumSystems(); iSys++) { for (int iOpt = 0; iOpt < data.getNumOptRuns(); iOpt++) { for (int iHyp = 0; iHyp < data.getNumHyps(); iHyp++) { work.addTask(new Triple<Integer, Integer, Integer>(iSys, iOpt, iHyp)); } } } work.waitForCompletion(); System.err.println("Finished collecting sufficient statistics for metric: " + metricMaster.toString()); } return suffStats; } private void runOverallEval(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) { for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { Metric<?> metric = metrics.get(iMetric); System.err.println("Scoring with metric: " + metric.toString()); for (int iSys = 0; iSys < data.getNumSystems(); iSys++) { double[] scoresByOptRun = new double[data.getNumOptRuns()]; for (int iOpt = 0; iOpt < data.getNumOptRuns(); iOpt++) { List<SuffStats<?>> statsBySent = suffStats.getStats(iMetric, iSys, iOpt); SuffStats<?> corpusStats = SuffStatUtils.sumStats(statsBySent); scoresByOptRun[iOpt] = metric.scoreStats(corpusStats); if (verbosity >= 1) { // TODO: Logging framework rather than verbosity level System.err.println("RESULT: " + results.sysNames[iSys] + ": " + results.metricNames[iMetric] + ": OptRun " + iOpt + ": " + String.format("%.6f", scoresByOptRun[iOpt])); } } double avg = MathUtils.average(scoresByOptRun); double stddev = MathUtils.stddev(scoresByOptRun); double min = MathUtils.min(scoresByOptRun); double max = MathUtils.max(scoresByOptRun); int medianIdx = MathUtils.medianIndex(scoresByOptRun); double median = scoresByOptRun[medianIdx]; results.report(iMetric, iSys, Type.AVG, avg); results.report(iMetric, iSys, Type.MEDIAN, median); results.report(iMetric, iSys, Type.STDDEV, stddev); results.report(iMetric, iSys, Type.MIN, min); results.report(iMetric, iSys, Type.MAX, max); results.report(iMetric, iSys, Type.MEDIAN_IDX, medianIdx); } } } private void runOOVAnalysis(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) { for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { Metric<?> metric = metrics.get(iMetric); // just do this with METEOR since it's the most forgiving if (metric instanceof multeval.metrics.METEOR) { multeval.metrics.METEOR meteor = (multeval.metrics.METEOR) metric; for (int iSys = 0; iSys < data.getNumSystems(); iSys++) { Multiset<String> unmatchedHypWords = HashMultiset.create(); Multiset<String> unmatchedRefWords = HashMultiset.create(); int medianIdx = results.get(iMetric, iSys, Type.MEDIAN_IDX).intValue(); List<SuffStats<?>> statsBySent = suffStats.getStats(iMetric, iSys, medianIdx); for (int iHyp = 0; iHyp < data.getNumHyps(); iHyp++) { METEORStats sentStats = (METEORStats) statsBySent.get(iHyp); unmatchedHypWords.addAll(meteor.getUnmatchedHypWords(sentStats)); unmatchedRefWords.addAll(meteor.getUnmatchedRefWords(sentStats)); } // print OOVs for this system List<Entry<String>> unmatchedHypWordsSorted = CollectionUtils.sortByCount(unmatchedHypWords); List<Entry<String>> unmatchedRefWordsSorted = CollectionUtils.sortByCount(unmatchedRefWords); int nHead = 10; System.err.println("Top unmatched hypothesis words accoring to METEOR: " + CollectionUtils.head(unmatchedHypWordsSorted, nHead)); System.err.println("Top unmatched reference words accoring to METEOR: " + CollectionUtils.head(unmatchedRefWordsSorted, nHead)); } } } } private void runBootstrapResampling(List<Metric<?>> metrics, HypothesisManager data, SuffStatManager suffStats, ResultsManager results) throws InterruptedException { for (int iSys = 0; iSys < data.getNumSystems(); iSys++) { double[] meanByMetric = new double[metrics.size()]; double[] stddevByMetric = new double[metrics.size()]; double[] minByMetric = new double[metrics.size()]; double[] maxByMetric = new double[metrics.size()]; for (int i = 0; i < metrics.size(); i++) { minByMetric[i] = Double.MAX_VALUE; maxByMetric[i] = Double.MIN_VALUE; } for (int iOpt = 0; iOpt < data.getNumOptRuns(); iOpt++) { System.err.println("Performing bootstrap resampling to estimate stddev for test set selection (System " + (iSys + 1) + " of " + data.getNumSystems() + "; opt run " + (iOpt + 1) + " of " + data.getNumOptRuns() + ")"); // index 1: metric, index 2: hypothesis, inner array: suff // stats List<List<SuffStats<?>>> suffStatsSysI = suffStats.getStats(iSys, iOpt); BootstrapResampler boot = new BootstrapResampler(threads, metrics, suffStatsSysI); List<double[]> sampledScoresByMetric = boot.resample(numBootstrapSamples); for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { double[] sampledScores = sampledScoresByMetric.get(iMetric); double mean = MathUtils.average(sampledScores); double stddev = MathUtils.stddev(sampledScores); double min = MathUtils.min(sampledScores); double max = MathUtils.max(sampledScores); // TODO: also include 95% CI? meanByMetric[iMetric] += mean / data.getNumOptRuns(); stddevByMetric[iMetric] += stddev / data.getNumOptRuns(); minByMetric[iMetric] = Math.min(min, minByMetric[iMetric]); maxByMetric[iMetric] = Math.max(max, maxByMetric[iMetric]); } } for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { results.report(iMetric, iSys, Type.RESAMPLED_MEAN_AVG, meanByMetric[iMetric]); results.report(iMetric, iSys, Type.RESAMPLED_STDDEV_AVG, stddevByMetric[iMetric]); results.report(iMetric, iSys, Type.RESAMPLED_MIN, minByMetric[iMetric]); results.report(iMetric, iSys, Type.RESAMPLED_MAX, maxByMetric[iMetric]); } } } }
20,830
40.496016
248
java
multeval
multeval-master/src/multeval/NbestEntry.java
package multeval; import java.util.*; import multeval.metrics.*; import com.google.common.base.*; public class NbestEntry { public int sentId; public int origRank; public String hyp; public String feats; public float total; public double[] metricScores; public int[] metricRank; public double[] submetricScores; public List<SuffStats<?>> metricStats; public static NbestEntry parse(String cdecStr, int origRank, int numMetrics) { NbestEntry result = new NbestEntry(); // 0 ||| the transactions with the shares of čez achieved almost half of // the normal agenda . ||| Glue=8 LanguageModel=-39.2525 PassThrough=1 // PhraseModel_0=2.18572 PhraseModel_1=13.4858 PhraseModel_2=4.24232 // WordPenalty=-6.51442 ContextCRF=-35.9812 crf.ContentWordCount=7 // crf.NonContentWordCount=26 crf.StopWordCount=7 // crf.NonStopWordCount=26 ||| -28.842 Iterator<String> columns = Splitter.on(" ||| ").split(cdecStr).iterator(); result.sentId = Integer.parseInt(columns.next()); result.hyp = columns.next(); result.feats = columns.next(); result.total = Float.parseFloat(columns.next()); result.origRank = origRank; result.metricRank = new int[numMetrics]; return result; } public String toString(String[] metricNames, String[] submetricNames) { StringBuilder rankStr = new StringBuilder("origRank=" + origRank); for(int iMetric = 0; iMetric < metricNames.length; iMetric++) { rankStr.append(" " + metricNames[iMetric] + "Rank=" + metricRank[iMetric]); } StringBuilder metricString = new StringBuilder(); if (metricScores != null) { metricString.append(" |||"); for(int iMetric = 0; iMetric < metricNames.length; iMetric++) { metricString.append(" " + metricNames[iMetric] + "=" + metricScores[iMetric]); } } if (submetricScores != null) { for(int iSub = 0; iSub < submetricNames.length; iSub++) { metricString.append(" " + submetricNames[iSub] + "=" + submetricScores[iSub]); } } return String.format("%d ||| %s ||| %s ||| %f ||| %s", sentId, hyp, feats, total, rankStr.toString()) + metricString.toString(); } }
2,195
30.826087
105
java
multeval
multeval-master/src/multeval/NbestModule.java
package multeval; import jannopts.ConfigurationException; import jannopts.Configurator; import jannopts.Option; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import multeval.metrics.BLEU; import multeval.metrics.Metric; import multeval.metrics.SuffStats; import multeval.metrics.TER; import multeval.parallel.MetricWorkerPool; import multeval.parallel.SynchronizedBufferedReader; import multeval.parallel.SynchronizedPrintStream; import multeval.util.FileUtils; import multeval.util.SuffStatUtils; import multeval.util.StringUtils; import com.google.common.base.Charsets; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; public class NbestModule implements Module { @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") public int verbosity; @Option(shortName = "o", longName = "metrics", usage = "Space-delimited list of metrics to use. Any of: bleu, meteor, ter, length", defaultValue = "bleu meteor ter", arrayDelim = " ") public String[] metricNames; @Option(shortName = "N", longName = "nbest", usage = "File containing tokenized, fullform hypotheses, one per line") public String nbestList; @Option(shortName = "R", longName = "refs", usage = "Space-delimited list of files containing tokenized, fullform references, one per line", arrayDelim = " ") public String[] refFiles; @Option(shortName = "r", longName = "rankDir", usage = "Rank hypotheses of median optimization run of each system with regard to improvement/decline over median baseline system and output to the specified directory for analysis", required = false) private String rankDir; @Option(shortName = "t", longName = "threads", usage = "Number of threads to use. This will be reset to 1 thread if you choose to use any thread-unsafe metrics such as TER (Zero means use all available cores)", defaultValue = "0") private int threads; @Override public Iterable<Class<?>> getDynamicConfigurables() { return ImmutableList.<Class<?>> of(BLEU.class, multeval.metrics.METEOR.class, TER.class); } public static class NbestTask { public final List<NbestEntry> myHyps; public final List<String> sentRefs; public NbestTask(List<NbestEntry> myHyps, List<String> sentRefs) { this.myHyps = myHyps; this.sentRefs = sentRefs; } } @Override public void run(Configurator opts) throws ConfigurationException, IOException, InterruptedException { final List<Metric<?>> metrics = MultEval.loadMetrics(metricNames, opts); final String[] submetricNames = getSubmetricNames(metrics); this.threads = MultEval.initThreads(metrics, threads); // 1) count hyps for error checking String lastLine = FileUtils.getLastLine(nbestList); NbestEntry lastEntry = NbestEntry.parse(lastLine, -1, 0); int numHyps = lastEntry.sentId + 1; // zero-based // 2) load refs List<List<String>> allRefs = HypothesisManager.loadRefs(refFiles, numHyps); System.err.println("Found " + numHyps + " hypotheses with " + allRefs.get(0).size() + " references"); // 3) process n-best list and write results final SynchronizedPrintStream out = new SynchronizedPrintStream(System.out); final SynchronizedPrintStream[] metricRankFiles = rankDir == null ? null : new SynchronizedPrintStream[metrics.size()]; ; if (rankDir != null) { new File(rankDir).mkdirs(); for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { metricRankFiles[iMetric] = new SynchronizedPrintStream(new PrintStream(new File(rankDir, metricNames[iMetric] + ".sorted"), "UTF-8")); } } SynchronizedBufferedReader in = new SynchronizedBufferedReader(new BufferedReader(new InputStreamReader( new FileInputStream(nbestList), Charsets.UTF_8))); String line; final int DEFAULT_NUM_HYPS = 1000; List<NbestEntry> hyps = new ArrayList<NbestEntry>(DEFAULT_NUM_HYPS); final List<List<SuffStats<?>>> oracleStatsByMetric = new ArrayList<List<SuffStats<?>>>(metrics.size()); final List<List<SuffStats<?>>> woracleStatsByMetric = new ArrayList<List<SuffStats<?>>>(metrics.size()); final List<List<SuffStats<?>>> topbestStatsByMetric = new ArrayList<List<SuffStats<?>>>(metrics.size()); for (int i = 0; i < metrics.size(); i++) { oracleStatsByMetric.add(new ArrayList<SuffStats<?>>()); woracleStatsByMetric.add(new ArrayList<SuffStats<?>>()); topbestStatsByMetric.add(new ArrayList<SuffStats<?>>()); } MetricWorkerPool<NbestModule.NbestTask, List<Metric<?>>> work = new MetricWorkerPool<NbestModule.NbestTask, List<Metric<?>>>( threads, new Supplier<List<Metric<?>>>() { @Override public List<Metric<?>> get() { List<Metric<?>> copy = new ArrayList<Metric<?>>(metrics.size()); for (Metric<?> metric : metrics) { copy.add(metric.threadClone()); } return copy; } }) { @Override public void doWork(List<Metric<?>> localMetrics, NbestModule.NbestTask t) { // local metrics are thread-safe on a per-instance basis // (i.e. multiple threads cannot access the same // instance) try { processHyp(localMetrics, submetricNames, t.myHyps, t.sentRefs, out, metricRankFiles, oracleStatsByMetric, woracleStatsByMetric, topbestStatsByMetric); } catch (InterruptedException e) { e.printStackTrace(); System.exit(1); } } }; work.start(); int curHyp = 0; int iLine = 0; while ((line = in.readLine()) != null) { iLine++; NbestEntry entry = NbestEntry.parse(line, hyps.size(), metrics.size()); if (curHyp != entry.sentId) { final List<String> sentRefs = allRefs.get(curHyp); work.addTask(new NbestTask(hyps, sentRefs)); if (iLine % 10000 == 0) { System.err.println("Processed " + iLine + " lines (" + curHyp + " hypotheses) so far..."); } int prevNumHyps = hyps.size(); // prevent future growing // don't just clear this! // pending tasks hold a reference to the previous instance of // this list, so it's important not to mutate it; we prefer not // to make an immutable copy since that can be expensive hyps = new ArrayList<NbestEntry>(prevNumHyps); entry.origRank = 0; curHyp = entry.sentId; } hyps.add(entry); } // handle last sentence List<String> sentRefs = allRefs.get(curHyp); work.addTask(new NbestTask(hyps, sentRefs)); work.waitForCompletion(); out.close(); if (rankDir != null) { System.err.println("Wrote n-best list ranked by metrics to: " + rankDir); for (int iMetric = 0; iMetric < metrics.size(); iMetric++) { metricRankFiles[iMetric].close(); } } for (int i = 0; i < metrics.size(); i++) { Metric<?> metric = metrics.get(i); SuffStats<?> topbestStats = SuffStatUtils.sumStats(topbestStatsByMetric.get(i)); double topbestScore = metric.scoreStats(topbestStats); String topbestSub = metric.scoreSubmetricsString(topbestStats); System.err.println(String.format("%s topbest score: %.2f (%s)", metric.toString(), topbestScore, topbestSub)); SuffStats<?> oracleStats = SuffStatUtils.sumStats(oracleStatsByMetric.get(i)); double oracleScore = metric.scoreStats(oracleStats); String oracleSub = metric.scoreSubmetricsString(oracleStats); System.err.println(String.format("%s oracle score: %.2f (%s)", metric.toString(), oracleScore, oracleSub)); SuffStats<?> woracleStats = SuffStatUtils.sumStats(woracleStatsByMetric.get(i)); double woracleScore = metric.scoreStats(woracleStats); String woracleSub = metric.scoreSubmetricsString(woracleStats); System.err.println(String.format("%s worst-oracle score: %.2f (%s)", metric.toString(), woracleScore, woracleSub)); } } public static String[] getSubmetricNames(List<Metric<?>> metrics) { int numSubmetrics = 0; for (Metric<?> metric : metrics) { numSubmetrics += metric.getSubmetricNames().length; } String[] submetricNames = new String[numSubmetrics]; int i = 0; for (Metric<?> metric : metrics) { for (String name : metric.getSubmetricNames()) { submetricNames[i] = name; i++; } } return submetricNames; } // process all hypotheses corresponding to a single sentence private void processHyp(List<Metric<?>> metricCopies, String[] submetricNames, List<NbestEntry> hyps, List<String> sentRefs, SynchronizedPrintStream out, SynchronizedPrintStream[] metricRankFiles, List<List<SuffStats<?>>> oracleStatsByMetric, List<List<SuffStats<?>>> woracleStatsByMetric, List<List<SuffStats<?>>> topbestStatsByMetric) throws InterruptedException { // score all of the hypotheses in the n-best list for (int iRank = 0; iRank < hyps.size(); iRank++) { List<SuffStats<?>> metricStats = new ArrayList<SuffStats<?>>(metricCopies.size()); double[] metricScores = new double[metricCopies.size()]; double[] submetricScores = new double[submetricNames.length]; NbestEntry entry = hyps.get(iRank); // NOTE: We normalize whitespace here instead of in the reader since // the initial reader must operate in a single thread entry.hyp = StringUtils.normalizeWhitespace(entry.hyp); int iSubmetric = 0; for (int iMetric = 0; iMetric < metricCopies.size(); iMetric++) { Metric<?> metric = metricCopies.get(iMetric); SuffStats<?> stats = metric.stats(entry.hyp, sentRefs); metricStats.add(stats); metricScores[iMetric] = metric.scoreStats(stats); for (double sub : metric.scoreSubmetricsStats(stats)) { submetricScores[iSubmetric] = sub; iSubmetric++; } } entry.metricStats = metricStats; entry.metricScores = metricScores; entry.submetricScores = submetricScores; } // assign rank by each metric and save suff stats for the topbest // hyp // accoring to each metric for (int iMetric = 0; iMetric < metricCopies.size(); iMetric++) { // TODO: Should we make this a single sync block to reduce lock // overhead? synchronized (topbestStatsByMetric) { topbestStatsByMetric.get(iMetric).add(hyps.get(0).metricStats.get(iMetric)); } sortByMetricScore(hyps, iMetric, metricCopies.get(iMetric).isBiggerBetter()); synchronized (oracleStatsByMetric) { oracleStatsByMetric.get(iMetric).add(hyps.get(0).metricStats.get(iMetric)); } synchronized (woracleStatsByMetric) { woracleStatsByMetric.get(iMetric).add( hyps.get(hyps.size() - 1).metricStats.get(iMetric)); } // and record the rank of each for (int iRank = 0; iRank < hyps.size(); iRank++) { hyps.get(iRank).metricRank[iMetric] = iRank; } } // put them back in their original order Collections.sort(hyps, new Comparator<NbestEntry>() { public int compare(NbestEntry a, NbestEntry b) { int ra = a.origRank; int rb = b.origRank; return (ra < rb ? -1 : 1); } }); int sentId = hyps.get(0).sentId; // and write them to an output file for (NbestEntry entry : hyps) { out.println(sentId, entry.toString(metricNames, submetricNames)); } out.finishUnit(sentId); if (metricRankFiles != null) { for (int iMetric = 0; iMetric < metricCopies.size(); iMetric++) { sortByMetricScore(hyps, iMetric, metricCopies.get(iMetric).isBiggerBetter()); // and write them to an output file for (NbestEntry entry : hyps) { metricRankFiles[iMetric].println(sentId, entry.toString(metricNames, submetricNames)); } metricRankFiles[iMetric].finishUnit(sentId); } } } private void sortByMetricScore(List<NbestEntry> hyps, final int i, final boolean isBiggerBetter) { Collections.sort(hyps, new Comparator<NbestEntry>() { public int compare(NbestEntry a, NbestEntry b) { double da = a.metricScores[i]; double db = b.metricScores[i]; if (isBiggerBetter) { return (da == db ? 0 : (da > db ? -1 : 1)); } else { return (da == db ? 0 : (da < db ? -1 : 1)); } } }); } }
12,146
34.517544
248
java
multeval
multeval-master/src/multeval/ResultsManager.java
package multeval; import java.util.*; public class ResultsManager { // indices: iSys, iMetric private final List<List<Map<Type, Double>>> resultsBySys; private int numMetrics; public final String[] metricNames; public final String[] sysNames; public final int numOptRuns; public enum Type { AVG, STDDEV, MIN, MAX, RESAMPLED_MEAN_AVG, RESAMPLED_STDDEV_AVG, RESAMPLED_MIN, RESAMPLED_MAX, P_VALUE, MEDIAN, MEDIAN_IDX } public ResultsManager(String[] metricNames, String[] sysNames, int numOptRuns) { this.metricNames = metricNames; this.sysNames = sysNames; this.numOptRuns = numOptRuns; this.numMetrics = metricNames.length; int numSys = sysNames.length; this.resultsBySys = new ArrayList<List<Map<Type, Double>>>(numSys); } public void report(int iMetric, int iSys, Type type, double d) { while(resultsBySys.size() <= iSys) { resultsBySys.add(new ArrayList<Map<Type, Double>>(numMetrics)); } List<Map<Type, Double>> resultsByMetric = resultsBySys.get(iSys); while(resultsByMetric.size() <= iMetric) { resultsByMetric.add(new HashMap<Type, Double>()); } Map<Type, Double> map = resultsByMetric.get(iMetric); map.put(type, d); System.err.println("RESULT: " + sysNames[iSys] + ": " + metricNames[iMetric] + ": " + type.name() + ": " + String.format("%.6f", d)); // too much precision here, but AsciiTable fixes this } public Double get(int iMetric, int iSys, Type type) { List<Map<Type, Double>> resultsByMetric = resultsBySys.get(iSys); if (resultsByMetric == null) { throw new RuntimeException("No results found for system + " + iSys); } Map<Type, Double> resultsByType = resultsByMetric.get(iMetric); if (resultsByType == null) { throw new RuntimeException("No results found for system " + iSys + " for metric " + iMetric); } Double result = resultsByType.get(type); if (result == null) { throw new RuntimeException("No results found for system " + iSys + " for metric " + iMetric + " of type " + type); } return result; } }
2,100
34.016667
120
java
multeval
multeval-master/src/multeval/SuffStatManager.java
package multeval; import java.util.*; import multeval.metrics.*; public class SuffStatManager { // indexices iSys, iOpt, iMetric, iHyp; inner array: various suff stats for // a particular metric private final List<List<List<List<SuffStats<?>>>>> statsBySys; private final int numMetrics; private final int numOpt; private final int numHyp; private static final SuffStats<?> DUMMY = null; public SuffStatManager(int numMetrics, int numSys, int numOpt, int numHyp) { this.numMetrics = numMetrics; this.numOpt = numOpt; this.numHyp = numHyp; this.statsBySys = new ArrayList<List<List<List<SuffStats<?>>>>>(numSys); // TODO: Use more intelligent list type that allows batch grow // operations // presize all lists for(int iSys = 0; iSys < numSys; iSys++) { statsBySys.add(new ArrayList<List<List<SuffStats<?>>>>(numOpt)); List<List<List<SuffStats<?>>>> statsByOpt = statsBySys.get(iSys); for(int iOpt=0; iOpt < numOpt; iOpt++) { statsByOpt.add(new ArrayList<List<SuffStats<?>>>(numMetrics)); List<List<SuffStats<?>>> statsByMetric = statsByOpt.get(iOpt); for(int iMetric =0; iMetric < numMetrics; iMetric++) { statsByMetric.add(new ArrayList<SuffStats<?>>(numHyp)); List<SuffStats<?>> statsByHyp = statsByMetric.get(iMetric); for(int iHyp=0; iHyp<numHyp; iHyp++) { statsByHyp.add(DUMMY); } } } } } // threadsafe public void saveStats(int iMetric, int iSys, int iOpt, int iHyp, SuffStats<?> stats) { // first, expand as necessary List<List<List<SuffStats<?>>>> statsByOpt = statsBySys.get(iSys); List<List<SuffStats<?>>> statsByMetric = statsByOpt.get(iOpt); List<SuffStats<?>> statsByHyp = statsByMetric.get(iMetric); statsByHyp.set(iHyp, stats); } // inner array: various suff stats for a particular metric public SuffStats<?> getStats(int iMetric, int iSys, int iOpt, int iHyp) { // TODO: More informative error messages w/ bounds checking return getStats(iMetric, iSys, iOpt).get(iHyp); } // list index: iHyp; inner array: various suff stats for a particular metric public List<SuffStats<?>> getStats(int iMetric, int iSys, int iOpt) { // TODO: More informative error messages w/ bounds checking return getStats(iSys, iOpt).get(iMetric); } // indices: iMetric, iHyp public List<List<SuffStats<?>>> getStats(int iSys, int iOpt) { // TODO: More informative error messages w/ bounds checking return statsBySys.get(iSys).get(iOpt); } // appends all optimization runs together // indices: iMetric, iHyp; inner array: various suff stats for a particular // metric public List<List<SuffStats<?>>> getStatsAllOptForSys(int iSys) { List<List<SuffStats<?>>> resultByMetric = new ArrayList<List<SuffStats<?>>>(numMetrics); List<List<List<SuffStats<?>>>> statsByOpt = statsBySys.get(iSys); for(int iMetric = 0; iMetric < numMetrics; iMetric++) { ArrayList<SuffStats<?>> resultByHyp = new ArrayList<SuffStats<?>>(numHyp * numOpt); resultByMetric.add(resultByHyp); for(int iOpt = 0; iOpt < numOpt; iOpt++) { List<List<SuffStats<?>>> statsByMetric = statsByOpt.get(iOpt); List<SuffStats<?>> statsByHyp = statsByMetric.get(iMetric); resultByHyp.addAll(statsByHyp); } } return resultByMetric; } }
3,449
35.315789
92
java
multeval
multeval-master/src/multeval/analysis/DiffRanker.java
package multeval.analysis; import java.io.*; import java.util.*; public class DiffRanker { private String[] metricNames; public DiffRanker(String[] metricNames) { this.metricNames = metricNames; } private static class HypItem { public final int id; public final List<String> refs; public final String hypBaseline; public final String hypSys; public final double[] metricScoresBaseline; public final double[] metricScoresSys; public HypItem(int id, List<String> refs, String hypBaseline, String hypSys, double[] metricScoresBaseline, double[] metricScoresSys) { this.id = id; this.hypBaseline = hypBaseline; this.hypSys = hypSys; this.refs = refs; this.metricScoresBaseline = metricScoresBaseline; this.metricScoresSys = metricScoresSys; } public double diff(int iMetric) { return metricScoresSys[iMetric] - metricScoresBaseline[iMetric]; } } public void write(List<String> hypsMedianBaseline, List<String> hypsMedianSys, List<List<String>> refs, double[][] sentMetricScoresBaseline, double[][] sentMetricScoresSys, final int sortByMetric, PrintWriter out) { // merge all the data together List<HypItem> list = new ArrayList<HypItem>(hypsMedianBaseline.size()); for(int i = 0; i < hypsMedianBaseline.size(); i++) { list.add(new HypItem(i, refs.get(i), hypsMedianBaseline.get(i), hypsMedianSys.get(i), sentMetricScoresBaseline[i], sentMetricScoresSys[i])); } // sort by metric improvement/decline Collections.sort(list, new Comparator<HypItem>() { @Override public int compare(HypItem hypA, HypItem hypB) { double diffA = hypA.diff(sortByMetric); double diffB = hypB.diff(sortByMetric); // most improved first return -(diffA < diffB ? -1 : (diffA == diffB ? 0 : 1)); } }); // TODO: Write the median optimization run id to // format the entries and write the file for(HypItem item : list) { // TODO: option: show all optimization runs? // TODO: option: show "submetrics" out.printf("SENT %d\t", item.id); // first, write out sort-by metric out.printf("%s: %.1f -> %.1f = %.1f", metricNames[sortByMetric], item.metricScoresBaseline[sortByMetric], item.metricScoresSys[sortByMetric], item.diff(sortByMetric)); for(int iMetric = 0; iMetric < metricNames.length; iMetric++) { if (iMetric != sortByMetric) { out.printf("\t%s: %.1f -> %.1f = %.1f", metricNames[iMetric], item.metricScoresBaseline[iMetric], item.metricScoresSys[iMetric], item.diff(iMetric)); } } out.println(); out.printf("%s-median-baseline: %s", metricNames[sortByMetric], item.hypBaseline); out.println(); // TODO: Insert system names here out.printf("%s-median-variant: %s", metricNames[sortByMetric], item.hypSys); out.println(); for(int iRef = 0; iRef < item.refs.size(); iRef++) { out.printf("ref%d: %s", iRef + 1, item.refs.get(iRef)); out.println(); } out.println(); } } }
3,142
33.163043
117
java
multeval
multeval-master/src/multeval/analysis/SentFormatter.java
package multeval.analysis; import java.io.*; import java.util.*; // sentence-level analysis only public class SentFormatter { private String[] metricNames; private String[] submetricNames; public SentFormatter(String[] metricNames, String[] submetricNames) { this.metricNames = metricNames; this.submetricNames = submetricNames; } private static class HypItem { public final int id; public final List<String> refs; public final String hyp; public final double[] metricScores; public final double[] submetricScores; public HypItem(int id, List<String> refs, String hyp, double[] metricScores, double[] submetricScores) { this.id = id; this.hyp = hyp; this.refs = refs; this.metricScores = metricScores; this.submetricScores = submetricScores; } } public void write(List<String> hyps, List<List<String>> refs, double[][] sentMetricScores, double[][] sentSubmetricScores, PrintWriter out) { // merge all the data together List<HypItem> list = new ArrayList<HypItem>(hyps.size()); for(int i = 0; i < hyps.size(); i++) { list.add(new HypItem(i, refs.get(i), hyps.get(i), sentMetricScores[i], sentSubmetricScores[i])); } // format the entries and write the file for(HypItem item : list) { // TODO: option: show "submetrics" out.printf("%d ||| %s |||", item.id, item.hyp); for(int iMetric = 0; iMetric < metricNames.length; iMetric++) { out.printf(" %s=%.2f", metricNames[iMetric], item.metricScores[iMetric]); } out.print(" |||"); for(int iSubmetric = 0; iSubmetric < submetricNames.length; iSubmetric++) { out.printf(" %s=%.2f", submetricNames[iSubmetric], item.submetricScores[iSubmetric]); } /* for(int iRef = 0; iRef < item.refs.size(); iRef++) { out.printf("ref%d: %s", iRef + 1, item.refs.get(iRef)); out.println(); } */ out.println(); } } }
2,003
28.910448
110
java
multeval
multeval-master/src/multeval/metrics/BLEU.java
package multeval.metrics; import jannopts.ConfigurationException; import jannopts.Configurator; import jannopts.Option; import java.util.ArrayList; import java.util.List; import jbleu.JBLEU; import multeval.util.LibUtil; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.Lists; // a MultiMetric wrapper around the jBLEU metric public class BLEU extends Metric<IntStats> { // @Option(shortName = "c", longName = "bleu.closestRefLength", usage = // "Use closest reference length when determining brevity penalty? (true behaves like IBM BLEU, false behaves like old NIST BLEU)", // defaultValue="true") // boolean closestRefLength; @Option(shortName = "v", longName = "bleu.verbosity", usage = "Verbosity level (Integer: 0-1)", defaultValue = "0") public int verbosity; private JBLEU bleu = new JBLEU(); public static final String[] SUBMETRIC_NAMES = { "bleu1p", "bleu2p", "bleu3p", "bleu4p", "brevity" }; @Override public IntStats stats(String hyp, List<String> refs) { List<String> tokHyp = Lists.newArrayList(Splitter.on(CharMatcher.BREAKING_WHITESPACE).split(hyp)); List<List<String>> tokRefs = tokenizeRefs(refs); IntStats result = new IntStats(JBLEU.getSuffStatCount()); bleu.stats(tokHyp, tokRefs, result.arr); return result; } public static List<List<String>> tokenizeRefs(List<String> refs) { List<List<String>> tokRefs = new ArrayList<List<String>>(); for(String ref : refs) { tokRefs.add(Lists.newArrayList(Splitter.on(CharMatcher.BREAKING_WHITESPACE).split(ref))); } return tokRefs; } @Override public String getMetricDescription() { return String.format("jBLEU V%s (an exact reimplementation of NIST's mteval-v13.pl without tokenization)", JBLEU.VERSION); } @Override public double score(IntStats suffStats) { return bleu.score(suffStats.arr) * 100; } @Override public double[] scoreSubmetrics(IntStats suffStats) { int N = 4; double[] result = new double[N + 1]; bleu.score(suffStats.arr, result); return result; } @Override public String[] getSubmetricNames() { return SUBMETRIC_NAMES; } @Override public String toString() { return "BLEU"; } @Override public void configure(Configurator opts) throws ConfigurationException { LibUtil.checkLibrary("jbleu.JBLEU", "jBLEU"); opts.configure(this); this.bleu.verbosity = this.verbosity; } @Override public boolean isBiggerBetter() { return true; } }
2,550
27.032967
133
java
multeval
multeval-master/src/multeval/metrics/IntStats.java
package multeval.metrics; import java.util.*; import multeval.util.*; public class IntStats extends SuffStats<IntStats> { public final int[] arr; public IntStats(int size) { this.arr = new int[size]; } @Override public void add(IntStats other) { ArrayUtils.plusEquals(this.arr, other.arr); } @Override public SuffStats<IntStats> create() { return new IntStats(arr.length); } @Override public String toString() { return Arrays.toString(arr); } }
492
16
51
java
multeval
multeval-master/src/multeval/metrics/Length.java
package multeval.metrics; import jannopts.*; import java.util.*; import jbleu.*; import com.google.common.base.*; import com.google.common.collect.*; // a MultiMetric wrapper around the jBLEU metric public class Length extends Metric<IntStats> { @Override public String getMetricDescription() { return "Hypothesis length over reference length as a percent"; } @Override public IntStats stats(String hyp, List<String> refs) { List<String> hypToks = Lists.newArrayList(Splitter.on(CharMatcher.BREAKING_WHITESPACE).split(hyp)); List<List<String>> tokRefs = BLEU.tokenizeRefs(refs); int verbosity = 0; int iRef = JBLEU.pickReference(hypToks, tokRefs, verbosity); IntStats result = new IntStats(2); result.arr[0] = hypToks.size(); result.arr[1] = tokRefs.get(iRef).size(); return result; } @Override public double score(IntStats suffStats) { int hypLen = suffStats.arr[0]; int refLen = suffStats.arr[1]; return ((double) hypLen / (double) refLen) * 100; } @Override public String toString() { return "Length"; } @Override public void configure(Configurator opts) throws ConfigurationException { opts.configure(this); } @Override public boolean isBiggerBetter() { return true; } }
1,284
21.946429
103
java
multeval
multeval-master/src/multeval/metrics/METEOR.java
package multeval.metrics; import jannopts.*; import java.io.*; import java.net.*; import java.util.*; import multeval.util.*; import com.google.common.primitives.*; import com.google.common.collect.*; import com.google.common.base.*; import edu.cmu.meteor.scorer.*; import edu.cmu.meteor.util.*; import edu.cmu.meteor.aligner.*; public class METEOR extends Metric<METEORStats> { @Option(shortName = "l", longName = "meteor.language", usage = "Two-letter language code of a supported METEOR language (e.g. 'en')") String language; @Option(shortName = "t", longName = "meteor.task", usage = "One of: rank adq hter tune (Rank is generally a good choice)", defaultValue = "rank") String task; @Option(shortName = "p", longName = "meteor.params", usage = "Custom parameters of the form 'alpha beta gamma' (overrides default)", arrayDelim = " ", required = false) double[] params; @Option(shortName = "m", longName = "meteor.modules", usage = "Specify modules. (overrides default) Any of: exact stem synonym paraphrase", arrayDelim = " ", required = false) String[] modules; @Option(shortName = "w", longName = "meteor.weights", usage = "Specify module weights (overrides default)", arrayDelim = " ", required = false) double[] moduleWeights; @Option(shortName = "x", longName = "meteor.beamSize", usage = "Specify beam size (overrides default)", defaultValue = "" + Constants.DEFAULT_BEAM_SIZE) int beamSize; @Option(shortName = "s", longName = "meteor.synonymDirectory", usage = "If default is not desired (NOTE: This option has a different short flag than stand-alone METEOR)", required = false) String synonymDirectory; @Option(shortName = "a", longName = "meteor.paraphraseFile", usage = "If default is not desired", required = false) String paraphraseFile; @Option(shortName = "k", longName = "meteor.keepPunctuation", usage = "Consider punctuation when aligning sentences (if false, the meteor tokenizer will be run, after which punctuation will be removed)", defaultValue = "true") boolean keepPunctuation; public static final String[] SUBMETRIC_NAMES = { "prec", "rec", "frag" }; // TODO: Meteor normalization? private MeteorScorer scorer; @Override public String getMetricDescription() { StringBuilder builder = new StringBuilder(); builder.append("Meteor V"+edu.cmu.meteor.util.Constants.VERSION); builder.append(" " + language); builder.append(" on " + task + " task"); if(modules == null) { builder.append(" with all default modules"); } else { builder.append(" with modules " + Joiner.on(", ").join(modules)); } if(keepPunctuation) { builder.append(" NOT"); } builder.append(" ignoring punctuation"); return builder.toString(); } @Override public void configure(Configurator opts) throws ConfigurationException { LibUtil.checkLibrary("edu.cmu.meteor.scorer.MeteorScorer", "METEOR"); System.err.println("Using METEOR Version " + edu.cmu.meteor.util.Constants.VERSION); opts.configure(this); // do some sanity checking if(Constants.getLanguageID(Constants.normLanguageName(language)) == Constants.LANG_OTHER && Constants.getTaskID(task) != Constants.TASK_LI) { throw new ConfigurationException("Unrecognized METEOR language: "+language); } if(Constants.getTaskID(task) == Constants.TASK_CUSTOM) { throw new ConfigurationException("Unrecognized METEOR task: "+task); } MeteorConfiguration config = new MeteorConfiguration(); config.setLanguage(language); // task must be set after language due to Meteor initializing defaults config.setTask(task); if (params != null) { config.setParameters(new ArrayList<Double>(Doubles.asList(params))); } if (moduleWeights != null) { config.setModuleWeights(new ArrayList<Double>(Doubles.asList(moduleWeights))); } if (modules != null) { List<String> moduleList = Arrays.asList(modules); config.setModulesByName(new ArrayList<String>(moduleList)); // error if not enough weights if (config.getModuleWeights().size() != modules.length) { throw new RuntimeException("You provided " + modules.length + " modules and " + config.getModuleWeights().size() + " module weights"); } } config.setBeamSize(beamSize); if (synonymDirectory != null) { try { // This should not ever throw a malformed url exception config.setSynDirURL((new File(synonymDirectory)).toURI().toURL()); } catch(MalformedURLException e) { throw new Error(e); } } if (paraphraseFile != null) { try { // This should not ever throw a malformed url exception config.setParaFileURL((new File(paraphraseFile)).toURI().toURL()); } catch(MalformedURLException e) { throw new Error(e); } } if (keepPunctuation) { config.setNormalization(Constants.NO_NORMALIZE); } else { config.setNormalization(Constants.NORMALIZE_NO_PUNCT); } System.err.println("Loading METEOR paraphrase table..."); Stopwatch watch = new Stopwatch(); watch.start(); scorer = new MeteorScorer(config); watch.stop(); System.err.println("Loaded METEOR in " + watch.toString(3)); } @Override public METEORStats stats(String hyp, List<String> refs) { // TODO: Don't create so many garbage MeteorStats objects just to be // copy-constructed MeteorStats result = scorer.getMeteorStats(hyp, new ArrayList<String>(refs)); return new METEORStats(result); } @Override public double score(METEORStats suffStats) { scorer.computeMetrics(suffStats.meteorStats); return suffStats.meteorStats.score * 100; } @Override public double[] scoreSubmetrics(METEORStats suffStats) { MeteorStats stats = suffStats.meteorStats; scorer.computeMetrics(stats); return new double[] { stats.precision, stats.recall, stats.fragPenalty }; } @Override public String[] getSubmetricNames() { return SUBMETRIC_NAMES; } public Multiset<String> getUnmatchedHypWords(METEORStats stats) { List<String> hypWords = stats.meteorStats.alignment.words1; Multiset<String> result = HashMultiset.create(hypWords); for(Match m : stats.meteorStats.alignment.matches) { if (m != null) { int hypMatchStart = m.matchStart; int hypMatchLen = m.matchLength; for (int i = 0; i < hypMatchLen; i++) { String matchedHypWord = hypWords.get(hypMatchStart + i); result.remove(matchedHypWord); } } } return result; } public Multiset<String> getUnmatchedRefWords(METEORStats stats) { List<String> refWords = stats.meteorStats.alignment.words2; Multiset<String> result = HashMultiset.create(refWords); for(Match m : stats.meteorStats.alignment.matches) { if(m != null) { int refMatchStart = m.start; int refMatchLen = m.length; for (int i = 0; i < refMatchLen; i++) { String matchedRefWord = refWords.get(refMatchStart + i); result.remove(matchedRefWord); } } } return result; } @Override public String toString() { return "METEOR"; } @Override public boolean isBiggerBetter() { return true; } @Override public Metric<?> threadClone() { METEOR metric = new METEOR(); metric.scorer = new MeteorScorer(scorer); return metric; } }
7,394
32.310811
228
java
multeval
multeval-master/src/multeval/metrics/METEORStats.java
package multeval.metrics; import edu.cmu.meteor.scorer.*; public class METEORStats extends SuffStats<METEORStats> { public final MeteorStats meteorStats; public METEORStats(MeteorStats other) { this.meteorStats = other; } private METEORStats() { this.meteorStats = new MeteorStats(); } @Override public void add(METEORStats other) { // "exact" meteor score isn't strictly a sum // due to a corner case in the fragmentation penalty this.meteorStats.addStats(other.meteorStats); } @Override public SuffStats<METEORStats> create() { return new METEORStats(); } @Override public String toString() { return meteorStats.toString(); } }
694
19.441176
57
java
multeval
multeval-master/src/multeval/metrics/Metric.java
package multeval.metrics; import jannopts.*; import java.util.*; /** * Computes a metric score given that metric's sufficient statistics (Yes, we're * skipping the hard, expensive part and letting the metric reference * implementations take care of that) * * @author jhclark */ public abstract class Metric<Stats extends SuffStats<Stats>> { public abstract Stats stats(String sentence, List<String> refs); public abstract double score(Stats suffStats); public abstract void configure(Configurator opts) throws ConfigurationException; public abstract boolean isBiggerBetter(); // this should include version! public abstract String getMetricDescription(); // indicates that a single instance can safely be used by a single thread // does NOT indicate that a single instance can support multiple threads // Update: We removed this since TER is now thread-safe in that a single JVM // can have multiple instances of it //public abstract boolean isThreadsafe(); public String[] getSubmetricNames() { return new String[0]; } public double[] scoreSubmetrics(Stats suffStats) { return new double[0]; } // hack around generics by erasure @SuppressWarnings("unchecked") public double scoreStats(SuffStats<?> suffStats) { return score((Stats) suffStats); } // hack around generics by erasure @SuppressWarnings("unchecked") public double[] scoreSubmetricsStats(SuffStats<?> suffStats) { return scoreSubmetrics((Stats) suffStats); } public String scoreSubmetricsString(SuffStats<?> suffStats) { StringBuilder builder = new StringBuilder(); String[] names = getSubmetricNames(); double[] subs = scoreSubmetricsStats(suffStats); for (int i = 0; i < names.length; i++) { builder.append(String.format("%s=%.2f", names[i], subs[i])); if (i < names.length - 1) { builder.append("; "); } } return builder.toString(); } public Metric<?> threadClone() { // for metrics like meteor that *can* be thread-safe, we need to make // copies // for metric like ter, we're just completely hosed return this; // works if this metric is threadsafe in general } }
2,121
28.068493
81
java