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/dslForScriptGenerator/DSLBasicConditional/functions/HaveEnemiesStrongest.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveEnemiesStrongest extends AbstractConditionalFunction { @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(5); // PlayerTargetParam playerTargetP= (PlayerTargetParam) lParam1.get(6); // EnumPlayerTarget enumPlayer=playerTargetP.getSelectedPlayerTarget().get(0); // String playerT=enumPlayer.name(); // int playerTarget=-1; // if(playerT=="Ally") // playerTarget=player; // if(playerT=="Enemy") // playerTarget=1-player; parameters.add(unitType); if (hasUnitInParam(lParam1)) { return runUnitConditional(game, currentPlayerAction, player, getUnitFromParam(lParam1)); } else { return runConditionalInSimpleWay(game, currentPlayerAction, player); } } @Override public String toString() { return "HaveUnitsinEnemyRange"; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player) { PhysicalGameState pgs = game.getPhysicalGameState(); //now we iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnitsSimpleWay(game, currentPlayerAction, player)) { //if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int damage = u2.getMaxDamage(); int HP = unAlly.getHitPoints(); if (damage > HP) { return true; } } } //} } return false; } private boolean runUnitConditional(GameState game, PlayerAction currentPlayerAction, int player, Unit unAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); //now we iterate for all ally units in order to discover wich one satisfy the condition // if (currentPlayerAction.getAction(unAlly) == null) { List<Unit> unitscurrent=new ArrayList<Unit>(); getPotentialUnitsSimpleWay(game, currentPlayerAction, player).forEach(unitscurrent::add); if(unitscurrent.contains(unAlly)) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int damage = u2.getMaxDamage(); int HP = unAlly.getHitPoints(); if (damage > HP) { return true; } } } } return false; } }
3,645
30.704348
115
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveEnemiesinUnitsRange.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveEnemiesinUnitsRange extends AbstractConditionalFunction { @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(5); parameters.add(unitType); if (hasUnitInParam(lParam1)) { return runUnitConditional(game, currentPlayerAction, player, getUnitFromParam(lParam1)); } else { return runConditionalInSimpleWay(game, currentPlayerAction, player); } } @Override public String toString() { return "HaveEnemiesinUnitsRange"; } private boolean runUnitConditional(GameState game, PlayerAction currentPlayerAction, int player, Unit unAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition //if (currentPlayerAction.getAction(unAlly) == null) { List<Unit> unitscurrent=new ArrayList<Unit>(); getPotentialUnitsSimpleWay(game, currentPlayerAction, player).forEach(unitscurrent::add); if(unitscurrent.contains(unAlly)) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= unAlly.getAttackRange())) { return true; } } } } return false; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnitsSimpleWay(game, currentPlayerAction, player)) { //if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= unAlly.getAttackRange())) { return true; } } } // } } return false; } }
3,770
34.575472
116
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveQtdEnemiesbyType.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveQtdEnemiesbyType extends AbstractConditionalFunction{ @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); QuantityParam qtd = (QuantityParam) lParam1.get(5); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(6); parameters.add(unitType); if (getEnemyUnitsOfType(game, currentPlayerAction, player).size() >= qtd.getQuantity()){ return true; } return false; } protected ArrayList<Unit> getEnemyUnitsOfType(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitsEnemy = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == 1-player && isUnitControlledByParam(u)){ unitsEnemy.add(u); } } return unitsEnemy; } @Override public String toString() { return "HaveQtdEnemiesbyType"; } }
1,876
30.283333
113
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveQtdUnitsAttacking.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveQtdUnitsAttacking extends AbstractConditionalFunction{ @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); QuantityParam qtd = (QuantityParam) lParam1.get(5); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(6); parameters.add(unitType); //if (getAllyUnitsAttacking(game, currentPlayerAction, player).size() >= qtd.getQuantity()){ if (getNumberUnitsDoingAction("attack",counterByFunction,game,currentPlayerAction) >= qtd.getQuantity()){ return true; } return false; } protected ArrayList<Unit> getAllyUnitsAttacking(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && isUnitControlledByParam(u) && currentPlayerAction.getAction(u)!=null){ if(currentPlayerAction.getAction(u).getType()==5) unitAllys.add(u); } } return unitAllys; } @Override public String toString() { return "HaveQtdUnitsAttacking"; } protected int getNumberUnitsDoingAction(String action, HashMap<Long, String> counterByFunction, GameState game, PlayerAction currentPlayerAction) { int counterUnits=0; // HashMap<Long, String> counterByFunctionNew = new HashMap<Long,String>(counterByFunction); Iterator it = counterByFunction.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if(pair.getValue().equals(action)) { if(getUnitByIdFree(game, currentPlayerAction, (Long)pair.getKey(), counterByFunction) && getUnitByIdCorrectType(game, currentPlayerAction, (Long)pair.getKey(), counterByFunction)) counterUnits++; } // else // { // counterByFunctionNew.remove((Long)pair.getKey()); // } } //counterByFunction=counterByFunctionNew; return counterUnits; } protected boolean getUnitByIdFree(GameState game, PlayerAction currentPlayerAction, Long idUnit, HashMap<Long, String> counterByFunction) { for (Unit u : game.getUnits()) { if(currentPlayerAction.getAction(u) == null && game.getActionAssignment(u) == null && u.getID()==idUnit ){ return false; } } for (Unit u : game.getUnits()) { if(u.getID()==idUnit ){ return true; } } return false; } protected boolean getUnitByIdCorrectType(GameState game, PlayerAction currentPlayerAction, Long idUnit, HashMap<Long, String> counterByFunction) { for (Unit u : game.getUnits()) { if(u.getID()==idUnit && isUnitControlledByParam(u)){ return true; } } return false; } }
3,925
34.690909
186
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveQtdUnitsHarversting.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.HarvestBasic; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveQtdUnitsHarversting extends AbstractConditionalFunction{ @Override public boolean runFunction(List lParam1, HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); QuantityParam qtd = (QuantityParam) lParam1.get(5); if (getNumberUnitsDoingAction("harvest",counterByFunction,game,currentPlayerAction) >= qtd.getQuantity()){ return true; } return false; } protected ArrayList<Unit> getAllyUnitsHarvesting(GameState game, PlayerAction currentPlayerAction, int player) { HarvestBasic hb =new HarvestBasic(); HashSet<Long> unitsID = hb.unitsID; ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player){ //if(currentPlayerAction.getAction(u).getType()==2 || currentPlayerAction.getAction(u).getType()==3 || u.getResources()>0) if(unitsID.contains(u.getID())) unitAllys.add(u); } } return unitAllys; } @Override public String toString() { return "HaveQtdUnitsHarversting"; } protected int getNumberUnitsDoingAction(String action, HashMap<Long, String> counterByFunction, GameState game, PlayerAction currentPlayerAction) { int counterUnits=0; // HashMap<Long, String> counterByFunctionNew = new HashMap<Long,String>(counterByFunction); Iterator it = counterByFunction.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if(pair.getValue().equals(action)) { if(getUnitByIdFree(game, currentPlayerAction, (Long)pair.getKey(), counterByFunction) ) counterUnits++; } // else // { // counterByFunctionNew.remove((Long)pair.getKey()); // } } //counterByFunction=counterByFunctionNew; return counterUnits; } protected boolean getUnitByIdFree(GameState game, PlayerAction currentPlayerAction, Long idUnit, HashMap<Long, String> counterByFunction) { for (Unit u : game.getUnits()) { if(currentPlayerAction.getAction(u) == null && game.getActionAssignment(u) == null && u.getID()==idUnit ){ return false; } } for (Unit u : game.getUnits()) { if(u.getID()==idUnit ){ return true; } } return false; } }
3,433
33.686869
151
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveQtdUnitsbyType.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveQtdUnitsbyType extends AbstractConditionalFunction{ @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); QuantityParam qtd = (QuantityParam) lParam1.get(5); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(6); parameters.add(unitType); if (getUnitsOfType(game, currentPlayerAction, player).size() >= qtd.getQuantity()){ return true; } return false; } protected ArrayList<Unit> getUnitsOfType(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && isUnitControlledByParam(u)){ unitAllys.add(u); } } return unitAllys; } @Override public String toString() { return "HaveQtdUnitsbyType"; } }
1,851
30.389831
108
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveUnitsStrongest.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveUnitsStrongest extends AbstractConditionalFunction { @Override public boolean runFunction(List lParam1, HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(5); // PlayerTargetParam playerTargetP= (PlayerTargetParam) lParam1.get(6); // EnumPlayerTarget enumPlayer=playerTargetP.getSelectedPlayerTarget().get(0); // String playerT=enumPlayer.name(); // int playerTarget=-1; // if(playerT=="Ally") // playerTarget=player; // if(playerT=="Enemy") // playerTarget=1-player; parameters.add(unitType); if (hasUnitInParam(lParam1)) { return runUnitConditional(game, currentPlayerAction, player, getUnitFromParam(lParam1)); } else { return runConditionalInSimpleWay(game, currentPlayerAction, player); } } @Override public String toString() { return "HaveUnitsinEnemyRange"; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnitsSimpleWay(game, currentPlayerAction, player)) { // if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int damage = unAlly.getMaxDamage(); int HP = u2.getHitPoints(); if (damage > HP) { return true; } } } // } } return false; } private boolean runUnitConditional(GameState game, PlayerAction currentPlayerAction, int player, Unit unAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition //if (currentPlayerAction.getAction(unAlly) == null) { List<Unit> unitscurrent=new ArrayList<Unit>(); getPotentialUnitsSimpleWay(game, currentPlayerAction, player).forEach(unitscurrent::add); if(unitscurrent.contains(unAlly)) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int damage = unAlly.getMaxDamage(); int HP = u2.getHitPoints(); if (damage > HP) { return true; } } } } return false; } }
3,642
31.81982
115
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveUnitsToDistantToEnemy.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.DistanceParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveUnitsToDistantToEnemy extends AbstractConditionalFunction { @Override public boolean runFunction(List lParam1,HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(5); DistanceParam distance = (DistanceParam) lParam1.get(6); parameters.add(unitType); parameters.add(distance); if (hasUnitInParam(lParam1)) { return runUnitConditional(game, currentPlayerAction, player, distance, getUnitFromParam(lParam1)); } else { return runConditionalInSimpleWay(game, currentPlayerAction, player, distance); } } @Override public String toString() { return "HaveUnitsToDistantToEnemy"; } private boolean runUnitConditional(GameState game, PlayerAction currentPlayerAction, int player, DistanceParam distance, Unit unAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition //if (currentPlayerAction.getAction(unAlly) == null) { List<Unit> unitscurrent=new ArrayList<Unit>(); getPotentialUnitsSimpleWay(game, currentPlayerAction, player).forEach(unitscurrent::add); if(unitscurrent.contains(unAlly)) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if (d <= distance.getDistance()) { return true; } } } } return false; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player, DistanceParam distance) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnitsSimpleWay(game, currentPlayerAction, player)) { //if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if (d <= distance.getDistance()) { return true; } } } //} } return false; } }
4,016
35.189189
139
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/HaveUnitsinEnemyRange.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class HaveUnitsinEnemyRange extends AbstractConditionalFunction { @Override public boolean runFunction(List lParam1, HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); //PathFinding pf = (PathFinding) lParam1.get(3); //UnitTypeTable a_utt = (UnitTypeTable) lParam1.get(4); UnitTypeParam unitType = (UnitTypeParam) lParam1.get(5); parameters.add(unitType); if (hasUnitInParam(lParam1)) { return runUnitConditional(game, currentPlayerAction, player, getUnitFromParam(lParam1)); } else { return runConditionalInSimpleWay(game, currentPlayerAction, player); } } @Override public String toString() { return "HaveUnitsinEnemyRange"; } private boolean runUnitConditional(GameState game, PlayerAction currentPlayerAction, int player, Unit unAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition //if (currentPlayerAction.getAction(unAlly) == null) { List<Unit> unitscurrent=new ArrayList<Unit>(); getPotentialUnitsSimpleWay(game, currentPlayerAction, player).forEach(unitscurrent::add); if(unitscurrent.contains(unAlly)) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= u2.getAttackRange())) { return true; } } } } return false; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player) { PhysicalGameState pgs = game.getPhysicalGameState(); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnitsSimpleWay(game, currentPlayerAction, player)) { //if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= u2.getAttackRange())) { return true; } } } //} } return false; } }
3,760
34.149533
116
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/IConditionalFunction.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.dslForScriptGenerator.DSLBasicConditional.functions; import java.util.HashMap; import java.util.List; /** * * @author rubens */ public interface IConditionalFunction { /** * * @param lParam1 = GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt * @return */ public boolean runFunction(List lParam1, HashMap<Long, String> counterByFunction); public void setDSLUsed(); }
665
25.64
121
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLBasicConditional/functions/IsPlayerInPosition.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.dslForScriptGenerator.DSLBasicConditional.functions; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PriorityPositionParam; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; /** * * @author rubens */ public class IsPlayerInPosition extends AbstractConditionalFunction { private boolean executed; private boolean previousEval; public IsPlayerInPosition() { this.executed = false; this.previousEval = false; } @Override public boolean runFunction(List lParam1, HashMap<Long, String> counterByFunction) { GameState game = (GameState) lParam1.get(0); int player = (int) lParam1.get(1); PlayerAction currentPlayerAction = (PlayerAction) lParam1.get(2); PriorityPositionParam position = (PriorityPositionParam) lParam1.get(5); parameters.add(position); return runConditionalInSimpleWay(game, currentPlayerAction, player); } @Override public String toString() { return "IsPlayerInPosition"; } private boolean runConditionalInSimpleWay(GameState game, PlayerAction currentPlayerAction, int player) { if (game.getTime() == 0 || (!this.executed)) { this.executed = true; PriorityPositionParam position = getPriorityParam(); int codeposition = getCodePosition(position); int[] limits = getLimitOfPosition(game, codeposition); Unit unReference = getUnitForReference(game, player); if (unReference != null) { //check if the position is between the limits //check if it is between if (codeposition == 3 || codeposition == 1) { //if left or right if (unReference.getX() <= limits[1] && unReference.getX() >= limits[0]) { this.previousEval = true; return true; } } else { //if bottom or up if (unReference.getY() <= limits[1] && unReference.getY() >= limits[0]) { this.previousEval = true; return true; } } } this.previousEval = false; return false; } return this.previousEval; } private int[] getLimitOfPosition(GameState game, int codeposition) { int[] ret = new int[2]; if (codeposition == 3) { //if left ret[0] = 0; ret[1] = game.getPhysicalGameState().getWidth() / 2; } else if (codeposition == 1) { //if right ret[0] = game.getPhysicalGameState().getWidth() / 2; ret[1] = game.getPhysicalGameState().getWidth(); } else if (codeposition == 0) { //if top ret[0] = 0; ret[1] = game.getPhysicalGameState().getHeight() / 2; } else { //if bottom ret[0] = game.getPhysicalGameState().getHeight() / 2; ret[1] = game.getPhysicalGameState().getHeight(); } return ret; } private int getCodePosition(PriorityPositionParam position) { for (EnumPositionType enumPositionType : position.getSelectedPosition()) { return enumPositionType.code(); } return 0; } private Unit getUnitForReference(GameState game, int player) { for (Unit un : game.getUnits()) { if (un.getPlayer() == player) { if (un.getType().isStockpile) { return un; } } } //if the base is not found, returns any option for (Unit un : game.getUnits()) { if (un.getPlayer() == player) { return un; } } return null; } }
4,158
33.090164
109
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/AbstractBasicAction.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.dslForScriptGenerator.DSLCommand; /** * * @author rubens */ public abstract class AbstractBasicAction extends AbstractCommand { }
347
19.470588
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/AbstractBooleanAction.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.dslForScriptGenerator.DSLCommand; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.abstraction.pathfinding.AStarPathFinding; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PlayerAction; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian */ public abstract class AbstractBooleanAction extends AbstractCommand { protected List<ICommand> commandsBoolean = new ArrayList<>(); protected UnitTypeTable utt; public PlayerAction appendCommands(int player, GameState gs, PlayerAction currentActions, HashMap<Long, String> counterByFunction) { PathFinding pf = new AStarPathFinding(); for (ICommand command : commandsBoolean) { currentActions = command.getAction(gs, player, currentActions, pf, utt, counterByFunction); } return currentActions; } //This method removes the default wait action to a unit, which was added just for //avoid apply actions to units that doesnt sattisfy the boolean protected void restoreOriginalActions(GameState game, int player, ArrayList<Unit> unitstoApplyWait, PlayerAction currentPlayerAction) { for (Unit u : game.getUnits()) { if (unitstoApplyWait.contains(u) && u.getPlayer() == player) { currentPlayerAction.removeUnitAction(u, currentPlayerAction.getAction(u)); } } } //This method set a default wait action to a unit in order to avoid apply actions to units //that doesnt sattisfy the boolean protected void temporalWaitActions(GameState game, int player, ArrayList<Unit> unitstoApplyWait, PlayerAction currentPlayerAction) { for (Unit u : game.getUnits()) { if (unitstoApplyWait.contains(u) && u.getPlayer() == player) { currentPlayerAction.addUnitAction(u, new UnitAction(0)); } } } }
2,275
35.126984
139
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/AbstractCommand.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.dslForScriptGenerator.DSLCommand; import java.util.ArrayList; import java.util.List; import java.util.Random; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IBehavior; import ai.synthesis.dslForScriptGenerator.IDSLParameters.ICoordinates; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IDistance; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IPlayerTarget; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IQuantity; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.ConstructionTypeParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PlayerTargetParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import util.Pair; /** * * @author rubens and julian */ public abstract class AbstractCommand implements ICommand{ private List<IParameters> parameters; private iDSL dslFragment; private boolean hasDSLUsed; public AbstractCommand() { this.parameters = new ArrayList<>(); hasDSLUsed = false; } public List<IParameters> getParameters() { return parameters; } public void setParameters(List<IParameters> parameters) { this.parameters = parameters; } public void addParameter(IParameters param){ this.parameters.add(param); } public iDSL getDslFragment() { return dslFragment; } public void setDslFragment(iDSL dslFragment) { this.dslFragment = dslFragment; } public boolean isHasDSLUsed() { return hasDSLUsed; } public void setHasDSLUsed(boolean hasDSLused) { this.hasDSLUsed = hasDSLused; } public synchronized void setHasDSLUsed() { this.hasDSLUsed = true; } protected Unit getUnitAlly(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && currentPlayerAction.getAction(u) == null && game.getActionAssignment(u) == null && u.getResources() == 0){ unitAllys.add(u); } } for (Unit unitAlly : unitAllys) { if(currentPlayerAction.getAction(unitAlly) == null){ return unitAlly; } } return null; } protected Unit getTargetEnemyUnit(GameState game, PlayerAction currentPlayerAction, int player, Unit allyUnit) { IBehavior behavior = getBehavior(); //verify if there are behavior param if(behavior != null){ return getEnemybyBehavior(game, player, behavior, allyUnit); }else{ return getEnemyRandomic(game, player); } } protected Unit getEnemyRandomic(GameState game, int player){ int enemyPlayer = (1-player); ArrayList<Unit> units = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == enemyPlayer){ units.add(u); } } Random rand = new Random(); try { return units.get(rand.nextInt(units.size())); } catch (Exception e) { return units.get(0); } } protected List<ConstructionTypeParam> getTypeBuildFromParam() { List<ConstructionTypeParam> types = new ArrayList<>(); for (IParameters param : getParameters()) { if(param instanceof ConstructionTypeParam){ types.add((ConstructionTypeParam) param); } } return types; } protected List<UnitTypeParam> getTypeUnitFromParam() { List<UnitTypeParam> types = new ArrayList<>(); for (IParameters param : getParameters()) { if(param instanceof UnitTypeParam){ types.add((UnitTypeParam) param); } } return types; } private Unit getEnemybyBehavior(GameState game, int player, IBehavior behavior, Unit allyUnit) { return behavior.getEnemytByBehavior(game, player, allyUnit); } protected ResourceUsage getResourcesUsed(PlayerAction currentPlayerAction, PhysicalGameState pgs) { ResourceUsage res = new ResourceUsage(); for (Pair<Unit, UnitAction> action : currentPlayerAction.getActions()) { if(action.m_a != null && action.m_b != null){ res.merge(action.m_b.resourceUsage(action.m_a, pgs)); } } return res; } protected Iterable<Unit> getPotentialUnits(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && currentPlayerAction.getAction(u) == null && game.getActionAssignment(u) == null && u.getResources() == 0 && isUnitControlledByParam(u)){ unitAllys.add(u); } } return unitAllys; } protected boolean hasInPotentialUnits(GameState game, PlayerAction currentPlayerAction, Unit uAlly, int player) { if(uAlly.getPlayer() == player && currentPlayerAction.getAction(uAlly) == null && game.getActionAssignment(uAlly) == null && uAlly.getResources() == 0 && isUnitControlledByParam(uAlly)) { return true; } else { return false; } } protected ArrayList<Unit> getUnitsOfType(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && isUnitControlledByParam(u)){ unitAllys.add(u); } } return unitAllys; } protected ArrayList<Unit> getEnemyUnitsOfType(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitsEnemy = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == 1-player && isUnitControlledByParam(u)){ unitsEnemy.add(u); } } return unitsEnemy; } protected ArrayList<Unit> getAllyUnitsAttacking(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && isUnitControlledByParam(u) && currentPlayerAction.getAction(u)!=null){ if(currentPlayerAction.getAction(u).getType()==5) unitAllys.add(u); } } return unitAllys; } protected ArrayList<Unit> getAllyUnitsHarvesting(GameState game, PlayerAction currentPlayerAction, int player) { ArrayList<Unit> unitAllys = new ArrayList<>(); for (Unit u : game.getUnits()) { if(u.getPlayer() == player && currentPlayerAction.getAction(u)!=null){ if(currentPlayerAction.getAction(u).getType()==2 || currentPlayerAction.getAction(u).getType()==3 ) unitAllys.add(u); } } return unitAllys; } protected boolean isUnitControlledByParam(Unit u) { List<UnitTypeParam> unType = getTypeUnitFromParam(); for (UnitTypeParam unitTypeParam : unType) { for (EnumTypeUnits paramType : unitTypeParam.getParamTypes()) { if(u.getType().ID == paramType.code()){ return true; } } } return false; } private boolean hasUnitsStopped(GameState game, int player, PlayerAction currentPlayerAction) { for(Unit un : game.getUnits()){ if(un.getPlayer() == player && un.getResources() == 0){ if(currentPlayerAction.getAction(un) == null && game.getActionAssignment(un) == null){ return true; } } } return false; } protected IQuantity getQuantityFromParam() { for(IParameters param : getParameters()){ if(param instanceof IQuantity){ return (IQuantity) param; } } return null; } protected IDistance getDistanceFromParam() { for(IParameters param : getParameters()){ if(param instanceof IDistance){ return (IDistance) param; } } return null; } protected ICoordinates getCoordinatesFromParam() { for(IParameters param : getParameters()){ if(param instanceof ICoordinates){ return (ICoordinates) param; } } return null; } protected PlayerTargetParam getPlayerTargetFromParam() { for(IParameters param : getParameters()){ if(param instanceof IPlayerTarget){ return (PlayerTargetParam) param; } } return null; } private IBehavior getBehavior() { IBehavior beh = null; for (IParameters parameter : parameters) { if(parameter instanceof IBehavior){ beh = (IBehavior) parameter; } } return beh; } protected int getResourcesInCurrentAction(PlayerAction currentPlayerAction) { int resources = 0; for (Pair<Unit, UnitAction> action : currentPlayerAction.getActions()) { if (action.m_b.getUnitType() != null) { resources += action.m_b.getUnitType().cost; } } return resources; } }
10,403
32.453376
117
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSL_RunBattle.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ai.synthesis.dslForScriptGenerator.DSLCommand; import ai.core.AI; import ai.evaluation.EvaluationFunction; import ai.evaluation.SimpleSqrtEvaluationFunction3; import ai.mcts.naivemcts.NaiveMCTS; import ai.synthesis.dslForScriptGenerator.DslAI; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCompiler.IDSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCompiler.MainDSLCompiler; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.utils.ReduceDSLController; import gui.PhysicalGameStatePanel; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import javax.swing.JFrame; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens Classe responsável por rodar os confrontos entre duas IA's. * Ambiente totalmente observável. */ public class DSL_RunBattle { static AI[] strategies = null; private HashMap<BigDecimal, String> scriptsTable; IDSLCompiler compiler = new MainDSLCompiler(); EvaluationFunction evaluation = new SimpleSqrtEvaluationFunction3(); public boolean run(iDSL tupleAi1, iDSL tupleAi2, int iMap) throws Exception { ArrayList<String> log = new ArrayList<>(); //controle de tempo Instant timeInicial = Instant.now(); Duration duracao; log.add("Tupla A1 = " + tupleAi1.translate()); log.add("Tupla A2 = " + tupleAi2.translate()); List<String> maps = new ArrayList<>(Arrays.asList( //"maps/24x24/basesWorkers24x24A.xml" //"maps/32x32/basesWorkers32x32A.xml" //"maps/battleMaps/Others/RangedHeavyMixed.xml" //"maps/NoWhereToRun9x8.xml" //"maps/BroodWar/(4)BloodBath.scmB.xml" //"maps/16x16/basesWorkers16x16A.xml" "maps/8x8/basesWorkers8x8A.xml" )); UnitTypeTable utt = new UnitTypeTable(); PhysicalGameState pgs = PhysicalGameState.load(maps.get(iMap), utt); GameState gs = new GameState(pgs, utt); int MAXCYCLES = 20000; int PERIOD = 20; boolean gameover = false; if (pgs.getHeight() == 8) { MAXCYCLES = 9000; } if (pgs.getHeight() == 9) { MAXCYCLES = 9000; } if (pgs.getHeight() == 16) { MAXCYCLES = 10000; } if (pgs.getHeight() == 24) { MAXCYCLES = 11000; } if (pgs.getHeight() == 32) { MAXCYCLES = 12000; } if (pgs.getHeight() == 64) { MAXCYCLES = 17000; } AI ai1 = new NaiveMCTS(utt); AI ai2 = buildCommandsIA(utt, tupleAi1); /* Variáveis para coleta de tempo */ double ai1TempoMin = 9999, ai1TempoMax = -9999; double ai2TempoMin = 9999, ai2TempoMax = -9999; double sumAi1 = 0, sumAi2 = 0; int totalAction = 0; log.add("---------AIs---------"); log.add("AI 1 = " + ai1.toString()); log.add("AI 2 = " + ai2.toString() + "\n"); log.add("---------Mapa---------"); log.add("Mapa= " + maps.get(iMap) + "\n"); //método para fazer a troca dos players //JFrame w = PhysicalGameStatePanel.newVisualizer(gs, 740, 740, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); // JFrame w = PhysicalGameStatePanel.newVisualizer(gs,640,640,false,PhysicalGameStatePanel.COLORSCHEME_WHITE); long startTime; long timeTemp; //System.out.println("Tempo de execução P2="+(startTime = System.currentTimeMillis() - startTime)); long nextTimeToUpdate = System.currentTimeMillis() + PERIOD; do { if (System.currentTimeMillis() >= nextTimeToUpdate) { totalAction++; startTime = System.currentTimeMillis(); PlayerAction pa1 = ai1.getAction(0, gs); //dados de tempo ai1 timeTemp = (System.currentTimeMillis() - startTime); sumAi1 += timeTemp; //coleto tempo mínimo if (ai1TempoMin > timeTemp) { ai1TempoMin = timeTemp; } //coleto tempo maximo if (ai1TempoMax < timeTemp) { ai1TempoMax = timeTemp; } startTime = System.currentTimeMillis(); PlayerAction pa2 = ai2.getAction(1, gs); //dados de tempo ai2 timeTemp = (System.currentTimeMillis() - startTime); sumAi2 += timeTemp; //coleto tempo mínimo if (ai2TempoMin > timeTemp) { ai2TempoMin = timeTemp; } //coleto tempo maximo if (ai2TempoMax < timeTemp) { ai2TempoMax = timeTemp; } gs.issueSafe(pa1); gs.issueSafe(pa2); // simulate: gameover = gs.cycle(); //w.repaint(); nextTimeToUpdate += PERIOD; } else { try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } //avaliacao de tempo duracao = Duration.between(timeInicial, Instant.now()); } while (!gameover && (gs.getTime() < MAXCYCLES)); log.add("Total de actions= " + totalAction + " sumAi1= " + sumAi1 + " sumAi2= " + sumAi2 + "\n"); log.add("Tempos de AI 1 = " + ai1.toString()); log.add("Tempo minimo= " + ai1TempoMin + " Tempo maximo= " + ai1TempoMax + " Tempo medio= " + (sumAi1 / (long) totalAction)); log.add("Tempos de AI 2 = " + ai2.toString()); log.add("Tempo minimo= " + ai2TempoMin + " Tempo maximo= " + ai2TempoMax + " Tempo medio= " + (sumAi2 / (long) totalAction) + "\n"); log.add("Winner " + Integer.toString(gs.winner())); log.add("Game Over"); if (gs.winner() == -1) { System.out.println("Empate!" + ai1.toString() + " vs " + ai2.toString() + " Max Cycles =" + MAXCYCLES + " Time:" + duracao.toMinutes()); // System.out.println("eval "+e); } //System.exit(0); DslAI t = (DslAI) ai2; ReduceDSLController.removeUnactivatedParts(tupleAi1,t.getCommands()); //w.dispatchEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING)); return true; } private AI buildCommandsIA(UnitTypeTable utt, iDSL code) { HashMap<Long, String> counterByFunction = new HashMap<Long, String>(); List<ICommand> commandsGP = compiler.CompilerCode(code, utt); AI aiscript = new DslAI(utt, commandsGP, "P1", code, counterByFunction); return aiscript; } }
7,473
35.10628
148
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/ValidatorLines.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.dslForScriptGenerator.DSLCommand; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCompiler.MainDSLCompiler; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.builderDSLTree.BuilderDSLTreeSingleton; import java.util.List; import rts.units.UnitTypeTable; import ai.synthesis.dslForScriptGenerator.DSLCompiler.IDSLCompiler; import ai.synthesis.grammar.dslTree.utils.ReduceDSLController; /** * * @author rubens */ public class ValidatorLines { public static void main(String args[]) throws Exception { UnitTypeTable utt = new UnitTypeTable(); IDSLCompiler compiler = new MainDSLCompiler(); for (int i = 0; i < 1000; i++) { S1DSL dsl = BuilderDSLTreeSingleton.getInstance().buildS1Grammar(); List<ICommand> commandsDSL = compiler.CompilerCode(dsl, utt); System.out.println(dsl.translate() + "\n"); BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint(dsl); System.out.println(commandsDSL.toString()); DSL_RunBattle run = new DSL_RunBattle(); run.run(dsl, dsl, 0); System.out.println("Validação pós remoção"); run.run(dsl, dsl, 0); System.out.println("*******************************************************************************"); } } }
1,637
37.093023
114
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/AttackBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPlayerTarget; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PlayerTargetParam; import ai.abstraction.AbstractAction; import ai.abstraction.Attack; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public class AttackBasic extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); PlayerTargetParam p = getPlayerTargetFromParam(); EnumPlayerTarget enumPlayer = p.getSelectedPlayerTarget().get(0); String pt = enumPlayer.name(); int playerTarget = -1; if (pt == "Ally") { playerTarget = player; } if (pt == "Enemy") { playerTarget = 1 - player; } for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { //pick one enemy unit to set the action Unit targetEnemy = getTargetEnemyUnit(game, currentPlayerAction, playerTarget, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null) { AbstractAction action = new Attack(unAlly, targetEnemy, pf); UnitAction uAct = action.execute(game, resources); if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if(counterByFunction.containsKey(unAlly.getID())) { if(!counterByFunction.get(unAlly.getID()).equals("attack")) counterByFunction.put(unAlly.getID(), "attack"); } else { counterByFunction.put(unAlly.getID(), "attack"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{AttackBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); PlayerTargetParam p = getPlayerTargetFromParam(); EnumPlayerTarget enumPlayer = p.getSelectedPlayerTarget().get(0); String pt = enumPlayer.name(); int playerTarget = -1; if (pt == "Ally") { playerTarget = player; } if (pt == "Enemy") { playerTarget = 1 - player; } //pick one enemy unit to set the action Unit targetEnemy = getTargetEnemyUnit(game, currentPlayerAction, playerTarget, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { AbstractAction action = new Attack(unAlly, targetEnemy, pf); UnitAction uAct = action.execute(game, resources); if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if(counterByFunction.containsKey(unAlly.getID())) { if(!counterByFunction.get(unAlly.getID()).equals("attack")) counterByFunction.put(unAlly.getID(), "attack"); } else { counterByFunction.put(unAlly.getID(), "attack"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } return currentPlayerAction; } }
5,735
36.006452
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/BuildBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IPriorityPosition; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IQuantity; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.ConstructionTypeParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PriorityPositionParam; import ai.abstraction.AbstractAction; import ai.abstraction.Build; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.Player; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import static rts.UnitAction.DIRECTION_DOWN; import static rts.UnitAction.DIRECTION_LEFT; import static rts.UnitAction.DIRECTION_RIGHT; import static rts.UnitAction.DIRECTION_UP; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.Pair; /** * * @author rubens */ public class BuildBasic extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { //get the unit that it will be builded ConstructionTypeParam unitToBeBuilded = getUnitToBuild(); if (unitToBeBuilded != null) { //verify if the limit of units are reached if (!limitReached(game, player, currentPlayerAction)) { //check if we have resources if (game.getPlayer(player).getResources() >= getResourceCost(unitToBeBuilded, a_utt)) { //pick one work to build Unit workToBuild = getWorkToBuild(player, game, currentPlayerAction, a_utt, pf); if (workToBuild != null) { //execute the build action UnitAction unAcTemp = translateUnitAction(game, a_utt, workToBuild, currentPlayerAction, player, pf); if (unAcTemp != null) { setHasDSLUsed(); if (counterByFunction.containsKey(workToBuild.getID())) { if (!counterByFunction.get(workToBuild.getID()).equals("build")) { counterByFunction.put(workToBuild.getID(), "build"); } } else { counterByFunction.put(workToBuild.getID(), "build"); } currentPlayerAction.addUnitAction(workToBuild, unAcTemp); } } } } } return currentPlayerAction; } private Unit getWorkToBuild(int player, GameState game, PlayerAction currentPlayerAction, UnitTypeTable a_utt, PathFinding pf) { for (Unit unit : game.getUnits()) { //verify if the unit is free if (unit.getPlayer() == player && unit.getType() == a_utt.getUnitType("Worker") && game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null && translateUnitAction(game, a_utt, unit, currentPlayerAction, player, pf) != null) { return unit; } } return null; } protected boolean hasInPotentialUnitsWorkers(GameState game, PlayerAction currentPlayerAction, Unit uAlly, int player, UnitTypeTable a_utt, PathFinding pf) { if (uAlly.getPlayer() == player && currentPlayerAction.getAction(uAlly) == null && game.getActionAssignment(uAlly) == null && uAlly.getResources() == 0 && uAlly.getType() == a_utt.getUnitType("Worker") && translateUnitAction(game, a_utt, uAlly, currentPlayerAction, player, pf) != null) { return true; } else { return false; } } private UnitAction translateUnitAction(GameState game, UnitTypeTable a_utt, Unit unit, PlayerAction currentPlayerAction, int player, PathFinding pf) { List<Integer> reservedPositions = new LinkedList<>(); reservedPositions.addAll(game.getResourceUsage().getPositionsUsed()); reservedPositions.addAll(currentPlayerAction.getResourceUsage().getPositionsUsed()); PhysicalGameState pgs = game.getPhysicalGameState(); return buildConsideringPosition(player, reservedPositions, pgs, a_utt, unit, currentPlayerAction, game, pf); } private UnitAction buildConsideringPosition(int player, List<Integer> reservedPositions, PhysicalGameState pgs, UnitTypeTable a_utt, Unit unit, PlayerAction currentPlayerAction, GameState game, PathFinding pf) { PriorityPositionParam order = getPriorityParam(); UnitAction ua = null; //pick the type to be builded UnitType unitType = getUnitTyppe(a_utt); for (EnumPositionType enumPositionType : order.getSelectedPosition()) { if (enumPositionType.code() == 4) { for (int enumCodePosition : getDirectionByEnemy(game, unit)) { ua = new UnitAction(UnitAction.TYPE_PRODUCE, enumCodePosition, unitType); if (game.isUnitActionAllowed(unit, ua) && isPositionFree(game, ua, unit)) { return ua; } } } else { ua = new UnitAction(UnitAction.TYPE_PRODUCE, enumPositionType.code(), unitType); } if (game.isUnitActionAllowed(unit, ua) && isPositionFree(game, ua, unit)) { return ua; } } return null; } private List<Integer> getDirectionByEnemy(GameState game, Unit unit) { int player = unit.getPlayer(); int enemy = (1 - player); ArrayList<Integer> directions = new ArrayList<>(); //get (following the order) base, barrack or enemy. Unit enUnit = getOrderedUnit(enemy, game); //check if the enemy is left or right if (enUnit.getX() >= unit.getX()) { directions.add(DIRECTION_RIGHT); } else { directions.add(DIRECTION_LEFT); } //check if the enemy is up or bottom if (enUnit.getY() >= unit.getY()) { directions.add(DIRECTION_DOWN); } else { directions.add(DIRECTION_UP); } //return all possible positions return directions; } private Unit getOrderedUnit(int enemy, GameState game) { Unit base = null; Unit barrack = null; Unit other = null; for (Unit unit : game.getUnits()) { if (unit.getPlayer() == enemy) { if (base == null && unit.getType().ID == 1) { base = unit; } else if (barrack == null && unit.getType().ID == 2) { barrack = unit; } else if (other == null) { other = unit; } else { break; } } } if (base != null) { return base; } else if (barrack != null) { return barrack; } return other; } private boolean limitReached(GameState game, int player, PlayerAction currentPlayerAction) { IQuantity qtt = getQuantityFromParam(); //verify if the quantity of units associated with the specific type were reached. if (qtt.getQuantity() > getQuantityUnitsBuilded(game, player, currentPlayerAction)) { return false; } return true; } private int getQuantityUnitsBuilded(GameState game, int player, PlayerAction currentPlayerAction) { int ret = 0; HashSet<EnumTypeUnits> types = new HashSet<>(); //get types in EnumTypeUnits for (IParameters param : getParameters()) { if (param instanceof ConstructionTypeParam) { types.addAll(((ConstructionTypeParam) param).getParamTypes()); } } //count for (EnumTypeUnits type : types) { ret += countUnitsByType(game, player, currentPlayerAction, type); } return ret; } private int countUnitsByType(GameState game, int player, PlayerAction currentPlayerAction, EnumTypeUnits type) { int qtt = 0; //count units in state for (Unit unit : game.getUnits()) { if (unit.getPlayer() == player && unit.getType().ID == type.code()) { qtt++; } } // count units in currentPlayerAction for (Pair<Unit, UnitAction> action : currentPlayerAction.getActions()) { if (action.m_a.getType().ID == type.code()) { qtt++; } } return qtt; } private PriorityPositionParam getPriorityParam() { for (IParameters param : getParameters()) { if (param instanceof IPriorityPosition) { return (PriorityPositionParam) param; } } return null; } private boolean isPositionFree(GameState game, UnitAction ua, Unit trainUnit) { int x, y; x = trainUnit.getX(); y = trainUnit.getY(); //define direction switch (ua.getDirection()) { case DIRECTION_UP: y--; break; case DIRECTION_RIGHT: x++; break; case DIRECTION_DOWN: y++; break; case DIRECTION_LEFT: x--; break; } int width = game.getPhysicalGameState().getWidth(); int height = game.getPhysicalGameState().getHeight(); if ((x + y * width) >= (width * height)) { return false; } if ((x + y * width) < 0) { return false; } if (game.free(x, y)) { return true; } return false; } private ConstructionTypeParam getUnitToBuild() { for (IParameters param : getParameters()) { if (param instanceof ConstructionTypeParam) { return (ConstructionTypeParam) param; } } return null; } private int getResourceCost(ConstructionTypeParam unitToBeBuilded, UnitTypeTable a_utt) { if (unitToBeBuilded.getParamTypes().get(0) == EnumTypeUnits.Base) { return a_utt.getUnitType("Base").cost; } else { int c = a_utt.getUnitType("Barracks").cost; return a_utt.getUnitType("Barracks").cost; } } public int findBuildingPosition(List<Integer> reserved, int desiredX, int desiredY, Player p, PhysicalGameState pgs) { boolean[][] free = pgs.getAllFree(); int x, y; /* System.out.println("-" + desiredX + "," + desiredY + "-------------------"); for(int i = 0;i<free[0].length;i++) { for(int j = 0;j<free.length;j++) { System.out.print(free[j][i] + "\t"); } System.out.println(""); } */ for (int l = 1; l < Math.max(pgs.getHeight(), pgs.getWidth()); l++) { for (int side = 0; side < 4; side++) { switch (side) { case 0://up y = desiredY - l; if (y < 0) { continue; } for (int dx = -l; dx <= l; dx++) { x = desiredX + dx; if (x < 0 || x >= pgs.getWidth()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 1://right x = desiredX + l; if (x >= pgs.getWidth()) { continue; } for (int dy = -l; dy <= l; dy++) { y = desiredY + dy; if (y < 0 || y >= pgs.getHeight()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 2://down y = desiredY + l; if (y >= pgs.getHeight()) { continue; } for (int dx = -l; dx <= l; dx++) { x = desiredX + dx; if (x < 0 || x >= pgs.getWidth()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; case 3://left x = desiredX - l; if (x < 0) { continue; } for (int dy = -l; dy <= l; dy++) { y = desiredY + dy; if (y < 0 || y >= pgs.getHeight()) { continue; } int pos = x + y * pgs.getWidth(); if (!reserved.contains(pos) && free[x][y]) { return pos; } } break; } } } return -1; } private UnitType getUnitTyppe(UnitTypeTable a_utt) { ConstructionTypeParam unitToBeBuilded = getUnitToBuild(); if (unitToBeBuilded.getParamTypes().get(0) == EnumTypeUnits.Base) { return a_utt.getUnitType("Base"); } else { return a_utt.getUnitType("Barracks"); } } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{BuildBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit workToBuild, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); //get the unit that it will be builded ConstructionTypeParam unitToBeBuilded = getUnitToBuild(); if (unitToBeBuilded != null) { //verify if the limit of units are reached if (!limitReached(game, player, currentPlayerAction)) { //check if we have resources if (game.getPlayer(player).getResources() >= getResourceCost(unitToBeBuilded, a_utt)) { //pick one work to build //Unit workToBuild = getWorkToBuild(player, game, currentPlayerAction, a_utt); if (workToBuild != null && hasInPotentialUnitsWorkers(game, currentPlayerAction, workToBuild, player, a_utt, pf)) { //execute the build action UnitAction unAcTemp = translateUnitAction(game, a_utt, workToBuild, currentPlayerAction, player, pf); if (unAcTemp != null) { setHasDSLUsed(); if (counterByFunction.containsKey(workToBuild.getID())) { if (!counterByFunction.get(workToBuild.getID()).equals("build")) { counterByFunction.put(workToBuild.getID(), "build"); } } else { counterByFunction.put(workToBuild.getID(), "build"); } currentPlayerAction.addUnitAction(workToBuild, unAcTemp); } } } } } return currentPlayerAction; } }
17,867
38.443709
224
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/ClusterBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.abstraction.pathfinding.PathFinding; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens & Julian */ public class ClusterBasic extends AbstractBasicAction { int _cenX = 0; int _cenY = 0; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); if (((ArrayList<Unit>) getPotentialUnits(game, currentPlayerAction, player)).size() > 0) { CalcCentroide((ArrayList<Unit>) getPotentialUnits(game, currentPlayerAction, player)); } for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { //pick one enemy unit to set the action // int pX = getCoordinatesFromParam().getX(); // int pY = getCoordinatesFromParam().getY(); //pick the positions if (game.getActionAssignment(unAlly) == null && unAlly != null) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, _cenX + _cenY * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("cluster")) { counterByFunction.put(unAlly.getID(), "cluster"); } } else { counterByFunction.put(unAlly.getID(), "cluster"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToCoordinatesBasic:{" + listParam + "}}"; } private void CalcCentroide(ArrayList<Unit> unitAllys) { int x = 0, y = 0; for (Unit un : unitAllys) { x += un.getX(); y += un.getY(); } x = x / unitAllys.size(); y = y / unitAllys.size(); _cenX = x; _cenY = y; } }
3,556
34.929293
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/HarvestBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.AbstractAction; import ai.abstraction.Harvest; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public class HarvestBasic extends AbstractBasicAction implements IUnitCommand { public final HashSet<Long> unitsID = new HashSet<>(); boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //check if there are resources to harverst if (!hasResources(game)) { return currentPlayerAction; } //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //get ID qtd units to be used in harvest process getUnitsToHarvest(game, player, currentPlayerAction); //send the unit to harverst if (!unitsID.isEmpty()) { for (Long unID : unitsID) { Unit unit = game.getUnit(unID); //get base more closest Unit closestBase = getClosestBase(game, player, unit); //get target resource Unit closestResource = getClosestResource(game, unit, pf, resources); if (game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null && closestBase != null && closestResource != null) { AbstractAction action = new Harvest(unit, closestResource, closestBase, pf); UnitAction uAct = action.execute(game, resources); if (uAct != null) { setHasDSLUsed(); if (counterByFunction.containsKey(unit.getID())) { if (!counterByFunction.get(unit.getID()).equals("harvest")) { counterByFunction.put(unit.getID(), "harvest"); } } else { counterByFunction.put(unit.getID(), "harvest"); } currentPlayerAction.addUnitAction(unit, uAct); resources.merge(uAct.resourceUsage(unit, pgs)); } } } } return currentPlayerAction; } private void getUnitsToHarvest(GameState game, int player, PlayerAction currentPlayerAction) { //unitsID.clear(); //Remove units that arent of the player //System.out.println("crazyMama "+player); HashSet<Long> otherPlayerUnits = new HashSet<>(); for (Long unID : unitsID) { if (game.getUnit(unID) != null) { if (game.getUnit(unID).getPlayer() != player) { otherPlayerUnits.add(unID); } } } //if there is units to remove, remove if (!otherPlayerUnits.isEmpty()) { unitsID.removeAll(otherPlayerUnits); } //check if there is an unit collecting in the game /* for (Unit unit : game.getUnits()) { if (unit.getPlayer() == player && game.getActionAssignment(unit) != null){ if(game.getActionAssignment(unit).action.getType() == 2){ unitsID.add(unit.getID()); } } } */ //if the collection is empty if (unitsID.isEmpty()) { for (Unit unit : game.getUnits()) { if (unit.getPlayer() == player && game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null && unitsID.size() < getQuantityFromParam().getQuantity() && unit.getType().ID == 3) { unitsID.add(unit.getID()); } } } else { //check if all units continue to exist in the game HashSet<Long> remUnit = new HashSet<>(); for (Long unID : unitsID) { if (game.getUnit(unID) == null) { remUnit.add(unID); } } //if there is units to remove, remove if (!remUnit.isEmpty()) { unitsID.removeAll(remUnit); } //update the total quantity of units for (Unit unit : game.getUnits()) { if (unit.getPlayer() == player && game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null && unitsID.size() < getQuantityFromParam().getQuantity() && unit.getType().ID == 3) { unitsID.add(unit.getID()); } } } } private Unit getClosestResource(GameState game, Unit unit, PathFinding pf, ResourceUsage ru) { Unit closestResource = null; int closestDistance = 0; for (Unit u2 : game.getUnits()) { if (u2.getType().isResource) { int d = Math.abs(u2.getX() - unit.getX()) + Math.abs(u2.getY() - unit.getY()); if (closestResource == null || d < closestDistance) { if (pf.findPathToAdjacentPosition(unit, u2.getX() + u2.getY() * game.getPhysicalGameState().getWidth(), game, ru) != null || unit.getX() == u2.getX() + 1 || unit.getX() == u2.getX() - 1 || unit.getY() == u2.getY() + 1 || unit.getY() == u2.getY() - 1) { closestResource = u2; closestDistance = d; } } } } return closestResource; } private Unit getClosestBase(GameState game, int player, Unit unit) { Unit closestBase = null; int closestDistance = 0; for (Unit u2 : game.getUnits()) { if (u2.getType().isStockpile && u2.getPlayer() == player) { int d = Math.abs(u2.getX() - unit.getX()) + Math.abs(u2.getY() - unit.getY()); if (closestBase == null || d < closestDistance) { closestBase = u2; closestDistance = d; } } } return closestBase; } private boolean hasResources(GameState game) { for (Unit unit : game.getUnits()) { if (unit.getType().isResource) { return true; } } return false; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{HarvestBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit u, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //check if there are resources to harverst if (!hasResources(game)) { return currentPlayerAction; } //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //get ID qtd units to be used in harvest process getUnitsToHarvest(game, player, currentPlayerAction); //send the unit to harverst if (!unitsID.isEmpty()) { for (Long unID : unitsID) { if (unID == u.getID()) { Unit unit = game.getUnit(unID); //get base more closest Unit closestBase = getClosestBase(game, player, unit); //get target resource Unit closestResource = getClosestResource(game, unit, pf, resources); if (game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null && closestBase != null && closestResource != null) { AbstractAction action = new Harvest(unit, closestResource, closestBase, pf); UnitAction uAct = action.execute(game, resources); if (uAct != null) { setHasDSLUsed(); if (counterByFunction.containsKey(unit.getID())) { if (!counterByFunction.get(unit.getID()).equals("harvest")) { counterByFunction.put(unit.getID(), "harvest"); } } else { counterByFunction.put(unit.getID(), "harvest"); } currentPlayerAction.addUnitAction(unit, uAct); resources.merge(uAct.resourceUsage(unit, pgs)); } } } } } return currentPlayerAction; } }
10,338
38.461832
183
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/MoveAwayBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens & Julian */ public class MoveAwayBasic extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { //pick one enemy unit to set the action Unit targetEnemy = farthestAllyBase(pgs, player, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, targetEnemy.getX() + targetEnemy.getY() * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveAway")) { counterByFunction.put(unAlly.getID(), "moveAway"); } } else { counterByFunction.put(unAlly.getID(), "moveAway"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } // if(move==null) // { // uAct=wait; // } } } return currentPlayerAction; } public Unit farthestAllyBase(PhysicalGameState pgs, int player, Unit unitAlly) { Unit farthestBase = null; int farthesttDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getType().name == "Base") { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int d = Math.abs(u2.getX() - unitAlly.getX()) + Math.abs(u2.getY() - unitAlly.getY()); if (farthestBase == null || d > farthesttDistance) { farthestBase = u2; farthesttDistance = d; } } } } return farthestBase; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToUnitBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); if (unAlly != null && currentPlayerAction.getAction(unAlly) != null) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //pick one enemy unit to set the action Unit targetEnemy = farthestAllyBase(pgs, player, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { UnitAction uAct = null; UnitAction move = pf.findPathToPositionInRange(unAlly, targetEnemy.getX() + targetEnemy.getY() * pgs.getWidth(), unAlly.getAttackRange(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveAway")) { counterByFunction.put(unAlly.getID(), "moveAway"); } } else { counterByFunction.put(unAlly.getID(), "moveAway"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } // if(move==null) // { // uAct=wait; // } } return currentPlayerAction; } }
6,059
36.875
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/MoveToCoordinatesBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import ai.abstraction.pathfinding.PathFinding; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens & Julian */ public class MoveToCoordinatesBasic extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; String originalPieceGrammar; String originalPieceGrammarWord; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); //pick the positions if (game.getActionAssignment(unAlly) == null && unAlly != null) { UnitAction uAct = null; UnitAction move = pf.findPath(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move == null) { move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); } if (move != null && game.isUnitActionAllowed(unAlly, move)) { uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToCoordinates")) { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } } else { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToCoordinatesBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); if (unAlly != null && currentPlayerAction.getAction(unAlly) != null && unAlly.getPlayer() != player) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); if (game.getActionAssignment(unAlly) == null && unAlly != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToCoordinates")) { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } } else { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } setHasDSLUsed(); currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } return currentPlayerAction; } /** * @return the originalPieceGrammar */ public String getOriginalPieceGrammar() { return originalPieceGrammar; } /** * @param originalPieceGrammar the originalPieceGrammar to set */ public void setOriginalPieceGrammar(String originalPieceGrammar) { this.originalPieceGrammar = originalPieceGrammar; } public String getOriginalPieceGrammarWord() { return originalPieceGrammarWord; } public void setOriginalPieceGrammarWord(String originalPieceGrammarWord) { this.originalPieceGrammarWord = originalPieceGrammarWord; } }
6,076
36.745342
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/MoveToCoordinatesBasic_old.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens & Julian */ public class MoveToCoordinatesBasic_old extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { //pick one enemy unit to set the action int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); //pick the positions if (game.getActionAssignment(unAlly) == null && unAlly != null) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToCoordinates")) { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } } else { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToCoordinatesBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); if (unAlly != null && currentPlayerAction.getAction(unAlly) != null) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //pick one enemy unit to set the action int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); //pick the positions if (game.getActionAssignment(unAlly) == null && unAlly != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToCoordinates")) { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } } else { counterByFunction.put(unAlly.getID(), "moveToCoordinates"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } return currentPlayerAction; } }
5,285
37.867647
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/MoveToCoordinatesOnce.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IQuantity; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public class MoveToCoordinatesOnce extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; String originalPieceGrammar; String originalPieceGrammarWord; HashSet<Unit> unitsToMove; private boolean hasExecuted; public MoveToCoordinatesOnce() { this.unitsToMove = new HashSet<>(); this.hasExecuted = false; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { if (game.getTime() == 0) { this.hasExecuted = false; } if (this.hasExecuted) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); IQuantity qtd = getQuantityFromParam(); cleanControlledUnits(game); for (Unit potentialUnit : getPotentialUnits(game, currentPlayerAction, player)) { if (game.getActionAssignment(potentialUnit) == null) { if (unitsToMove.size() < qtd.getQuantity()) { unitsToMove.add(potentialUnit); } } } if (unitsToMove.isEmpty()) { return currentPlayerAction; } //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); for (Unit unAlly : unitsToMove) { //pick the positions int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); if (unAlly.getX() == pX && unAlly.getY() == pY) { this.hasExecuted = true; unitsToMove.clear(); return currentPlayerAction; } if (game.getActionAssignment(unAlly) == null && unAlly != null) { UnitAction uAct = null; UnitAction move = pf.findPath(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move == null) { move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); } if (move != null && game.isUnitActionAllowed(unAlly, move)) { uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveOnceToCoord")) { counterByFunction.put(unAlly.getID(), "moveOnceToCoord"); } } else { counterByFunction.put(unAlly.getID(), "moveOnceToCoord"); } setHasDSLUsed(); currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToCoordinatesOnce:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); if (game.getTime() == 0) { this.hasExecuted = false; } if (this.hasExecuted) { return currentPlayerAction; } if (unAlly != null && currentPlayerAction.getAction(unAlly) != null && unAlly.getPlayer() != player) { return currentPlayerAction; } //check if the unit is on type if (!isUnitControlledByParam(unAlly)) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); IQuantity qtd = getQuantityFromParam(); cleanControlledUnits(game); if (unitsToMove.size() < qtd.getQuantity()) { unitsToMove.add(unAlly); } else { //check if the unit is in controlled units if (!unitsToMove.contains(unAlly)) { return currentPlayerAction; } } //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); int pX = getCoordinatesFromParam().getX(); int pY = getCoordinatesFromParam().getY(); if (unAlly.getX() == pX && unAlly.getY() == pY) { this.hasExecuted = true; unitsToMove.clear(); return currentPlayerAction; } if (game.getActionAssignment(unAlly) == null && unAlly != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { UnitAction uAct = null; UnitAction move = pf.findPathToAdjacentPosition(unAlly, pX + pY * pgs.getWidth(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)); uAct = move; if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveOnceToCoord")) { counterByFunction.put(unAlly.getID(), "moveOnceToCoord"); } } else { counterByFunction.put(unAlly.getID(), "moveOnceToCoord"); } setHasDSLUsed(); currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } return currentPlayerAction; } /** * @return the originalPieceGrammar */ public String getOriginalPieceGrammar() { return originalPieceGrammar; } /** * @param originalPieceGrammar the originalPieceGrammar to set */ public void setOriginalPieceGrammar(String originalPieceGrammar) { this.originalPieceGrammar = originalPieceGrammar; } public String getOriginalPieceGrammarWord() { return originalPieceGrammarWord; } public void setOriginalPieceGrammarWord(String originalPieceGrammarWord) { this.originalPieceGrammarWord = originalPieceGrammarWord; } private void cleanControlledUnits(GameState game) { List<Unit> unitsRemove = new ArrayList<>(); for (Unit unit : unitsToMove) { if (game.getUnit(unit.getID()) == null) { unitsRemove.add(unit); } } for (Unit unit : unitsRemove) { unitsToMove.remove(unit); } } }
8,355
34.709402
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/MoveToUnitBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPlayerTarget; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PlayerTargetParam; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.HashMap; import java.util.HashSet; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.UnitAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens & Julian */ public class MoveToUnitBasic extends AbstractBasicAction implements IUnitCommand { boolean needUnit = false; @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); PlayerTargetParam p = getPlayerTargetFromParam(); EnumPlayerTarget enumPlayer = p.getSelectedPlayerTarget().get(0); String pt = enumPlayer.name(); int playerTarget = -1; if (pt == "Ally") { playerTarget = player; } if (pt == "Enemy") { playerTarget = 1 - player; } for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { //pick one enemy unit to set the action Unit targetEnemy = getTargetEnemyUnit(game, currentPlayerAction, playerTarget, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null) { UnitAction uAct = null; UnitAction move = pf.findPathToPositionInRange(unAlly, targetEnemy.getX() + targetEnemy.getY() * pgs.getWidth(), unAlly.getAttackRange(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)){ uAct = move; } if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToUnit")) { counterByFunction.put(unAlly.getID(), "moveToUnit"); } } else { counterByFunction.put(unAlly.getID(), "moveToUnit"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } } return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{MoveToUnitBasic:{" + listParam + "}}"; } public void setUnitIsNecessary() { this.needUnit = true; } public void setUnitIsNotNecessary() { this.needUnit = false; } @Override public Boolean isNecessaryUnit() { return needUnit; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit unAlly, HashMap<Long, String> counterByFunction) { //usedCommands.add(getOriginalPieceGrammar()+")"); if (unAlly != null && currentPlayerAction.getAction(unAlly) != null && unAlly.getPlayer() != player) { return currentPlayerAction; } ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); PlayerTargetParam p = getPlayerTargetFromParam(); EnumPlayerTarget enumPlayer = p.getSelectedPlayerTarget().get(0); String pt = enumPlayer.name(); int playerTarget = -1; if (pt == "Ally") { playerTarget = player; } if (pt == "Enemy") { playerTarget = 1 - player; } //pick one enemy unit to set the action Unit targetEnemy = getTargetEnemyUnit(game, currentPlayerAction, playerTarget, unAlly); if (game.getActionAssignment(unAlly) == null && unAlly != null && targetEnemy != null && hasInPotentialUnits(game, currentPlayerAction, unAlly, player)) { UnitAction uAct = null; UnitAction move = pf.findPathToPositionInRange(unAlly, targetEnemy.getX() + targetEnemy.getY() * pgs.getWidth(), unAlly.getAttackRange(), game, resources); if (move != null && game.isUnitActionAllowed(unAlly, move)){ uAct = move; } if (uAct != null && (uAct.getType() == 5 || uAct.getType() == 1)) { setHasDSLUsed(); if (counterByFunction.containsKey(unAlly.getID())) { if (!counterByFunction.get(unAlly.getID()).equals("moveToUnit")) { counterByFunction.put(unAlly.getID(), "moveToUnit"); } } else { counterByFunction.put(unAlly.getID(), "moveToUnit"); } currentPlayerAction.addUnitAction(unAlly, uAct); resources.merge(uAct.resourceUsage(unAlly, pgs)); } } return currentPlayerAction; } }
6,233
39.480519
188
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicAction/TrainBasic.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.dslForScriptGenerator.DSLCommand.DSLBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IPriorityPosition; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IQuantity; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.ConstructionTypeParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PriorityPositionParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.UnitTypeParam; import ai.abstraction.AbstractAction; import ai.abstraction.Train; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import rts.GameState; import rts.Player; import rts.PlayerAction; import rts.UnitAction; import static rts.UnitAction.DIRECTION_DOWN; import static rts.UnitAction.DIRECTION_LEFT; import static rts.UnitAction.DIRECTION_RIGHT; import static rts.UnitAction.DIRECTION_UP; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.Pair; /** * * @author rubens */ public class TrainBasic extends AbstractBasicAction { @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { int resourcesUsed = getResourcesInCurrentAction(currentPlayerAction); if ((game.getPlayer(player).getResources() - resourcesUsed) >= valueOfUnitsToBuild(game, player, a_utt) && limitReached(game, player, currentPlayerAction)) { //get units basead in type to produce List<Unit> unitToBuild = getUnitsToBuild(game, player); Player p = game.getPlayer(player); //produce the type of unit in param for (Unit unit : unitToBuild) { if (game.getActionAssignment(unit) == null && currentPlayerAction.getAction(unit) == null) { UnitAction unTemp = translateUnitAction(game, a_utt, unit, p); if (unTemp != null) { setHasDSLUsed(); if(counterByFunction.containsKey(unit.getID())) { if(!counterByFunction.get(unit.getID()).equals("train")) counterByFunction.put(unit.getID(), "train"); } else { counterByFunction.put(unit.getID(), "train"); } currentPlayerAction.addUnitAction(unit, unTemp); } } } } return currentPlayerAction; } private List<Unit> getUnitsToBuild(GameState game, int player) { List<Unit> units = new ArrayList<>(); //pick the units basead in the types List<ConstructionTypeParam> types = getTypeBuildFromParam(); for (Unit un : game.getUnits()) { if (un.getPlayer() == player) { if (unitIsType(un, types)) { units.add(un); } } } return units; } private boolean unitIsType(Unit un, List<ConstructionTypeParam> types) { for (ConstructionTypeParam type : types) { if (type.getParamTypes().contains(EnumTypeUnits.byName(un.getType().name))) { return true; } } return false; } private UnitAction translateUnitAction(GameState game, UnitTypeTable a_utt, Unit unit, Player p) { List<UnitTypeParam> types = getTypeUnitFromParam(); for (UnitTypeParam type : types) { for (EnumTypeUnits en : type.getParamTypes()) { if(p.getResources() >= a_utt.getUnitType(en.code()).cost) { UnitAction uAct = null; //train based in PriorityPosition uAct = trainUnitBasedInPriorityPosition(game, unit, a_utt.getUnitType(en.code())); if (uAct == null) { AbstractAction action = new Train(unit, a_utt.getUnitType(en.code())); uAct = action.execute(game); } if (uAct != null && uAct.getType() == 4) { return uAct; } } } } return null; } private boolean limitReached(GameState game, int player, PlayerAction currentPlayerAction) { IQuantity qtt = getQuantityFromParam(); //verify if the quantity of units associated with the specific type were reached. if (qtt.getQuantity() <= getQuantityUnitsBuilded(game, player, currentPlayerAction)) { return false; } return true; } private int getQuantityUnitsBuilded(GameState game, int player, PlayerAction currentPlayerAction) { int ret = 0; HashSet<EnumTypeUnits> types = new HashSet<>(); //get types in EnumTypeUnits for (IParameters param : getParameters()) { if (param instanceof UnitTypeParam) { types.addAll(((UnitTypeParam) param).getParamTypes()); } } //count for (EnumTypeUnits type : types) { ret += countUnitsByType(game, player, currentPlayerAction, type); } return ret; } private int countUnitsByType(GameState game, int player, PlayerAction currentPlayerAction, EnumTypeUnits type) { int qtt = 0; //count units in state for (Unit unit : game.getUnits()) { if (unit.getPlayer() == player && unit.getType().ID == type.code()) { qtt++; } } // count units in currentPlayerAction for (Pair<Unit, UnitAction> action : currentPlayerAction.getActions()) { if ((action.m_b.getUnitType() != null)) { if (action.m_b.getUnitType().ID == type.code()) { qtt++; } } } return qtt; } private UnitAction trainUnitBasedInPriorityPosition(GameState game, Unit unit, UnitType unitType) { PriorityPositionParam order = getPriorityParam(); UnitAction ua = null; for (EnumPositionType enumPositionType : order.getSelectedPosition()) { if (enumPositionType.code() == 4) { for (int enumCodePosition : getDirectionByEnemy(game, unit)) { ua = new UnitAction(UnitAction.TYPE_PRODUCE, enumCodePosition, unitType); if (game.isUnitActionAllowed(unit, ua) && isPositionFree(game, ua, unit)) { return ua; } } } else { ua = new UnitAction(UnitAction.TYPE_PRODUCE, enumPositionType.code(), unitType); } if (game.isUnitActionAllowed(unit, ua) && isPositionFree(game, ua, unit)) { return ua; } } return null; } private List<Integer> getDirectionByEnemy(GameState game, Unit unit) { int player = unit.getPlayer(); int enemy = (1 - player); ArrayList<Integer> directions = new ArrayList<>(); //get (following the order) base, barrack or enemy. Unit enUnit = getOrderedUnit(enemy, game); //check if the enemy is left or right if (enUnit.getX() >= unit.getX()) { directions.add(DIRECTION_RIGHT); } else { directions.add(DIRECTION_LEFT); } //check if the enemy is up or bottom if (enUnit.getY() >= unit.getY()) { directions.add(DIRECTION_DOWN); } else { directions.add(DIRECTION_UP); } //return all possible positions return directions; } private Unit getOrderedUnit(int enemy, GameState game) { Unit base = null; Unit barrack = null; Unit other = null; for (Unit unit : game.getUnits()) { if (unit.getPlayer() == enemy) { if (base == null && unit.getType().ID == 1) { base = unit; } else if (barrack == null && unit.getType().ID == 2) { barrack = unit; } else if (other == null) { other = unit; } else { break; } } } if (base != null) { return base; } else if (barrack != null) { return barrack; } return other; } private PriorityPositionParam getPriorityParam() { for (IParameters param : getParameters()) { if (param instanceof IPriorityPosition) { return (PriorityPositionParam) param; } } return null; } private boolean isPositionFree(GameState game, UnitAction ua, Unit trainUnit) { int x, y; x = trainUnit.getX(); y = trainUnit.getY(); //define direction switch (ua.getDirection()) { case DIRECTION_UP: y--; break; case DIRECTION_RIGHT: x++; break; case DIRECTION_DOWN: y++; break; case DIRECTION_LEFT: x--; break; } try { if (game.free(x, y)) { return true; } } catch (Exception e) { return false; } return false; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } //remove the last comma. listParam = listParam.substring(0, listParam.lastIndexOf(",")); listParam += "}"; return "{TrainBasic:{" + listParam + "}}"; } private int valueOfUnitsToBuild(GameState game, int player, UnitTypeTable a_utt) { int v = 999; List<UnitTypeParam> types = getTypeUnitFromParam(); for (UnitTypeParam type : types) { for (EnumTypeUnits en : type.getParamTypes()) { if(v > a_utt.getUnitType(en.code()).cost){ v = a_utt.getUnitType(en.code()).cost; } } } return v; } }
10,999
33.375
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/AllyRange.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if some enemy unit is in the * attack range of an ally unit */ public class AllyRange extends AbstractBooleanAction { public AllyRange(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //now we iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { boolean applyWait = true; if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= unAlly.getAttackRange())) { applyWait = false; } } } if (applyWait) { unitstoApplyWait.add(unAlly); } } } //here we set with wait the units that dont satisfy the condition temporalWaitActions(game, player, unitstoApplyWait, currentPlayerAction); //here we apply the action just over the units that satisfy the condition currentPlayerAction = appendCommands(player, game, currentPlayerAction,counterByFunction); //here we remove the wait action f the other units and the flow continues restoreOriginalActions(game, player, unitstoApplyWait, currentPlayerAction); return currentPlayerAction; } @Override public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{AllyRange:{" + listParam + "}}"; } }
3,680
36.948454
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/DistanceFromEnemy.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if some unitAlly is in a * distance x of an enemy */ public class DistanceFromEnemy extends AbstractBooleanAction { public DistanceFromEnemy(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { boolean applyWait = true; if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if (d <= getDistanceFromParam().getDistance()) { applyWait = false; } } } if (applyWait) { unitstoApplyWait.add(unAlly); } } } //here we set with wait the units that dont satisfy the condition temporalWaitActions(game, player, unitstoApplyWait, currentPlayerAction); //here we apply the action just over the units that satisfy the condition currentPlayerAction = appendCommands(player, game, currentPlayerAction,counterByFunction); //here we remove the wait action f the other units and the flow continues restoreOriginalActions(game, player, unitstoApplyWait, currentPlayerAction); return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } return "{DistanceFromEnemy:{" + listParam + "}}"; } }
3,583
37.12766
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/EnemyRange.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if some unitAlly is in the * attack range of an enemy */ public class EnemyRange extends AbstractBooleanAction { public EnemyRange(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //now whe iterate for all ally units in order to discover wich one satisfy the condition for (Unit unAlly : getPotentialUnits(game, currentPlayerAction, player)) { boolean applyWait = true; if (currentPlayerAction.getAction(unAlly) == null) { for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() != player) { int dx = u2.getX() - unAlly.getX(); int dy = u2.getY() - unAlly.getY(); double d = Math.sqrt(dx * dx + dy * dy); //If satisfies, an action is applied to that unit. Units that not satisfies will be set with // an action wait. if ((d <= u2.getAttackRange())) { applyWait = false; } } } if (applyWait) { unitstoApplyWait.add(unAlly); } } } //here we set with wait the units that dont satisfy the condition temporalWaitActions(game, player, unitstoApplyWait, currentPlayerAction); //here we apply the action just over the units that satisfy the condition currentPlayerAction = appendCommands(player, game, currentPlayerAction, counterByFunction); //here we remove the wait action f the other units and the flow continues restoreOriginalActions(game, player, unitstoApplyWait, currentPlayerAction); return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{EnemyRange:{" + listParam + "}}"; } }
3,687
37.020619
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/IfFunction.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLBasicConditional.SimpleConditional; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public class IfFunction implements ICommand, IUnitCommand { protected SimpleConditional conditional; protected List<ICommand> commandsThen = new ArrayList<>(); protected List<ICommand> commandsElse = new ArrayList<>(); public void setConditional(SimpleConditional conditional) { this.conditional = conditional; } public SimpleConditional getConditional() { return this.conditional; } public void setCommandsThen(List<ICommand> commandsThen) { this.commandsThen = commandsThen; } public void includeFullCommandsThen(List<ICommand> commandsThen) { this.commandsThen.addAll(commandsThen); } public void includeFullCommandsElse(List<ICommand> commandsElse) { this.commandsElse.addAll(commandsElse); } public void setCommandsElse(List<ICommand> commandsElse) { this.commandsElse = commandsElse; } public void addCommandsThen(ICommand commandThen) { this.commandsThen.add(commandThen); } public void addCommandsElse(ICommand commandElse) { this.commandsElse.add(commandElse); } public List<ICommand> getCommandsThen() { return commandsThen; } public List<ICommand> getCommandsElse() { return commandsElse; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { if (conditional.runConditional(game, player, currentPlayerAction, pf, a_utt, counterByFunction)) { for (ICommand command : commandsThen) { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } else { if (!commandsElse.isEmpty()) { for (ICommand command : commandsElse) { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } return currentPlayerAction; } public String toString() { String listParam = conditional.toString(); listParam += " Then:{"; for (ICommand command : commandsThen) { listParam += command.toString() + ","; } //remove the last comma. if(listParam.lastIndexOf(",")>0){ listParam = listParam.substring(0, listParam.lastIndexOf(",")); } listParam += "}"; if (!commandsElse.isEmpty()) { listParam += " Else:{"; for (ICommand command : commandsElse) { listParam += command.toString() + ","; } //remove the last comma. if(listParam.lastIndexOf(",")>0){ listParam = listParam.substring(0, listParam.lastIndexOf(",")); } listParam += "}"; } return "{If:{" + listParam + "}}"; } @Override public Boolean isNecessaryUnit() { //look in the conditional if it needs a Unit if (conditional.isNecessaryUnit()) { return true; } for (ICommand iCommand : commandsThen) { if (iCommand instanceof IUnitCommand) { IUnitCommand iUnitCom = (IUnitCommand) iCommand; if (iUnitCom.isNecessaryUnit()) { return true; } } } for (ICommand iCommand : commandsElse) { if (iCommand instanceof IUnitCommand) { IUnitCommand iUnitCom = (IUnitCommand) iCommand; if (iUnitCom.isNecessaryUnit()) { return true; } } } return false; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit u, HashMap<Long, String> counterByFunction) { if (conditional.isNecessaryUnit()) { if (conditional.runConditional(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction)) { for (ICommand command : commandsThen) { //currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt); if (command instanceof IUnitCommand) { IUnitCommand tempUnit = (IUnitCommand) command; if (tempUnit.isNecessaryUnit()) { currentPlayerAction = tempUnit.getAction(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction); } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } else { if (!commandsElse.isEmpty()) { for (ICommand command : commandsElse) { if (command instanceof IUnitCommand) { IUnitCommand tempUnit = (IUnitCommand) command; if (tempUnit.isNecessaryUnit()) { currentPlayerAction = tempUnit.getAction(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction); } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } } } else { if (conditional.runConditional(game, player, currentPlayerAction, pf, a_utt, counterByFunction)) { for (ICommand command : commandsThen) { //currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt); if (command instanceof IUnitCommand) { IUnitCommand tempUnit = (IUnitCommand) command; if (tempUnit.isNecessaryUnit()) { currentPlayerAction = tempUnit.getAction(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction); } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } else { if (!commandsElse.isEmpty()) { for (ICommand command : commandsElse) { if (command instanceof IUnitCommand) { IUnitCommand tempUnit = (IUnitCommand) command; if (tempUnit.isNecessaryUnit()) { currentPlayerAction = tempUnit.getAction(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction); } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } else { currentPlayerAction = command.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } } } return currentPlayerAction; } @Override public boolean isHasDSLUsed() { return true; } }
8,763
38.836364
183
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/NAllyUnitsAttacking.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if there are X ally units of * type t attacking */ public class NAllyUnitsAttacking extends AbstractBooleanAction { public NAllyUnitsAttacking(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //here we validate if there are x ally units of type t in the map if (getAllyUnitsAttacking(game, currentPlayerAction, player).size() >= getQuantityFromParam().getQuantity()) { currentPlayerAction = appendCommands(player, game, currentPlayerAction, counterByFunction); } return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{NAllyUnitsAttacking:{" + listParam + "}}"; } }
2,431
34.764706
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/NAllyUnitsHarvesting.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if there are X ally units * harvesting */ public class NAllyUnitsHarvesting extends AbstractBooleanAction { public NAllyUnitsHarvesting(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //here we validate if there are x ally units of type t in the map if (getAllyUnitsHarvesting(game, currentPlayerAction, player).size() >= getQuantityFromParam().getQuantity()) { currentPlayerAction = appendCommands(player, game, currentPlayerAction, counterByFunction); } return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{NAllyUnitsHarvesting:{" + listParam + "}}"; } }
2,426
34.691176
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/NAllyUnitsofType.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.abstraction.pathfinding.PathFinding; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if there are X ally units of * type t in the map */ public class NAllyUnitsofType extends AbstractBooleanAction { public NAllyUnitsofType(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //here we validate if there are x ally units of type t in the map if (getUnitsOfType(game, currentPlayerAction, player).size() >= getQuantityFromParam().getQuantity()) { currentPlayerAction = appendCommands(player, game, currentPlayerAction, counterByFunction); } return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{NAllyUnitsofType:{" + listParam + "}}"; } }
2,415
35.059701
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicBoolean/NEnemyUnitsofType.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.dslForScriptGenerator.DSLCommand.DSLBasicBoolean; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBooleanAction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.abstraction.pathfinding.PathFinding; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PhysicalGameState; import rts.PlayerAction; import rts.ResourceUsage; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens Julian This condition evaluates if there are X enemy units of * type t in the map */ public class NEnemyUnitsofType extends AbstractBooleanAction { public NEnemyUnitsofType(List<ICommand> commandsBoolean) { this.commandsBoolean = commandsBoolean; } @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long,String> counterByFunction) { utt = a_utt; ResourceUsage resources = new ResourceUsage(); PhysicalGameState pgs = game.getPhysicalGameState(); ArrayList<Unit> unitstoApplyWait = new ArrayList<>(); //update variable resources resources = getResourcesUsed(currentPlayerAction, pgs); //here we validate if there are x ally units of type t in the map if (getEnemyUnitsOfType(game, currentPlayerAction, player).size() >= getQuantityFromParam().getQuantity()) { currentPlayerAction = appendCommands(player, game, currentPlayerAction, counterByFunction); } return currentPlayerAction; } public String toString() { String listParam = "Params:{"; for (IParameters parameter : getParameters()) { listParam += parameter.toString() + ","; } listParam += "Actions:{"; for (ICommand command : commandsBoolean) { listParam += command.toString(); } //remove the last comma. // listParam = listParam.substring(0, listParam.lastIndexOf(",")); // listParam += "}"; return "{NEnemyUnitsofType:{" + listParam + "}}"; } }
2,424
34.661765
174
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLBasicLoops/ForFunction.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.dslForScriptGenerator.DSLCommand.DSLBasicLoops; import ai.abstraction.pathfinding.PathFinding; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.IUnitCommand; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public class ForFunction implements ICommand{ protected List<ICommand> commandsFor = new ArrayList<>(); @Override public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction) { for(Unit u : getAllyUnits(game, player)){ for (ICommand commandFor : commandsFor) { if(commandFor instanceof IUnitCommand && ((IUnitCommand)commandFor).isNecessaryUnit()){ IUnitCommand commandWithUnit = (IUnitCommand)commandFor; currentPlayerAction = commandWithUnit.getAction(game, player, currentPlayerAction, pf, a_utt, u, counterByFunction); }else{ currentPlayerAction = commandFor.getAction(game, player, currentPlayerAction, pf, a_utt, counterByFunction); } } } return currentPlayerAction; } public List<ICommand> getCommandsFor() { return commandsFor; } public void setCommandsFor(List<ICommand> commandsFor) { this.commandsFor.addAll(commandsFor); } private Iterable<Unit> getAllyUnits(GameState game, int player) { ArrayList<Unit> units = new ArrayList<>(); for (Unit unit : game.getUnits()) { if(unit.getPlayer() == player){ units.add(unit); } } return units; } @Override public String toString() { String listParam = ""; for (ICommand iCommand : commandsFor) { listParam += iCommand.toString() + ","; } //remove the last comma listParam = listParam.substring(0, listParam.lastIndexOf(",")); return "forFunction{" + listParam + '}'; } @Override public boolean isHasDSLUsed() { return true; } }
2,601
30.349398
175
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLEnumerators/EnumPlayerTarget.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.dslForScriptGenerator.DSLCommand.DSLEnumerators; /** * * @author rubens */ public enum EnumPlayerTarget { Ally(0), Enemy(1); private final int code; EnumPlayerTarget(int code) { this.code = code; } public int code() { return this.code; } public static EnumPlayerTarget byCode(int codigo) { for (EnumPlayerTarget t : EnumPlayerTarget.values()) { if (codigo == t.code()) { return t; } } throw new IllegalArgumentException("invalid code!"); } public static EnumPlayerTarget byName(String name) { if (name.equals("Ally")) { return EnumPlayerTarget.Ally; } else if (name.equals("Enemy")) { return EnumPlayerTarget.Enemy; } throw new IllegalArgumentException("invalid name!"); } }
1,068
23.295455
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLEnumerators/EnumPositionType.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.dslForScriptGenerator.DSLCommand.DSLEnumerators; /** * * @author rubens */ public enum EnumPositionType { Left(3), Right(1), Up(0), Down(2), EnemyDirection(4); private final int code; EnumPositionType(int code) { this.code = code; } public int code() { return this.code; } public static EnumPositionType byCode(int codigo) { for (EnumPositionType t : EnumPositionType.values()) { if (codigo == t.code()) { return t; } } throw new IllegalArgumentException("invalid code!"); } public static EnumPositionType byName(String name) { if (name.equals("Left")) { return EnumPositionType.Left; } else if (name.equals("Right")) { return EnumPositionType.Right; } else if (name.equals("Up")) { return EnumPositionType.Up; }else if (name.equals("Down")) { return EnumPositionType.Down; }else if (name.equals("EnemyDir")) { return EnumPositionType.EnemyDirection; } throw new IllegalArgumentException("invalid name!"); } }
1,378
26.58
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommand/DSLEnumerators/EnumTypeUnits.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.dslForScriptGenerator.DSLCommand.DSLEnumerators; /** * * @author rubens */ public enum EnumTypeUnits { Resource(0), Base(1), Barracks(2), Worker(3), Light(4), Heavy(5), Ranged(6); private final int code; EnumTypeUnits(int code) { this.code = code; } public int code() { return this.code; } public static EnumTypeUnits byCode(int codigo) { for (EnumTypeUnits t : EnumTypeUnits.values()) { if (codigo == t.code()) { return t; } } throw new IllegalArgumentException("invalid code!"); } public static EnumTypeUnits byName(String name) { if (name.equals("Resource")) { return EnumTypeUnits.Resource; } else if (name.equals("Base")) { return EnumTypeUnits.Base; } else if (name.equals("Barracks")) { return EnumTypeUnits.Barracks; }else if (name.equals("Worker")) { return EnumTypeUnits.Worker; }else if (name.equals("Light")) { return EnumTypeUnits.Light; }else if (name.equals("Heavy")) { return EnumTypeUnits.Heavy; }else if (name.equals("Ranged")) { return EnumTypeUnits.Ranged; } throw new IllegalArgumentException("invalid name!"); } }
1,528
27.314815
80
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommandInterfaces/ICommand.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.dslForScriptGenerator.DSLCommandInterfaces; import java.util.HashMap; import java.util.HashSet; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens and julian */ public interface ICommand{ public boolean isHasDSLUsed(); public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, HashMap<Long, String> counterByFunction); }
710
28.625
174
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCommandInterfaces/IUnitCommand.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.dslForScriptGenerator.DSLCommandInterfaces; import java.util.HashMap; import java.util.HashSet; import ai.abstraction.pathfinding.PathFinding; import rts.GameState; import rts.PlayerAction; import rts.units.Unit; import rts.units.UnitTypeTable; /** * * @author rubens */ public interface IUnitCommand { public Boolean isNecessaryUnit(); public PlayerAction getAction(GameState game, int player, PlayerAction currentPlayerAction, PathFinding pf, UnitTypeTable a_utt, Unit u, HashMap<Long, String> counterByFunction); }
738
28.56
182
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/AbstractDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPlayerTarget; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IParameters; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.ClosestEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.FarthestEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.LessHealthyEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.MostHealthyEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PriorityPositionParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.RandomEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.StrongestEnemy; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.TypeConcrete; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.WeakestEnemy; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.FunctionsforDSL; import java.util.List; /** * * @author rubens */ public abstract class AbstractDSLCompiler implements IDSLCompiler { protected final FunctionsforDSL fGrammar = new FunctionsforDSL(); public static String generateString(int initialPos, int finalPos, String[] fragments) { String fullString = ""; if (finalPos > (fragments.length - 1)) { finalPos = (fragments.length - 1); } for (int i = initialPos; i <= finalPos; i++) { fullString += fragments[i] + " "; } return fullString.trim(); } protected boolean isBasicCommand(String fragment) { List<FunctionsforDSL> basicFunctions = fGrammar.getBasicFunctionsForGrammar(); for (FunctionsforDSL basicFunction : basicFunctions) { if (fragment.contains(basicFunction.getNameFunction())) { return true; } } return false; } protected int countCaracter(String fragment, String toFind) { int total = 0; for (int i = 0; i < fragment.length(); i++) { char ch = fragment.charAt(i); String x1 = String.valueOf(ch); if (x1.equalsIgnoreCase(toFind)) { total = total + 1; } } return total; } protected IParameters getBehaviorByName(String i) { switch (i) { case "closest": return new ClosestEnemy(); case "farthest": return new FarthestEnemy(); case "lessHealthy": return new LessHealthyEnemy(); case "mostHealthy": return new MostHealthyEnemy(); case "strongest": return new StrongestEnemy(); case "weakest": return new WeakestEnemy(); default: return new RandomEnemy(); } } protected IParameters getTypeUnitByString(String j) { switch (j) { case "Worker": return TypeConcrete.getTypeWorker(); case "Light": return TypeConcrete.getTypeLight(); case "Ranged": return TypeConcrete.getTypeRanged(); case "Heavy": return TypeConcrete.getTypeHeavy(); default: return TypeConcrete.getTypeUnits(); } } protected IParameters getPriorityPositionByName(String i) { PriorityPositionParam p = new PriorityPositionParam(); switch (i) { case "Left": p.addPosition(EnumPositionType.Left); return p; case "Right": p.addPosition(EnumPositionType.Right); return p; case "Up": p.addPosition(EnumPositionType.Up); return p; default: p.addPosition(EnumPositionType.Down); return p; } } protected EnumPlayerTarget getPlayerTargetByNumber(String p) { if (p.equals("Ally")) { return EnumPlayerTarget.Ally; } return EnumPlayerTarget.Enemy; } protected IParameters getTypeConstructByName(String param) { if (param.equals("Base")) { return TypeConcrete.getTypeBase(); //add unit construct type } else if (param.equals("Barrack")) { return TypeConcrete.getTypeBarracks(); //add unit construct type } else { return TypeConcrete.getTypeConstruction(); } } protected int getPositionParentClose(int initialPosition, String[] fragments) { int contOpen = 0, contClosed = 0; for (int i = initialPosition; i < fragments.length; i++) { String fragment = fragments[i]; contOpen += countCaracter(fragment, "("); contClosed += countCaracter(fragment, ")"); if (contOpen == contClosed) { return i; } } return fragments.length; } protected int getLastPositionForFor(int initialPosition, String[] fragments) { //first get the name for(u) if (isForInitialClause(fragments[initialPosition])) { initialPosition++; } //second, we get the full () to complet the for. return getPositionParentClose(initialPosition, fragments); } private boolean isForInitialClause(String fragment) { if (fragment.contains("for(u)")) { return true; } return false; } }
5,871
34.161677
91
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/ConditionalDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLBasicConditional.SimpleConditional; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.DistanceParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import rts.units.UnitTypeTable; /** * * @author rubens */ public class ConditionalDSLCompiler extends AbstractDSLCompiler { private boolean deny_boolean; @Override public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public SimpleConditional getConditionalByCode(iDSL dsl) { SimpleConditional conditional = buildConditional(dsl.translate(), dsl); return conditional; } private SimpleConditional buildConditional(String code, iDSL dsl) { code = eval_deny_boolean(code); if (code.contains("HaveEnemiesinUnitsRange")) { return conditionalHaveEnemiesinUnitsRange(code,dsl); } if (code.contains("HaveQtdEnemiesbyType")) { return conditionalHaveQtdEnemiesbyType(code,dsl); } if (code.contains("HaveQtdUnitsAttacking")) { return conditionalHaveQtdUnitsAttacking(code,dsl); } if (code.contains("HaveQtdUnitsbyType")) { return conditionalHaveQtdUnitsbyType(code,dsl); } if (code.contains("HaveQtdUnitsHarversting")) { return conditionalHaveQtdUnitsHarversting(code,dsl); } if (code.contains("HaveUnitsinEnemyRange")) { return conditionalHaveUnitsinEnemyRange(code,dsl); } if (code.contains("HaveUnitsToDistantToEnemy")) { return conditionalHaveUnitsToDistantToEnemy(code,dsl); } if (code.contains("HaveUnitsStrongest")) { return conditionalHaveUnitsStrongest(code,dsl); } if (code.contains("HaveEnemiesStrongest")) { return conditionalHaveEnemiesStrongest(code,dsl); } if (code.contains("IsPlayerInPosition")) { return conditionalIsPlayerInPosition(code,dsl); } return null; } private SimpleConditional conditionalHaveEnemiesinUnitsRange(String code, iDSL dsl) { code = code.replace("HaveEnemiesinUnitsRange(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 1) { return new SimpleConditional(this.deny_boolean,"HaveEnemiesinUnitsRange", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]))), dsl); } else { return new SimpleConditional(this.deny_boolean,"HaveEnemiesinUnitsRange", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), params[1])), dsl); } } private SimpleConditional conditionalHaveQtdEnemiesbyType(String code, iDSL dsl) { code = code.replace("HaveQtdEnemiesbyType(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); return new SimpleConditional(this.deny_boolean,"HaveQtdEnemiesbyType", new ArrayList(Arrays.asList(new QuantityParam(Integer.decode(params[1])), getTypeUnitByString(params[0]))), dsl); } private SimpleConditional conditionalHaveQtdUnitsAttacking(String code, iDSL dsl) { code = code.replace("HaveQtdUnitsAttacking(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); return new SimpleConditional(this.deny_boolean,"HaveQtdUnitsAttacking", new ArrayList(Arrays.asList(new QuantityParam(Integer.decode(params[1])), getTypeUnitByString(params[0]))), dsl); } private SimpleConditional conditionalHaveQtdUnitsbyType(String code, iDSL dsl) { code = code.replace("HaveQtdUnitsbyType(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); return new SimpleConditional(this.deny_boolean,"HaveQtdUnitsbyType", new ArrayList(Arrays.asList(new QuantityParam(Integer.decode(params[1])), getTypeUnitByString(params[0]))), dsl); } private SimpleConditional conditionalHaveQtdUnitsHarversting(String code, iDSL dsl) { code = code.replace("HaveQtdUnitsHarversting(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); return new SimpleConditional(this.deny_boolean,"HaveQtdUnitsHarversting", new ArrayList(Arrays.asList(new QuantityParam(Integer.decode(params[0])))) , dsl); } private SimpleConditional conditionalHaveUnitsinEnemyRange(String code, iDSL dsl) { code = code.replace("HaveUnitsinEnemyRange(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 1) { return new SimpleConditional(this.deny_boolean,"HaveUnitsinEnemyRange", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]))) , dsl); } else { return new SimpleConditional(this.deny_boolean,"HaveUnitsinEnemyRange", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), params[1])), dsl); } } private SimpleConditional conditionalHaveUnitsToDistantToEnemy(String code, iDSL dsl) { code = code.replace("HaveUnitsToDistantToEnemy(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 2) { return new SimpleConditional(this.deny_boolean,"HaveUnitsToDistantToEnemy", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), new DistanceParam(Integer.decode(params[1])))), dsl); } else { return new SimpleConditional(this.deny_boolean,"HaveUnitsToDistantToEnemy", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), new DistanceParam(Integer.decode(params[1])), params[2])), dsl); } } private SimpleConditional conditionalHaveUnitsStrongest(String code, iDSL dsl) { code = code.replace("HaveUnitsStrongest(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 1) { return new SimpleConditional(this.deny_boolean,"HaveUnitsStrongest", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]))) , dsl); } else { return new SimpleConditional(this.deny_boolean,"HaveUnitsStrongest", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), params[1])), dsl); } } private SimpleConditional conditionalHaveEnemiesStrongest(String code, iDSL dsl) { code = code.replace("HaveEnemiesStrongest(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 1) { return new SimpleConditional(this.deny_boolean,"HaveEnemiesStrongest", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]))) , dsl); } else { return new SimpleConditional(this.deny_boolean,"HaveEnemiesStrongest", new ArrayList(Arrays.asList(getTypeUnitByString(params[0]), params[1])), dsl); } } private SimpleConditional conditionalIsPlayerInPosition(String code, iDSL dsl) { code = code.replace("IsPlayerInPosition(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); if (params.length == 1) { return new SimpleConditional(this.deny_boolean,"IsPlayerInPosition", new ArrayList(Arrays.asList(getPriorityPositionByName(params[0]))), dsl); } else { return new SimpleConditional(this.deny_boolean,"IsPlayerInPosition", new ArrayList(Arrays.asList(getPriorityPositionByName(params[0]), params[1])), dsl); } } private String eval_deny_boolean(String code) { this.deny_boolean = false; if (code.startsWith("!")) { this.deny_boolean = true; code = code.replace("!", ""); } return code; } }
9,265
41.310502
135
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/ForDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicLoops.ForFunction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.FunctionsforDSL; import ai.synthesis.grammar.dslTree.CDSL; 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.interfacesDSL.iDSL; import java.nio.file.SecureDirectoryStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import rts.units.UnitTypeTable; /** * * @author rubens */ public class ForDSLCompiler extends AbstractDSLCompiler{ private IfDSLCompiler ifCompiler = new IfDSLCompiler(); protected FunctionDSLCompiler functionCompiler = new FunctionDSLCompiler(); protected ConditionalDSLCompiler conditionalCompiler = new ConditionalDSLCompiler(); @Override public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt) { if(!(code instanceof S3DSL)){ try { throw new Exception("problem with initial object"); } catch (Exception ex) { Logger.getLogger(ForDSLCompiler.class.getName()).log(Level.SEVERE, null, ex); } } S3DSL start = (S3DSL) code; ForFunction forFunction = new ForFunction(); List<ICommand> commands = new ArrayList<>(); List<iDSL> fragments = new ArrayList<>(); fragments.add(start.getForCommand().getFirstDSL()); fragments.add(start.getForCommand().getNextCommand()); //build the items inside of the compiler for (int i = 0; i < fragments.size(); i++) { iDSL f = fragments.get(i); if(f instanceof CDSL){ //get the complete string forFunction.setCommandsFor(functionCompiler.CompilerCode(f, utt)); } else if (f instanceof S2DSL) { forFunction.setCommandsFor(ifCompiler.CompilerCode(f, utt)); } else if (f instanceof S4DSL) { fragments.add(((S4DSL) f).getFirstDSL()); fragments.add(((S4DSL) f).getNextCommand()); } } commands.add(forFunction); return commands; } public static List<ICommand> CompilerCodeStatic(iDSL code, UnitTypeTable utt) { FunctionDSLCompiler functionCompiler = new FunctionDSLCompiler(); IfDSLCompiler ifCompiler = new IfDSLCompiler(); ForFunction forFunction = new ForFunction(); List<ICommand> commands = new ArrayList<>(); if(!(code instanceof S1DSL)){ try { throw new Exception("problem with initial object"); } catch (Exception ex) { Logger.getLogger(ForDSLCompiler.class.getName()).log(Level.SEVERE, null, ex); } } S1DSL start = (S1DSL) code; List<iDSL> fragments = new ArrayList<>(); fragments.add(start.getCommandS1()); fragments.add(start.getNextCommand()); //build the items inside of the compiler for (iDSL f : fragments) { if(f instanceof CDSL){ //get the complete string forFunction.setCommandsFor(functionCompiler.CompilerCode(f, utt)); } else if (f instanceof S2DSL) { forFunction.setCommandsFor(ifCompiler.CompilerCode(f, utt)); } } commands.add(forFunction); return commands; } }
4,131
38.730769
93
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/FunctionDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.AttackBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.BuildBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.ClusterBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.HarvestBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.MoveAwayBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.MoveToCoordinatesBasic_old; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.MoveToCoordinatesOnce; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.MoveToUnitBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicAction.TrainBasic; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPlayerTarget; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.CoordinatesParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PlayerTargetParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.PriorityPositionParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.QuantityParam; import ai.synthesis.dslForScriptGenerator.DSLParametersConcrete.TypeConcrete; import ai.synthesis.grammar.dslTree.CDSL; import ai.synthesis.grammar.dslTree.EmptyDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iEmptyDSL; import java.util.ArrayList; import java.util.List; import rts.units.UnitTypeTable; /** * * @author rubens */ public class FunctionDSLCompiler extends AbstractDSLCompiler { static public int counterCommands = 0; @Override public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt) { List<ICommand> commands = new ArrayList<>(); CDSL starts = (CDSL) code; ICommand tFunction; if(starts.getRealCommand() != null && !(starts.getRealCommand() instanceof iEmptyDSL)){ tFunction = buildFunctionByCode(starts.getRealCommand(), utt); commands.add(tFunction); } if (starts.getNextCommand() != null && !(starts.getNextCommand() instanceof iEmptyDSL)) { commands.addAll(CompilerCode(starts.getNextCommand(), utt)); } return commands; } public int getLastPositionForBasicFunction(int initialPosition, String[] fragments) { int contOpen = 0, contClosed = 0; for (int i = initialPosition; i < fragments.length; i++) { String fragment = fragments[i]; contOpen += countCaracter(fragment, "("); contClosed += countCaracter(fragment, ")"); if (contOpen == contClosed) { return i; } } return fragments.length; } public int getLastPositionForBasicFunctionInFor(int initialPosition, String[] fragments) { boolean removeInitialParen = false; int contOpen = 0, contClosed = 0; //check if starts with ( if (fragments[initialPosition].startsWith("(")) { removeInitialParen = true; } for (int i = initialPosition; i < fragments.length; i++) { String fragment = fragments[i]; if (i == initialPosition && removeInitialParen) { fragment = fragment.substring(1); } contOpen += countCaracter(fragment, "("); contClosed += countCaracter(fragment, ")"); if (contOpen == contClosed) { return i; } } return fragments.length; } private ICommand buildFunctionByCode(iDSL dsl, UnitTypeTable utt) { String code = dsl.translate(); if (code.contains("build")) { return buildCommand(code, dsl, utt); } if (code.contains("attack")) { return attackCommand(code, dsl, utt); } if (code.contains("harvest")) { return harvestCommand(code, dsl, utt); } if (code.contains("moveToCoord")) { return moveToCoordCommand(code, dsl, utt); } if (code.contains("moveToUnit")) { return moveToUnitCommand(code, dsl, utt); } if (code.contains("train")) { return trainCommand(code, dsl, utt); } if (code.contains("moveaway")) { return moveAwayCommand(code, dsl, utt); } if (code.contains("cluster")) { return clusterCommand(code, dsl, utt); } if (code.contains("moveOnceToCoord")) { return moveToCoordOnceCommand(code, dsl, utt); } return null; } private ICommand buildCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("build(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); BuildBasic build = new BuildBasic(); if (params[0].equals("Base")) { build.addParameter(TypeConcrete.getTypeBase()); //add unit construct type } else if (params[0].equals("Barrack")) { build.addParameter(TypeConcrete.getTypeBarracks()); //add unit construct type } else { build.addParameter(TypeConcrete.getTypeConstruction()); } build.addParameter(new QuantityParam(Integer.decode(params[1]))); //add qtd unit //add position PriorityPositionParam pos = new PriorityPositionParam(); pos.addPosition(EnumPositionType.byName(params[2])); build.addParameter(pos); //If there are more than 3 parameters, we need a unit if (params.length > 3) { build.setUnitIsNecessary(); } build.setDslFragment(dsl); return build; } private ICommand harvestCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("harvest(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); HarvestBasic harverst = new HarvestBasic(); harverst.addParameter(TypeConcrete.getTypeWorker()); //add unit type harverst.addParameter(new QuantityParam(Integer.decode(params[0]))); //add qtd unit if (params.length > 1) { harverst.setUnitIsNecessary(); } harverst.setDslFragment(dsl); return harverst; } private ICommand attackCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("attack(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); AttackBasic attack = new AttackBasic(); attack.addParameter(getTypeUnitByString(params[0])); //add unit type PlayerTargetParam pt = new PlayerTargetParam(); pt.addPlayer(EnumPlayerTarget.Enemy); attack.addParameter(pt); attack.addParameter(getBehaviorByName(params[1])); //add behavior if (params.length > 2) { attack.setUnitIsNecessary(); } attack.setDslFragment(dsl); return attack; } private ICommand moveToCoordCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("moveToCoord(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); MoveToCoordinatesBasic_old moveToCoordinates = new MoveToCoordinatesBasic_old(); int x = Integer.decode(params[1]); int y = Integer.decode(params[2]); moveToCoordinates.addParameter(new CoordinatesParam(x, y)); moveToCoordinates.addParameter(getTypeUnitByString(params[0]));//add unit type if (params.length > 3) { moveToCoordinates.setUnitIsNecessary(); } moveToCoordinates.setDslFragment(dsl); return moveToCoordinates; } private ICommand moveToUnitCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("moveToUnit(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); MoveToUnitBasic moveToUnit = new MoveToUnitBasic(); moveToUnit.addParameter(getTypeUnitByString(params[0])); //add unit type PlayerTargetParam pt = new PlayerTargetParam(); pt.addPlayer(getPlayerTargetByNumber(params[1])); moveToUnit.addParameter(pt); moveToUnit.addParameter(getBehaviorByName(params[2])); //add behavior if (params.length > 3) { moveToUnit.setUnitIsNecessary(); } moveToUnit.setDslFragment(dsl); return moveToUnit; } private ICommand trainCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("train(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); TrainBasic train = new TrainBasic(); //train.addParameter(getTypeConstructByName(params[1])); //add unit construct type if (params[0].equals("All")) { train.addParameter(getTypeConstructByName("All")); } else if (params[0].equals("Worker")) { train.addParameter(getTypeConstructByName("Base")); //add unit construct type } else { train.addParameter(getTypeConstructByName("Barrack")); } train.addParameter(getTypeUnitByString(params[0])); //add unit Type //train.addParameter(TypeConcrete.getTypeWorker()); //add unit Type train.addParameter(new QuantityParam(Integer.decode(params[1]))); //add qtd unit PriorityPositionParam pos = new PriorityPositionParam(); //for (Integer position : Permutation.getPermutation(j)) { pos.addPosition(EnumPositionType.byName(params[2])); //} train.addParameter(pos); train.setDslFragment(dsl); return train; } private ICommand moveAwayCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("moveaway(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); MoveAwayBasic moveAway = new MoveAwayBasic(); moveAway.addParameter(getTypeUnitByString(params[0])); if (params.length > 1) { moveAway.setUnitIsNecessary(); } moveAway.setDslFragment(dsl); return moveAway; } private ICommand clusterCommand(String code, iDSL dsl, UnitTypeTable utt) { if (code.startsWith("(")) { code = code.substring(1); } code = code.replace("cluster(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); ClusterBasic cluster = new ClusterBasic(); cluster.addParameter(getTypeUnitByString(params[0])); cluster.setDslFragment(dsl); return cluster; } private ICommand moveToCoordOnceCommand(String code, iDSL dsl, UnitTypeTable utt) { if(code.startsWith("(")){ code = code.substring(1); } code = code.replace("moveOnceToCoord(", ""); code = code.replace(")", "").replace(",", " "); String[] params = code.split(" "); MoveToCoordinatesOnce moveToCoordinates = new MoveToCoordinatesOnce(); int x = Integer.decode(params[2]); int y = Integer.decode(params[3]); moveToCoordinates.addParameter(new CoordinatesParam(x, y)); moveToCoordinates.addParameter(getTypeUnitByString(params[0]));//add unit type moveToCoordinates.addParameter(new QuantityParam(Integer.decode(params[1]))); //add qtd unit if (params.length > 4) { moveToCoordinates.setUnitIsNecessary(); } return moveToCoordinates; } }
12,755
38.8625
100
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/IDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.util.List; import rts.units.UnitTypeTable; /** * * @author rubens */ public interface IDSLCompiler { public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt); }
571
23.869565
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/IfDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicBoolean.IfFunction; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S3DSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iEmptyDSL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import rts.units.UnitTypeTable; /** * * @author rubens */ public class IfDSLCompiler extends AbstractDSLCompiler{ protected FunctionDSLCompiler functionCompiler = new FunctionDSLCompiler(); protected ConditionalDSLCompiler conditionalCompiler = new ConditionalDSLCompiler(); @Override public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt) { if(!(code instanceof S2DSL)){ try { throw new Exception("problem with initial object"); } catch (Exception ex) { Logger.getLogger(ForDSLCompiler.class.getName()).log(Level.SEVERE, null, ex); } } IfFunction ifFun = new IfFunction(); S2DSL starts = (S2DSL) code; List<ICommand> commands = new ArrayList<>(); //first build the if and get the conditional ifFun.setConditional(conditionalCompiler.getConditionalByCode(starts.getBoolCommand())); //second build the then //get the complete then and move for the fragments. if(starts.getThenCommand() != null && !(starts.getThenCommand() instanceof iEmptyDSL) && !starts.translate().equals("")){ ifFun.includeFullCommandsThen(functionCompiler.CompilerCode(starts.getThenCommand(), utt)); } //third build the else, if exists ATTENTION if(starts.getElseCommand() != null && !(starts.getElseCommand() instanceof iEmptyDSL)){ ifFun.includeFullCommandsElse(functionCompiler.CompilerCode(starts.getElseCommand(), utt)); } commands.add(ifFun); return commands; } }
2,429
36.384615
104
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLCompiler/MainDSLCompiler.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.dslForScriptGenerator.DSLCompiler; import ai.synthesis.dslForScriptGenerator.DSLCommandInterfaces.ICommand; import ai.synthesis.grammar.dslTree.CDSL; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S3DSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import rts.units.UnitTypeTable; /** * * @author julian and rubens */ public class MainDSLCompiler extends AbstractDSLCompiler { private IfDSLCompiler ifCompiler = new IfDSLCompiler(); private ForDSLCompiler forCompiler = new ForDSLCompiler(); protected FunctionDSLCompiler functionCompiler = new FunctionDSLCompiler(); protected ConditionalDSLCompiler conditionalCompiler = new ConditionalDSLCompiler(); @Override public List<ICommand> CompilerCode(iDSL code, UnitTypeTable utt) { return buildCommands(code, utt); } private List<ICommand> buildCommands(iDSL code, UnitTypeTable utt) { List<ICommand> commands = new ArrayList<>(); if(!(code instanceof S1DSL)){ try { throw new Exception("problem with initial object"); } catch (Exception ex) { System.err.println("problem at mainCompiler"); } } S1DSL start = (S1DSL) code; List<iDSL> fragments = new ArrayList<>(); fragments.add(start.getCommandS1()); fragments.add(start.getNextCommand()); for (iDSL f : fragments) { if(f instanceof CDSL){ commands.addAll(functionCompiler.CompilerCode(f, utt)); } else if (f instanceof S2DSL) { commands.addAll(ifCompiler.CompilerCode(f, utt)); }else if(f instanceof S3DSL){ commands.addAll(forCompiler.CompilerCode(f, utt)); }else if(f instanceof S1DSL){ commands.addAll(buildCommands(f, utt)); } } //for (ICommand command : commands) { // System.out.println(command.toString()); //} return commands; } }
2,542
33.835616
88
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/BehaviorAbstract.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IBehavior; /** * * @author rubens */ public abstract class BehaviorAbstract implements IBehavior{ }
419
22.333333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/ClosestEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens */ public class ClosestEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit closestEnemy = null; int closestDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int d = Math.abs(u2.getX() - unitAlly.getX()) + Math.abs(u2.getY() - unitAlly.getY()); if (closestEnemy == null || d < closestDistance) { closestEnemy = u2; closestDistance = d; } } } return closestEnemy; } @Override public String toString() { return "ClosestEnemy{-}"; } }
1,166
26.785714
102
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/ConstructionTypeParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import java.util.List; /** * * @author rubens */ public class ConstructionTypeParam extends TypeConcrete { public boolean addType(EnumTypeUnits enType) { if (enType == EnumTypeUnits.Barracks || enType == EnumTypeUnits.Base) { selectedTypes.add(enType); return true; }else{ return false; } } @Override public List<EnumTypeUnits> getParamTypes() { return selectedTypes; } @Override public String toString() { return "ConstructionTypeParam:{selectedTypes="+selectedTypes+ '}'; } }
955
22.9
82
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/CoordinatesParam.java
package ai.synthesis.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.IDSLParameters.ICoordinates; public class CoordinatesParam implements ICoordinates { private int x,y; public CoordinatesParam(int x, int y) { this.x=x; this.y=y; } @Override public int getX() { // TODO Auto-generated method stub return x; } @Override public int getY() { // TODO Auto-generated method stub return y; } @Override public void setCoordinates(int x, int y) { // TODO Auto-generated method stub this.x=x; this.y=y; } @Override public String toString() { return "CoordinatesParam:{" + "x=" + x + ", y=" + y + '}'; } }
719
15.744186
70
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/DistanceParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IDistance; /** * * @author rubens */ public class DistanceParam implements IDistance{ private int value; public DistanceParam() { this.value = 0; } public DistanceParam(int value) { this.value = value; } @Override public int getDistance() { return value; } @Override public void setDistance(int value) { this.value = value; } @Override public String toString() { return "DistanceParam:{" + "value=" + value + '}'; } }
853
17.977778
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/FarthestEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class FarthestEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit farthestEnemy = null; int farthesttDistance = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int d = Math.abs(u2.getX() - unitAlly.getX()) + Math.abs(u2.getY() - unitAlly.getY()); if (farthestEnemy == null || d > farthesttDistance) { farthestEnemy = u2; farthesttDistance = d; } } } return farthestEnemy; } @Override public String toString() { return "FarthestEnemy:{-}"; } }
1,185
26.581395
102
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/LessHealthyEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class LessHealthyEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit lessHealthyEnemy = null; int minimumHP = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int hp = u2.getMaxHitPoints(); if (lessHealthyEnemy == null || hp < minimumHP) { lessHealthyEnemy = u2; minimumHP = hp; } } } return lessHealthyEnemy; } @Override public String toString() { return "LessHealthyEnemy:{-}"; } }
1,121
25.093023
80
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/MostHealthyEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class MostHealthyEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit mostHealthyEnemy = null; int maximumHP = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int hp = u2.getMaxHitPoints(); if (mostHealthyEnemy == null || hp > maximumHP) { mostHealthyEnemy = u2; maximumHP = hp; } } } return mostHealthyEnemy; } @Override public String toString() { return "MostHealthyEnemy:{-}"; } }
1,120
25.690476
80
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/PlayerTargetParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPlayerTarget; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IPlayerTarget; import java.util.ArrayList; import java.util.List; /** * * @author rubens */ public class PlayerTargetParam implements IPlayerTarget { private List<EnumPlayerTarget> selectedPlayerTarget; public PlayerTargetParam() { this.selectedPlayerTarget = new ArrayList<>(); } public List<EnumPlayerTarget> getSelectedPlayerTarget() { return selectedPlayerTarget; } public void setSelectedPosition(List<EnumPlayerTarget> selectedPlayerTarget) { this.selectedPlayerTarget = selectedPlayerTarget; } public void addPlayer(EnumPlayerTarget player){ if(!selectedPlayerTarget.contains(player)){ this.selectedPlayerTarget.add(player); } } @Override public String toString() { return "PlayerTargetParam:{" + "selectedPlayerTarget=" + selectedPlayerTarget + '}'; } }
1,283
26.319149
92
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/PriorityPositionParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumPositionType; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IPriorityPosition; import java.util.ArrayList; import java.util.List; /** * * @author rubens */ public class PriorityPositionParam implements IPriorityPosition{ private List<EnumPositionType> selectedPosition; public PriorityPositionParam() { this.selectedPosition = new ArrayList<>(); } public List<EnumPositionType> getSelectedPosition() { return selectedPosition; } public void setSelectedPosition(List<EnumPositionType> selectedPosition) { this.selectedPosition = selectedPosition; } public void addPosition(EnumPositionType position){ if(!selectedPosition.contains(position)){ this.selectedPosition.add(position); } } @Override public String toString() { return "PriorityPositionParam:{" + "selectedPosition=" + selectedPosition + '}'; } }
1,276
26.76087
88
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/QuantityParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IQuantity; /** * * @author rubens */ public class QuantityParam implements IQuantity{ private int value; public QuantityParam() { this.value = 0; } public QuantityParam(int value) { this.value = value; } @Override public int getQuantity() { return value; } @Override public void setQuantity(int value) { this.value = value; } @Override public String toString() { return "QuantityParam:{" + "value=" + value + '}'; } }
848
18.295455
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/RandomEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class RandomEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit randomEnemy = null; Random r=new Random(); int quantityUnits=0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { quantityUnits++; } } int idUnit=r.nextInt(quantityUnits); int counterUnits=0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player && counterUnits==idUnit) { counterUnits++; randomEnemy=u2; } } return randomEnemy; } @Override public String toString() { return "RandomEnemy:{-}"; } }
1,290
24.313725
90
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/StrongestEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class StrongestEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit strongestEnemy = null; int maximumDamage = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int d = u2.getMaxDamage(); if (strongestEnemy == null || d > maximumDamage) { strongestEnemy = u2; maximumDamage = d; } } } return strongestEnemy; } @Override public String toString() { return "StrongestEnemy{-}"; } }
1,129
24.681818
80
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/TypeConcrete.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import ai.synthesis.dslForScriptGenerator.IDSLParameters.IType; import java.util.ArrayList; import java.util.List; /** * * @author rubens */ public abstract class TypeConcrete implements IType{ List<EnumTypeUnits> selectedTypes; public TypeConcrete() { selectedTypes = new ArrayList<>(); } public static IType getTypeConstruction(){ ConstructionTypeParam tReturn = new ConstructionTypeParam(); tReturn.addType(EnumTypeUnits.Base); tReturn.addType(EnumTypeUnits.Barracks); return tReturn; } public static IType getTypeBase(){ ConstructionTypeParam tReturn = new ConstructionTypeParam(); tReturn.addType(EnumTypeUnits.Base); return tReturn; } public static IType getTypeBarracks(){ ConstructionTypeParam tReturn = new ConstructionTypeParam(); tReturn.addType(EnumTypeUnits.Barracks); return tReturn; } public static IType getTypeUnits(){ UnitTypeParam tReturn = new UnitTypeParam(); tReturn.addType(EnumTypeUnits.Heavy); tReturn.addType(EnumTypeUnits.Light); tReturn.addType(EnumTypeUnits.Ranged); tReturn.addType(EnumTypeUnits.Worker); return tReturn; } public static IType getTypeHeavy(){ UnitTypeParam tReturn = new UnitTypeParam(); tReturn.addType(EnumTypeUnits.Heavy); return tReturn; } public static IType getTypeLight(){ UnitTypeParam tReturn = new UnitTypeParam(); tReturn.addType(EnumTypeUnits.Light); return tReturn; } public static IType getTypeRanged(){ UnitTypeParam tReturn = new UnitTypeParam(); tReturn.addType(EnumTypeUnits.Ranged); return tReturn; } public static IType getTypeWorker(){ UnitTypeParam tReturn = new UnitTypeParam(); tReturn.addType(EnumTypeUnits.Worker); return tReturn; } }
2,305
28.564103
82
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/UnitTypeParam.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.dslForScriptGenerator.DSLParametersConcrete; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import java.util.List; /** * * @author rubens */ public class UnitTypeParam extends TypeConcrete { public boolean addType(EnumTypeUnits enType) { if (enType == EnumTypeUnits.Heavy || enType == EnumTypeUnits.Light || enType == EnumTypeUnits.Ranged || enType == EnumTypeUnits.Worker) { selectedTypes.add(enType); return true; }else{ return false; } } @Override public List<EnumTypeUnits> getParamTypes() { return selectedTypes; } @Override public String toString() { return "UnitTypeParam:{selectedTypes="+selectedTypes+ '}'; } }
1,037
23.714286
82
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/WeakestEnemy.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.dslForScriptGenerator.DSLParametersConcrete; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class WeakestEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit weakestEnemy = null; int maximumDamage = 0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { int d = u2.getMaxDamage(); if (weakestEnemy == null || d < maximumDamage) { weakestEnemy = u2; maximumDamage = d; } } } return weakestEnemy; } @Override public String toString() { return "WeakestEnemy{-}"; } }
1,107
25.380952
80
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLTableGenerator/FunctionsforDSL.java
package ai.synthesis.dslForScriptGenerator.DSLTableGenerator; import java.util.ArrayList; import java.util.List; public class FunctionsforDSL { String nameFunction; List<ParameterDSL> parameters; List<String> typeUnitDiscrete; List<String> typeUnitTrainDiscrete; List<String> typeStructureDiscrete; List<String> behaviourDiscrete; List<String> playerTargetDiscrete; List<String> priorityPositionDiscrete; List<String> priorityPositionDiscreteLimited; List<FunctionsforDSL> basicFunctionsForGrammar; List<FunctionsforDSL> basicFunctionsForGrammarUnit; List<FunctionsforDSL> conditionalsForGrammar; List<FunctionsforDSL> conditionalsForGrammarUnit; public FunctionsforDSL(String nameFunction, List<ParameterDSL> parameters) { this.nameFunction = nameFunction; this.parameters = parameters; } public FunctionsforDSL() { initializateDiscreteSpecificParameters(); createTableBasicFunctionsGrammar(); createTableConditionalsGrammar(); } public void initializateDiscreteSpecificParameters() { //Parameter TypeUnit typeUnitDiscrete = new ArrayList<>(); typeUnitDiscrete.add("Worker"); typeUnitDiscrete.add("Light"); typeUnitDiscrete.add("Ranged"); typeUnitDiscrete.add("Heavy"); //typeUnitDiscrete.add("All"); //Parameter TypeUnitTrain typeUnitTrainDiscrete = new ArrayList<>(); typeUnitTrainDiscrete.add("Worker"); typeUnitTrainDiscrete.add("Light"); typeUnitTrainDiscrete.add("Ranged"); typeUnitTrainDiscrete.add("Heavy"); //typeUnitTrainDiscrete.add("All"); //Parameter TypeStructure typeStructureDiscrete = new ArrayList<>(); typeStructureDiscrete.add("Base"); typeStructureDiscrete.add("Barrack"); //typeStructureDiscrete.add("All"); //Parameter Behaviour behaviourDiscrete = new ArrayList<>(); behaviourDiscrete.add("closest"); behaviourDiscrete.add("farthest"); behaviourDiscrete.add("lessHealthy"); behaviourDiscrete.add("mostHealthy"); behaviourDiscrete.add("strongest"); behaviourDiscrete.add("weakest"); //behaviourDiscrete.add("random"); //Parameter PlayerTarget playerTargetDiscrete = new ArrayList<>(); playerTargetDiscrete.add("Enemy"); playerTargetDiscrete.add("Ally"); //Parameter PriorityPosition priorityPositionDiscrete = new ArrayList<>(); priorityPositionDiscrete.add("Up"); priorityPositionDiscrete.add("Down"); priorityPositionDiscrete.add("Right"); priorityPositionDiscrete.add("Left"); priorityPositionDiscrete.add("EnemyDir"); //Parameter PriorityPositionLimited priorityPositionDiscreteLimited = new ArrayList<>(); priorityPositionDiscreteLimited.add("Up"); priorityPositionDiscreteLimited.add("Down"); priorityPositionDiscreteLimited.add("Right"); priorityPositionDiscreteLimited.add("Left"); } public void createTableBasicFunctionsGrammar() { basicFunctionsForGrammar = new ArrayList<>(); basicFunctionsForGrammarUnit = new ArrayList<>(); //Function AttackBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("behaviour", null, null, behaviourDiscrete)); basicFunctionsForGrammar.add(new FunctionsforDSL("attack", parameters)); //Function AttackBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("behaviour", null, null, behaviourDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("attack", parameters)); //Function BuildBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 2.0, null)); //5 parameters.add(new ParameterDSL("priorityPositionDiscreteLimited", null, null, priorityPositionDiscreteLimited)); basicFunctionsForGrammar.add(new FunctionsforDSL("build", parameters)); //Function BuildBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 2.0, null)); parameters.add(new ParameterDSL("priorityPositionDiscreteLimited", null, null, priorityPositionDiscreteLimited)); parameters.add(new ParameterDSL("u", null, null, null)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("build", parameters)); //Function HarvestBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("Quantity", 1.0, 4.0, null)); //10 basicFunctionsForGrammar.add(new FunctionsforDSL("harvest", parameters)); //Function HarvestBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("Quantity", 1.0, 4.0, null)); parameters.add(new ParameterDSL("u", null, null, null)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("harvest", parameters)); // //Function MoveToCoordinatesBasic // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); // parameters.add((new ParameterDSL("x", 0.0, 0.0, null))); // parameters.add((new ParameterDSL("y", 0.0, 0.0, null))); // basicFunctionsForGrammar.add(new FunctionsforDSL("moveToCoord", parameters)); // //Function MoveToCoordinatesBasic // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); // parameters.add((new ParameterDSL("x", 0.0, 15.0, null))); // parameters.add((new ParameterDSL("y", 0.0, 15.0, null))); // parameters.add(new ParameterDSL("u", null, null, null)); // basicFunctionsForGrammarUnit.add(new FunctionsforDSL("moveToCoord", parameters)); //Function MoveToUnitBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("playerTarget", null, null, playerTargetDiscrete)); parameters.add(new ParameterDSL("behaviour", null, null, behaviourDiscrete)); basicFunctionsForGrammar.add(new FunctionsforDSL("moveToUnit", parameters)); //Function MoveToUnitBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("playerTarget", null, null, playerTargetDiscrete)); parameters.add(new ParameterDSL("behaviour", null, null, behaviourDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("moveToUnit", parameters)); //Function TrainBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitTrainDiscrete)); //parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); //20 parameters.add(new ParameterDSL("priorityPos", null, null, priorityPositionDiscrete)); basicFunctionsForGrammar.add(new FunctionsforDSL("train", parameters)); //Function TrainBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitTrainDiscrete)); //parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); parameters.add(new ParameterDSL("priorityPos", null, null, priorityPositionDiscrete)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("train", parameters)); //Function MoveAwayBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); //parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); basicFunctionsForGrammar.add(new FunctionsforDSL("moveaway", parameters)); //Function MoveAwayBasic parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); basicFunctionsForGrammarUnit.add(new FunctionsforDSL("moveaway", parameters)); //Function ClusterBasic // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); // //parameters.add(new ParameterDSL("structureType", null, null, typeStructureDiscrete)); // basicFunctionsForGrammar.add(new FunctionsforDSL("cluster", parameters)); //Function MoveToCoordinatesOnce // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); // parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); // parameters.add((new ParameterDSL("x", 0.0, 15.0, null))); // parameters.add((new ParameterDSL("y", 0.0, 15.0, null))); // basicFunctionsForGrammar.add(new FunctionsforDSL("moveOnceToCoord", parameters)); // //Function MoveToCoordinatesOnce // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); // parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); // parameters.add((new ParameterDSL("x", 0.0, 15.0, null))); // parameters.add((new ParameterDSL("y", 0.0, 15.0, null))); // parameters.add(new ParameterDSL("u", null, null, null)); // basicFunctionsForGrammarUnit.add(new FunctionsforDSL("moveOnceToCoord", parameters)); } public void createTableConditionalsGrammar() { conditionalsForGrammar = new ArrayList<>(); conditionalsForGrammarUnit = new ArrayList<>(); //Conditional HaveEnemiesinUnitsRange parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); conditionalsForGrammar.add(new FunctionsforDSL("HaveEnemiesinUnitsRange", parameters)); //Conditional HaveEnemiesinUnitsRange parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveEnemiesinUnitsRange", parameters)); //Conditional HaveQtdEnemiesbyType parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammar.add(new FunctionsforDSL("HaveQtdEnemiesbyType", parameters)); //Conditional HaveQtdEnemiesbyType parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveQtdEnemiesbyType", parameters)); //Conditional HaveQtdEnemiesAttacking parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammar.add(new FunctionsforDSL("HaveQtdUnitsAttacking", parameters)); //Conditional HaveQtdEnemiesAttacking parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveQtdUnitsAttacking", parameters)); //Conditional HaveQtdUnitsbyType parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammar.add(new FunctionsforDSL("HaveQtdUnitsbyType", parameters)); //Conditional HaveQtdUnitsbyType parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveQtdUnitsbyType", parameters)); //Conditional HaveQtdUnitsHarvesting parameters = new ArrayList<>(); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammar.add(new FunctionsforDSL("HaveQtdUnitsHarversting", parameters)); //Conditional HaveQtdUnitsHarvesting parameters = new ArrayList<>(); parameters.add(new ParameterDSL("Quantity", 1.0, 10.0, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveQtdUnitsHarversting", parameters)); //Conditional HaveUnitsinEnemyRange parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); conditionalsForGrammar.add(new FunctionsforDSL("HaveUnitsinEnemyRange", parameters)); //Conditional HaveUnitsinEnemyRange parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveUnitsinEnemyRange", parameters)); //Conditional HaveUnitsToDistantToEnemy parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Distance", 1.0, 10.0, null)); conditionalsForGrammar.add(new FunctionsforDSL("HaveUnitsToDistantToEnemy", parameters)); //Conditional HaveUnitsToDistantToEnemy parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("Distance", 1.0, 10.0, null)); parameters.add(new ParameterDSL("u", null, null, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveUnitsToDistantToEnemy", parameters)); //Conditional HaveUnitsStrongest parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); conditionalsForGrammar.add(new FunctionsforDSL("HaveUnitsStrongest", parameters)); //Conditional HaveUnitsStrongest parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveUnitsStrongest", parameters)); //Conditional HaveEnemiesStrongest parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); conditionalsForGrammar.add(new FunctionsforDSL("HaveEnemiesStrongest", parameters)); //Conditional HaveEnemiesStrongest parameters = new ArrayList<>(); parameters.add(new ParameterDSL("unitType", null, null, typeUnitDiscrete)); parameters.add(new ParameterDSL("u", null, null, null)); conditionalsForGrammarUnit.add(new FunctionsforDSL("HaveEnemiesStrongest", parameters)); //Conditional IsPlayerInPosition // parameters = new ArrayList<>(); // parameters.add(new ParameterDSL("priorityPositionDiscreteLimited", null, null, priorityPositionDiscreteLimited)); // conditionalsForGrammar.add(new FunctionsforDSL("IsPlayerInPosition", parameters)); } public void printFunctions(List<FunctionsforDSL> functionstoPrint) { for(FunctionsforDSL f: functionstoPrint) { System.out.println(f.nameFunction); } } public List<FunctionsforDSL> getBasicFunctionsForGrammar() { return basicFunctionsForGrammar; } public void setBasicFunctionsForGrammar(List<FunctionsforDSL> newList) { basicFunctionsForGrammar=newList; } public List<FunctionsforDSL> getConditionalsForGrammar() { return conditionalsForGrammar; } public void setConditionalsForGrammar(List<FunctionsforDSL> newList) { conditionalsForGrammar=newList; } public List<FunctionsforDSL> getBasicFunctionsForGrammarUnit() { return basicFunctionsForGrammarUnit; } public List<FunctionsforDSL> getConditionalsForGrammarUnit() { return conditionalsForGrammarUnit; } public String getNameFunction() { return nameFunction; } public List<ParameterDSL> getParameters() { return parameters; } }
17,490
48.549575
123
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/DSLTableGenerator/ParameterDSL.java
package ai.synthesis.dslForScriptGenerator.DSLTableGenerator; import java.util.List; public class ParameterDSL { String parameterName; Double superiorLimit; Double inferiorLimit; List<String> discreteSpecificValues; public ParameterDSL(String parameterName, Object inferiorLimit, Object superiorLimit, Object discreteSpecificValues) { this.parameterName=parameterName; if(superiorLimit != null){ this.superiorLimit=(Double)superiorLimit; }else{ this.superiorLimit = null; } if(inferiorLimit != null){ this.inferiorLimit=(Double)inferiorLimit; }else{ this.inferiorLimit = null; } this.discreteSpecificValues=(List<String>)discreteSpecificValues; } /** * @return the parameterName */ public String getParameterName() { return parameterName; } /** * @return the superiorLimit */ public double getSuperiorLimit() { return superiorLimit; } /** * @return the inferiorLimit */ public double getInferiorLimit() { return inferiorLimit; } /** * @return the discreteSpecificValues */ public List<String> getDiscreteSpecificValues() { return discreteSpecificValues; } }
1,291
21.666667
117
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IBehavior.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.dslForScriptGenerator.IDSLParameters; import rts.GameState; import rts.units.Unit; /** * * @author rubens */ public interface IBehavior extends IParameters{ public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly); }
450
24.055556
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/ICoordinates.java
package ai.synthesis.dslForScriptGenerator.IDSLParameters; public interface ICoordinates extends IParameters{ public int getX(); public int getY(); public void setCoordinates(int x, int y); }
205
24.75
58
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IDistance.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.dslForScriptGenerator.IDSLParameters; /** * * @author rubens */ public interface IDistance extends IParameters{ public int getDistance(); public void setDistance(int value); }
394
23.6875
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IParameters.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.dslForScriptGenerator.IDSLParameters; /** * * @author rubens */ public interface IParameters { }
312
19.866667
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IPlayerTarget.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.dslForScriptGenerator.IDSLParameters; /** * * @author rubens Julian */ public interface IPlayerTarget extends IParameters{ }
336
21.466667
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IPriorityPosition.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.dslForScriptGenerator.IDSLParameters; /** * * @author rubens */ public interface IPriorityPosition extends IParameters{ }
337
21.533333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IQuantity.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.dslForScriptGenerator.IDSLParameters; /** * * @author rubens */ public interface IQuantity extends IParameters{ public int getQuantity(); public void setQuantity(int value); }
394
23.6875
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/dslForScriptGenerator/IDSLParameters/IType.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.dslForScriptGenerator.IDSLParameters; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLEnumerators.EnumTypeUnits; import java.util.List; /** * * @author rubens */ public interface IType extends IParameters{ public List<EnumTypeUnits> getParamTypes(); }
475
25.444444
82
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/configurations/ConfigurationsGrammar.java
package ai.synthesis.grammar.configurations; public final class ConfigurationsGrammar { public static final int SIZE_CHROMOSOME = 10; public static final int SIZE_POPULATION = 100; public static final int NUMBER_JOBS = 39; public static final int SIZE_ELITE = 10; public static final int SIZE_INVADERS = 10; public static final int K_TOURNMENT = 25; public static final int SIZE_PARENTSFORCROSSOVER = 40; public static final double MUTATION_RATE = 0.2; public static final double MUTATION_RATE_RULE = 0.2; public static final double MUTATION_ORDER_RATE = 0.1; public static final boolean INCREASING_INDEX = false; public static final double INCREASING_RATE = 0.2; public static final double DECREASING_RATE = 0.2; public static final int QTD_ENEMIES_SAMPLE_RANDOM = 5; public static final int QTD_ENEMIES_SAMPLE_ELITE = 10; public static final int QTD_RULES = 60088; public static final int SIZE_CHROMOSOME_SCRIPT = 10; public static final int SIZE_TABLE_SCRIPTS = 1000; public static final int TYPE_CONTROL = 1; public static final int TIME_GA_EXEC = 13; public static final int QTD_GENERATIONS = 1000; public static final int deltaForMutation = 1; public static final boolean RESET_ENABLED = true; public static final boolean MUTATION_ORDER_ENABLED = true; public static final boolean curriculum = false; public final static boolean UCB1 = false; public static final int QTD_RULES_CONDITIONAL = 115; public static final int QTD_RULES_BASIC_FUNCTIONS = 518; public static final int MAX_QTD_COMPONENTS = 10; public static boolean recoverTable = false; public final static boolean removeRules = true; public static final boolean evolvingScript = true; public static final boolean sketch = true; public static final String idSketch = "C"; }
1,881
41.772727
62
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/AbstractNodeDSLTree.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; /** * * @author rubens */ public abstract class AbstractNodeDSLTree implements iNodeDSLTree{ private iDSL father; private boolean leaf; public AbstractNodeDSLTree() { this.father = null; this.leaf = false; } @Override public void setFather(iDSL father){ this.father = father; } @Override public iDSL getFather() { return father; } public boolean isLeaf() { return leaf; } public void setLeaf(boolean leaf) { this.leaf = leaf; } public void setMyAsFather(iDSL child, iDSL father){ if(child == null){ return; } if(child instanceof iNodeDSLTree){ iNodeDSLTree iChild = (iNodeDSLTree) child; iChild.setFather(father); }else{ System.err.println("Object Problem with "+child); System.err.println("Object translate "+child.translate()); System.err.println("Problem at method "+ "ai.synthesis.grammar.dslTree.AbstractNodeDSLTree.setAsFather()" + "with type convert"); } } @Override public iNodeDSLTree getRightNode() { return (iNodeDSLTree) getRightChild(); } @Override public iNodeDSLTree getLeftNode() { return (iNodeDSLTree) getLeftChild(); } }
1,730
23.380282
84
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/BooleanDSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iBooleanDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.util.Objects; import java.util.UUID; /** * Represent the Boolean options for IF(B) commands * Example: B-> b_1 | b_2 | ... | b_m * @author rubens */ public class BooleanDSL extends AbstractNodeDSLTree implements iBooleanDSL{ private String uniqueID = UUID.randomUUID().toString(); private String booleanCommand; public BooleanDSL(String booleanCommand) { this.booleanCommand = booleanCommand; super.setLeaf(true); } public BooleanDSL(String booleanCommand, iDSL father) { super.setFather(father); this.booleanCommand = booleanCommand; } @Override public String translate() { return booleanCommand.trim(); } @Override public String friendly_translate() { return booleanCommand.trim(); } public String getBooleanCommand() { return booleanCommand; } public void setBooleanCommand(String booleanCommand) { this.booleanCommand = booleanCommand; } @Override public int hashCode() { int hash = 7; hash = 43 * hash + Objects.hashCode(this.uniqueID); hash = 43 * hash + Objects.hashCode(this.booleanCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BooleanDSL other = (BooleanDSL) obj; if (!Objects.equals(this.booleanCommand, other.booleanCommand)) { return false; } return true; } public BooleanDSL clone(){ return new BooleanDSL(booleanCommand); } @Override public iDSL getRightChild() { return null; } @Override public iDSL getLeftChild() { return null; } @Override public String getFantasyName() { return "B->"+booleanCommand; } @Override public void removeRightNode() { throw new UnsupportedOperationException("Not supported remotion in BooleanDSL."); } @Override public void removeLeftNode() { throw new UnsupportedOperationException("Not supported remotion in BooleanDSL."); } @Override public String formmated_translation() { return booleanCommand; } }
2,756
23.837838
90
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/CDSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iCommandDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iEmptyDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS4ConstraintDSL; import java.util.Objects; /** * Represent de C element at DSL S_1→ C S_1 | S_2 S_1 | S_3 S_1 | empty * * @author rubens */ public class CDSL extends AbstractNodeDSLTree implements iDSL, iS4ConstraintDSL, iS1ConstraintDSL { private iCommandDSL realCommand; //mandatory private CDSL nextCommand; //optional public iCommandDSL getRealCommand() { return realCommand; } public void setRealCommand(iCommandDSL realCommand) { this.realCommand = realCommand; super.setMyAsFather(realCommand, this); } public CDSL getNextCommand() { return nextCommand; } public void setNextCommand(CDSL nextCommand) { this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } public CDSL(iCommandDSL realCommand) { this.realCommand = realCommand; super.setMyAsFather(realCommand, this); this.nextCommand = null; } public CDSL(iCommandDSL realCommand, CDSL nextCommand) { this.realCommand = realCommand; super.setMyAsFather(realCommand, this); this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } public CDSL(iCommandDSL realCommand, CDSL nextCommand, iDSL father) { this(realCommand,nextCommand); super.setFather(father); } @Override public String translate() { if (nextCommand == null) { return realCommand.translate(); } else if (nextCommand instanceof iEmptyDSL) { return realCommand.translate(); } return (realCommand.translate() + " " + nextCommand.translate()).trim(); } @Override public String friendly_translate() { return this.translate(); } @Override public CDSL clone() { if (this.nextCommand == null) { return new CDSL((iCommandDSL) realCommand.clone()); } return new CDSL((iCommandDSL) realCommand.clone(), (CDSL) nextCommand.clone()); } @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.realCommand); hash = 53 * hash + Objects.hashCode(this.nextCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CDSL other = (CDSL) obj; if (!Objects.equals(this.realCommand, other.realCommand)) { return false; } if (!Objects.equals(this.nextCommand, other.nextCommand)) { return false; } return true; } @Override public iDSL getRightChild() { return this.realCommand; } @Override public iDSL getLeftChild() { return this.nextCommand; } @Override public String getFantasyName() { return "C"; } @Override public void removeRightNode() { this.realCommand = null; } @Override public void removeLeftNode() { this.nextCommand = null; } @Override public String formmated_translation() { if (nextCommand == null) { return realCommand.formmated_translation(); } else if (nextCommand instanceof iEmptyDSL) { return realCommand.translate(); } return (realCommand.formmated_translation() + "\t " + nextCommand.formmated_translation()).trim(); } }
4,138
26.593333
106
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/CommandDSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iCommandDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.util.Objects; import java.util.UUID; /** * * @author rubens */ public class CommandDSL extends AbstractNodeDSLTree implements iCommandDSL { private String uniqueID = UUID.randomUUID().toString(); private String grammarDSF; public CommandDSL(String grammarDSF) { this.grammarDSF = grammarDSF; super.setLeaf(true); } public CommandDSL(String grammarDSF, iDSL father) { this(grammarDSF); super.setFather(father); } public String getGrammarDSF() { return grammarDSF; } public void setGrammarDSF(String grammarDSF) { this.grammarDSF = grammarDSF; } @Override public String translate() { return grammarDSF.trim(); } @Override public String friendly_translate() { return this.translate(); } @Override public int hashCode() { int hash = 5; hash = 97 * hash + Objects.hashCode(this.uniqueID); hash = 97 * hash + Objects.hashCode(this.grammarDSF); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CommandDSL other = (CommandDSL) obj; if (!Objects.equals(this.grammarDSF, other.grammarDSF)) { return false; } return true; } @Override public CommandDSL clone() { return new CommandDSL(this.grammarDSF); } @Override public iDSL getRightChild() { return null; } @Override public iDSL getLeftChild() { return null; } @Override public String getFantasyName() { return "c->"+grammarDSF; } @Override public void removeRightNode() { throw new UnsupportedOperationException("Not supported in CommandDSL."); } @Override public void removeLeftNode() { throw new UnsupportedOperationException("Not supported in CommandDSL."); } @Override public String formmated_translation() { return grammarDSF+"\n"; } }
2,572
21.769912
81
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/EmptyDSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iEmptyDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS4ConstraintDSL; import java.util.Objects; import java.util.UUID; /** * * @author rubens */ public class EmptyDSL extends AbstractNodeDSLTree implements iEmptyDSL, iS4ConstraintDSL, iS1ConstraintDSL{ private String uniqueID = UUID.randomUUID().toString(); private String command; public EmptyDSL() { this.command = "(e)"; super.setLeaf(true); } public EmptyDSL(iDSL father) { this(); super.setFather(father); } @Override public String translate() { return command; } @Override public String friendly_translate() { return ""; } @Override public int hashCode() { int hash = 5; hash = 29 * hash + Objects.hashCode(this.uniqueID); hash = 29 * hash + Objects.hashCode(this.command); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EmptyDSL other = (EmptyDSL) obj; if (!Objects.equals(this.command, other.command)) { return false; } return true; } public EmptyDSL clone() { return new EmptyDSL(); } @Override public iDSL getRightChild() { return null; } @Override public iDSL getLeftChild() { return null; } @Override public String getFantasyName() { return "empty"; } @Override public void removeRightNode() { throw new UnsupportedOperationException("Not supported in EmptyDSL."); } @Override public void removeLeftNode() { throw new UnsupportedOperationException("Not supported in EmptyDSL."); } @Override public String formmated_translation() { return ""; } }
2,432
21.738318
107
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S1DSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import java.util.Objects; /** * Class to represent S_1 -> C S_1 | S_2 S_1 | S_3 S_1 | empty * @author rubens */ public class S1DSL extends AbstractNodeDSLTree implements iDSL{ private iS1ConstraintDSL commandS1; //left private S1DSL nextCommand; //right public S1DSL(iS1ConstraintDSL commandS1) { this.commandS1 = commandS1; super.setMyAsFather(commandS1, this); this.nextCommand = null; } public S1DSL(iS1ConstraintDSL commandS1, iDSL father) { this(commandS1); super.setFather(father); } public S1DSL(iS1ConstraintDSL commandS1, S1DSL nextCommand) { this.commandS1 = commandS1; super.setMyAsFather(commandS1, this); this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } public S1DSL(iS1ConstraintDSL commandS1, S1DSL nextCommand, iDSL father) { this(commandS1, nextCommand); super.setFather(father); } @Override public String translate() { if(this.nextCommand == null){ return commandS1.translate(); } return (commandS1.translate()+" "+nextCommand.translate()).trim(); } @Override public String friendly_translate() { return this.translate(); } public iS1ConstraintDSL getCommandS1() { return commandS1; } public void setCommandS1(iS1ConstraintDSL commandS1) { this.commandS1 = commandS1; super.setMyAsFather(commandS1, this); } public S1DSL getNextCommand() { return nextCommand; } public void setNextCommand(S1DSL nextCommand) { this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } @Override public S1DSL clone(){ if(nextCommand == null){ return new S1DSL((iS1ConstraintDSL)commandS1.clone()); } return new S1DSL((iS1ConstraintDSL)commandS1.clone(), (S1DSL)nextCommand.clone()); } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.commandS1); hash = 79 * hash + Objects.hashCode(this.nextCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final S1DSL other = (S1DSL) obj; if (!Objects.equals(this.commandS1, other.commandS1)) { return false; } if (!Objects.equals(this.nextCommand, other.nextCommand)) { return false; } return true; } @Override public iDSL getRightChild() { //return this.commandS1; return this.nextCommand; } @Override public iDSL getLeftChild() { //return this.nextCommand; return this.commandS1; } @Override public String getFantasyName() { return "S1"; } @Override public void removeRightNode() { //this.commandS1 = null; this.nextCommand = null; } @Override public void removeLeftNode() { //this.nextCommand = null; this.commandS1 = null; } @Override public String formmated_translation() { if(this.nextCommand == null){ return commandS1.formmated_translation(); } return (commandS1.formmated_translation()+" \n "+nextCommand.formmated_translation()).trim(); } }
3,959
25.4
101
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S2DSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS4ConstraintDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS5ConstraintDSL; import java.util.Objects; /** * Class to represent S_2 -> if(S5) then {C} | if(B) then {C} else {C} * * @author rubens */ public class S2DSL extends AbstractNodeDSLTree implements iDSL, iS4ConstraintDSL, iS1ConstraintDSL { private iS5ConstraintDSL boolCommand; private CDSL thenCommand; private CDSL elseCommand; public S2DSL(iS5ConstraintDSL boolCommand, CDSL thenCommand) { this.boolCommand = boolCommand; super.setMyAsFather(boolCommand, this); this.thenCommand = thenCommand; super.setMyAsFather(thenCommand, this); this.elseCommand = null; } public S2DSL(iS5ConstraintDSL boolCommand, CDSL thenCommand, iDSL father) { this(boolCommand, thenCommand); super.setFather(father); } public S2DSL(iS5ConstraintDSL boolCommand, CDSL thenCommand, CDSL elseCommand) { this.boolCommand = boolCommand; super.setMyAsFather(boolCommand, this); this.thenCommand = thenCommand; super.setMyAsFather(thenCommand, this); this.elseCommand = elseCommand; super.setMyAsFather(elseCommand, this); } public S2DSL(iS5ConstraintDSL boolCommand, CDSL thenCommand, CDSL elseCommand, iDSL father) { this(boolCommand, thenCommand, elseCommand); super.setFather(father); } /** * The method will translate the objects following the example: * if(HaveQtdUnitsHarversting(20)) -- conditional (attack(Worker,weakest)) * -- then clause (attack(Worker,weakest) attack(Worker,weakest)) -- else * clause * * @return */ @Override public String translate() { String ifCode; ifCode = "if(" + this.boolCommand.translate() + ")"; ifCode += " then(" + this.thenCommand.translate() + ")"; if (this.elseCommand != null) { ifCode += " else(" + this.elseCommand.translate() + ")"; } return ifCode.replace("else()", "").trim(); } @Override public String friendly_translate() { return this.translate(); } public iS5ConstraintDSL getBoolCommand() { return boolCommand; } public void setBoolCommand(iS5ConstraintDSL boolCommand) { this.boolCommand = boolCommand; super.setMyAsFather(boolCommand, this); } public CDSL getThenCommand() { return thenCommand; } public void setThenCommand(CDSL thenCommand) { this.thenCommand = thenCommand; super.setMyAsFather(thenCommand, this); } public CDSL getElseCommand() { return elseCommand; } public void setElseCommand(CDSL elseCommand) { this.elseCommand = elseCommand; super.setMyAsFather(elseCommand, this); } @Override public S2DSL clone() { if (elseCommand == null) { return new S2DSL((iS5ConstraintDSL) boolCommand.clone(), (CDSL) thenCommand.clone()); } return new S2DSL((iS5ConstraintDSL) boolCommand.clone(), (CDSL) thenCommand.clone(), (CDSL) elseCommand.clone() ); } @Override public int hashCode() { int hash = 3; hash = 47 * hash + Objects.hashCode(this.boolCommand); hash = 47 * hash + Objects.hashCode(this.thenCommand); hash = 47 * hash + Objects.hashCode(this.elseCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final S2DSL other = (S2DSL) obj; if (!Objects.equals(this.boolCommand, other.boolCommand)) { return false; } if (!Objects.equals(this.thenCommand, other.thenCommand)) { return false; } if (!Objects.equals(this.elseCommand, other.elseCommand)) { return false; } return true; } @Override public iDSL getRightChild() { //return this.thenCommand; return this.elseCommand; } @Override public iDSL getLeftChild() { //return this.elseCommand; return this.thenCommand; } @Override public String getFantasyName() { return "S2 - if("+boolCommand.translate()+")"; } @Override public void removeRightNode() { //this.thenCommand = null; this.elseCommand = null; } @Override public void removeLeftNode() { //this.elseCommand = null; this.thenCommand = null; } @Override public String formmated_translation() { String ifCode; ifCode = "if(" + this.boolCommand.formmated_translation() + ")\n"; ifCode += " begin-then{\n \t" + this.thenCommand.formmated_translation() + "\n\t}end-then\n"; if (this.elseCommand != null) { ifCode += " begin-else{\n \t" + this.elseCommand.formmated_translation() + "\n\t}end-else"; } return ifCode.replace("begin-else{}end-else", "").trim(); } }
5,649
28.736842
103
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S3DSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import java.util.Objects; /** * Class to represent S_3 -> for (each unit u) {S_4} * * @author rubens */ public class S3DSL extends AbstractNodeDSLTree implements iDSL, iS1ConstraintDSL { private S4DSL forCommand; public S3DSL(S4DSL forCommand) { this.forCommand = forCommand; super.setMyAsFather(forCommand, this); } public S3DSL(S4DSL forCommand, iDSL father) { this(forCommand); super.setFather(father); } @Override public String translate() { return "for(u) (" + forCommand.translate() + ")"; } @Override public String friendly_translate() { return this.translate(); } public S4DSL getForCommand() { return forCommand; } public void setForCommand(S4DSL forCommand) { this.forCommand = forCommand; super.setMyAsFather(forCommand, this); } @Override public S3DSL clone() { return new S3DSL((S4DSL) forCommand.clone()); } @Override public int hashCode() { int hash = 7; hash = 23 * hash + Objects.hashCode(this.forCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final S3DSL other = (S3DSL) obj; if (!Objects.equals(this.forCommand, other.forCommand)) { return false; } return true; } @Override public iDSL getRightChild() { //return this.forCommand; return null; } @Override public iDSL getLeftChild() { //return null; return this.forCommand; } @Override public String getFantasyName() { return "S3 - for"; } @Override public void removeRightNode() { //this.forCommand = null; throw new UnsupportedOperationException("Not supported in S3DSL."); } @Override public void removeLeftNode() { //throw new UnsupportedOperationException("Not supported in S3DSL."); this.forCommand = null; } @Override public String formmated_translation() { return "for(u) {\n\t" + forCommand.formmated_translation()+ "\n\t}\n"; } }
2,721
22.669565
82
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S4DSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS4ConstraintDSL; import java.util.Objects; /** * Class to represent S_4 -> C S_4 | S_2 S_4 | empty * @author rubens */ public class S4DSL extends AbstractNodeDSLTree implements iDSL{ private iS4ConstraintDSL firstDSL; //left private S4DSL nextCommand; //right public S4DSL(iS4ConstraintDSL firstDSL) { this.firstDSL = firstDSL; super.setMyAsFather(firstDSL, this); this.nextCommand = null; } public S4DSL(iS4ConstraintDSL firstDSL, iDSL father) { this(firstDSL); super.setFather(father); } public S4DSL(iS4ConstraintDSL firstDSL, S4DSL nextCommand) { this.firstDSL = firstDSL; super.setMyAsFather(firstDSL, this); this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } public S4DSL(iS4ConstraintDSL firstDSL, S4DSL nextCommand, iDSL father) { this(firstDSL, nextCommand); super.setFather(father); } @Override public String translate() { if(nextCommand == null){ return firstDSL.translate(); } return (firstDSL.translate()+" "+nextCommand.translate()).trim(); } @Override public String friendly_translate() { return this.translate(); } public iS4ConstraintDSL getFirstDSL() { return firstDSL; } public void setFirstDSL(iS4ConstraintDSL firstDSL) { this.firstDSL = firstDSL; super.setMyAsFather(firstDSL, this); } public S4DSL getNextCommand() { return nextCommand; } public void setNextCommand(S4DSL nextCommand) { this.nextCommand = nextCommand; super.setMyAsFather(nextCommand, this); } @Override public S4DSL clone() { if(nextCommand == null){ return new S4DSL((iS4ConstraintDSL)firstDSL.clone()); } return new S4DSL((iS4ConstraintDSL)firstDSL.clone(), (S4DSL)nextCommand.clone()); } @Override public int hashCode() { int hash = 7; hash = 23 * hash + Objects.hashCode(this.firstDSL); hash = 23 * hash + Objects.hashCode(this.nextCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final S4DSL other = (S4DSL) obj; if (!Objects.equals(this.firstDSL, other.firstDSL)) { return false; } if (!Objects.equals(this.nextCommand, other.nextCommand)) { return false; } return true; } @Override public iDSL getRightChild() { //return this.firstDSL; return this.nextCommand; } @Override public iDSL getLeftChild() { //return this.nextCommand; return this.firstDSL; } @Override public String getFantasyName() { return "S4"; } @Override public void removeRightNode() { //this.firstDSL = null; this.nextCommand = null; } @Override public void removeLeftNode() { //this.nextCommand = null; this.firstDSL = null; } @Override public String formmated_translation() { if(nextCommand == null){ return firstDSL.formmated_translation(); } return (firstDSL.formmated_translation()+"\n"+nextCommand.formmated_translation()).trim(); } }
3,900
25.006667
98
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S5DSL.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.grammar.dslTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iBooleanDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS5ConstraintDSL; import java.util.Objects; /** * Class to represent S_5 -> not B | B * * @author rubens */ public class S5DSL extends AbstractNodeDSLTree implements iS5ConstraintDSL{ private S5DSLEnum NotFactor; private iBooleanDSL boolCommand; public S5DSL(iBooleanDSL boolCommand) { this.boolCommand = boolCommand; this.NotFactor = S5DSLEnum.NONE; } public S5DSL(S5DSLEnum NotFactor, iBooleanDSL boolCommand) { this(boolCommand); this.NotFactor = NotFactor; } public S5DSL(iBooleanDSL boolCommand, iDSL father) { super.setFather(father); this.boolCommand = boolCommand; this.NotFactor = S5DSLEnum.NONE; } public S5DSL(S5DSLEnum NotFactor, iBooleanDSL boolCommand, iDSL father) { super.setFather(father); this.boolCommand = boolCommand; this.NotFactor = S5DSLEnum.NONE; this.NotFactor = NotFactor; } public S5DSLEnum getNotFactor() { return NotFactor; } public void setNotFactor(S5DSLEnum NotFactor) { this.NotFactor = NotFactor; } public iBooleanDSL getBoolCommand() { return boolCommand; } public void setBoolCommand(iBooleanDSL boolCommand) { this.boolCommand = boolCommand; } @Override public String translate() { if(this.NotFactor == NotFactor.NONE){ return boolCommand.translate().trim(); }else if (this.NotFactor == NotFactor.NOT) { return "!"+boolCommand.translate().trim(); } return boolCommand.translate().trim(); } @Override public String friendly_translate() { return this.translate(); } @Override public iDSL getRightChild() { //return this.boolCommand; return null; } @Override public iDSL getLeftChild() { //return null; return this.boolCommand; } @Override public String getFantasyName() { return "S5->"+this.translate(); } @Override public void removeRightNode() { //this.boolCommand = null; throw new UnsupportedOperationException("Not supported remotion in BooleanDSL."); } @Override public void removeLeftNode() { //throw new UnsupportedOperationException("Not supported remotion in BooleanDSL."); this.boolCommand = null; } public S5DSL clone() { return new S5DSL(this.NotFactor, (iBooleanDSL) this.boolCommand.clone()); } @Override public int hashCode() { int hash = 3; hash = 97 * hash + Objects.hashCode(this.NotFactor); hash = 97 * hash + Objects.hashCode(this.boolCommand); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final S5DSL other = (S5DSL) obj; if (this.NotFactor != other.NotFactor) { return false; } if (!Objects.equals(this.boolCommand, other.boolCommand)) { return false; } return true; } @Override public String formmated_translation() { if(this.NotFactor == NotFactor.NONE){ return boolCommand.formmated_translation().trim(); }else if (this.NotFactor == NotFactor.NOT) { return "not "+boolCommand.translate().trim(); } return boolCommand.formmated_translation().trim(); } }
4,081
24.835443
92
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/S5DSLEnum.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.grammar.dslTree; /** * * @author rubens */ public enum S5DSLEnum { NONE, NOT, AND, OR; }
303
19.266667
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/builderDSLTree/BuilderDSLTreeSingleton.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.grammar.dslTree.builderDSLTree; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.FunctionsforDSL; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.ParameterDSL; 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.iBooleanDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iCommandDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; class nodeSearchControl { private int nodeCount; public nodeSearchControl() { nodeCount = 1; } public int getNodeCount() { return nodeCount; } public void incrementCounter() { this.nodeCount++; } } /** * Focus on build a complete DSL following the rules: S1DSL -> CDSL S1DSL | * S2DSL S1DSL | S3DSL S1DSL | EmptyDSL S2DSL -> if(BooleanDSL) then {CDSL} | * if(BooleanDSL) then {CDSL} else {CDSL} S3DSL -> for(u) {S4DSL} S4DSL -> CDSL * S4DSL | S2DSL S4DSL | EmptyDSL BooleanDSL -> BooleanDSL1 | BooleanDSL2 | ... * | BooleanDSLm, m = 356 CDSL -> CommandDSL1 CDSL | ... | CommandDSLn CDSL | * CommandDSL1 | ... -> | CommandDSLn | EmptyDSL * * @author rubens */ public class BuilderDSLTreeSingleton { //SETTINGS************************************************ private int C_Grammar_Depth = 4; //3 private final double C_Grammar_Chances_Empty = 0.05; private final double S2_Grammar_Chances_Else = 0.5; private int S4_Grammar_Depth = 4; //2 private int S1_Grammar_Depth = 4; private final double S5_Grammar_Chances_Not = 0.5; //SIZE CONTROLL private final NeighbourTypeEnum type_neigh = NeighbourTypeEnum.LIMITED; private final int MAX_SIZE = 1000; //12 //******************************************************** private static BuilderDSLTreeSingleton uniqueInstance; private final FunctionsforDSL grammar; private static final Random rand = new Random(); /** * The constructor is private to keep the singleton working properly */ private BuilderDSLTreeSingleton() { grammar = new FunctionsforDSL(); } /** * get a instance of the class. * * @return the singleton instance of the class */ public static synchronized BuilderDSLTreeSingleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new BuilderDSLTreeSingleton(); } return uniqueInstance; } public FunctionsforDSL getGrammar() { return grammar; } public NeighbourTypeEnum get_neighbour_type() { return this.type_neigh; } /** * ### Option to build an empty element Returns a instance of EmptyDSL * * @return instance of EmptyDSL configured */ public EmptyDSL buildEmptyDSL() { return new EmptyDSL(); } /** * ### Option to build a randomly CDSL option Build a CDSL (C) grammar with * Empty possibility and multiples levels * * @param includeUnit Boolean that defines if the command is related or not * with the "u" parameter. * @return a CDSL */ public CDSL buildCGramar(boolean includeUnit) { CDSL root = buildRandomlyCGramar(includeUnit); if (root.getRealCommand() instanceof EmptyDSL) { return root; } CDSL child = root; for (int j = 1; j < (rand.nextInt(C_Grammar_Depth) + 1); j++) { CDSL next = buildRandomlyCGramar(includeUnit); child.setNextCommand(next); child = next; if (child.getRealCommand() instanceof EmptyDSL) { return root; } } return root; } /** * Build a CDSL (C) grammar with Empty possibility * * @param includeUnit Boolean that defines if the command is related or not * with the "u" parameter. * @return a CDSL */ public CDSL buildRandomlyCGramar(boolean includeUnit) { if (Math.random() < C_Grammar_Chances_Empty) { return new CDSL(new EmptyDSL()); } else { return buildTerminalCGrammar(includeUnit); } } /** * Build a CDSL (C) grammar without Empty possibility * * @param includeUnit Boolean that defines if the command is related or not * with the "u" parameter. * @return a CDSL */ public CDSL buildTerminalCGrammar(boolean includeUnit) { String sCommand = ""; int infLim; int supLim; String discreteValue; FunctionsforDSL cGrammar; cGrammar = getCommandGrammar(includeUnit); sCommand += cGrammar.getNameFunction() + "("; for (ParameterDSL p : cGrammar.getParameters()) { if ("u".equals(p.getParameterName())) { sCommand += "u,"; } else if (p.getDiscreteSpecificValues() == null) { infLim = (int) p.getInferiorLimit(); supLim = (int) p.getSuperiorLimit(); int parametherValueChosen; if (supLim != infLim) { parametherValueChosen = rand.nextInt(supLim - infLim) + infLim; } else { parametherValueChosen = supLim; } sCommand += parametherValueChosen + ","; } else { int idChosen = rand.nextInt(p.getDiscreteSpecificValues().size()); discreteValue = p.getDiscreteSpecificValues().get(idChosen); sCommand += discreteValue + ","; } } sCommand = sCommand.substring(0, sCommand.length() - 1); sCommand += ") "; iCommandDSL c = new CommandDSL(sCommand); return new CDSL(c); } /** * ### Option to build a B (BooleanDSL) This method returns a BooleanDSL * without a command with parameter "u". * * @param includeUnit Boolean that defines if the command is related or not * with the "u" parameter. * @return a instance of BooleanDSL */ public BooleanDSL buildBGrammar(boolean includeUnit) { String tName; int infLimit, supLimit; String discreteValue; FunctionsforDSL tBoolean; tBoolean = getBooleanGrammar(includeUnit); tName = tBoolean.getNameFunction() + "("; for (ParameterDSL p : tBoolean.getParameters()) { if ("u".equals(p.getParameterName())) { tName += "u,"; } else if (p.getDiscreteSpecificValues() == null) { infLimit = (int) p.getInferiorLimit(); supLimit = (int) p.getSuperiorLimit(); int parametherValueChosen = rand.nextInt(supLimit - infLimit) + infLimit; tName = tName + parametherValueChosen + ","; } else { int idChosen = rand.nextInt(p.getDiscreteSpecificValues().size()); discreteValue = p.getDiscreteSpecificValues().get(idChosen); tName = tName + discreteValue + ","; } } tName = tName.substring(0, tName.length() - 1).concat(")"); return new BooleanDSL(tName); } /** * Returns a FunctionsforDSL used to build the conditional Grammar. * * @param includeUnit Boolean that defines if the command is related or not * @return a FunctionsforDSL with all necessary parameters */ public FunctionsforDSL getBooleanGrammar(boolean includeUnit) { int idBGrammar; if (includeUnit == false) { idBGrammar = rand.nextInt(grammar.getConditionalsForGrammar().size()); return grammar.getConditionalsForGrammar().get(idBGrammar); } else { idBGrammar = rand.nextInt(grammar.getConditionalsForGrammarUnit().size()); return grammar.getConditionalsForGrammarUnit().get(idBGrammar); } } /** * Returns a FunctionsforDSL used to build the C (CDSL) Grammar. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a FunctionsforDSL with all necessary parameters */ public FunctionsforDSL getCommandGrammar(boolean includeUnit) { if (includeUnit == false) { int idBasicActionSelected = rand.nextInt(grammar.getBasicFunctionsForGrammar().size()); return grammar.getBasicFunctionsForGrammar().get(idBasicActionSelected); } else { int idBasicActionSelected = rand.nextInt(grammar.getBasicFunctionsForGrammarUnit().size()); return grammar.getBasicFunctionsForGrammarUnit().get(idBasicActionSelected); } } /** * Returns a S2 (S2DSL) without else. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S2DSL instance with a conditional (BooleanDSL) and then * configured with a C (CSDL) instance. */ public S2DSL buildS2ThenGrammar(boolean includeUnit) { CDSL C = buildCGramar(includeUnit); while (C.getRealCommand() instanceof EmptyDSL || C.translate().equals("")) { C = buildCGramar(includeUnit); } S5DSL s5 = new S5DSL(buildBGrammar(includeUnit)); if (rand.nextFloat() < this.S5_Grammar_Chances_Not) { s5.setNotFactor(S5DSLEnum.NOT); } S2DSL S2 = new S2DSL(s5, C); return S2; } /** * Returns a S2 (S2DSL) with else. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S2DSL instance with a conditional (BooleanDSL), then and else * configured in a C (CSDL) instance. */ public S2DSL buildS2ElseGrammar(boolean includeUnit) { S2DSL S2 = buildS2ThenGrammar(includeUnit); S2.setElseCommand(buildCGramar(includeUnit)); return S2; } /** * ### Option to build a S2 (S2DSL) for randomly cases Returns a S2 (S2DSL) * with else or not, it is defined randomly. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S2DSL instance with a conditional (BooleanDSL), then configured * in a C (CSDL) instance. Else is optional and defined randomly */ public S2DSL buildS2Grammar(boolean includeUnit) { if (Math.random() < S2_Grammar_Chances_Else) { return buildS2ThenGrammar(includeUnit); } else { return buildS2ElseGrammar(includeUnit); } } /** * Returns a S4 (S4DSL) with terminal EmptyDSL, S4 -> empty. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S4DSL instance with an EmptyDSL defined */ public S4DSL buildTerminalS4Grammar(boolean includeUnit) { return new S4DSL(buildEmptyDSL()); } /** * Returns a S4 (S4DSL) with C (CDSL) configured, S4 -> C S4 (next). Obs.: * S4 (next) is defined as null. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S4DSL instance with a C (CDSL) defined */ public S4DSL buildS4WithCGrammar(boolean includeUnit) { return new S4DSL(buildCGramar(includeUnit)); } /** * Returns a S4 (S4DSL) with S2 (S2DSL) configured, S4 -> S2 S4 (next). * Obs.: S4 (next) is defined as null. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S4DSL instance with a S2 (S2DSL) defined */ public S4DSL buildS4WithS2Grammar(boolean includeUnit) { return new S4DSL(buildS2Grammar(includeUnit)); } /** * Returns a S4 (S4DSL) with one possibility 1: C S4 | S2 S4 | empty. Obs.: * S4 (next) is always defined as null. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S4DSL instance */ public S4DSL buildS4RandomlyGrammar(boolean includeUnit) { double p = Math.random(); if (p < 0.45) { return buildS4WithCGrammar(includeUnit); } else if (p > 0.45 && p < 0.95) { return buildS4WithS2Grammar(includeUnit); } else { return buildTerminalS4Grammar(includeUnit); } } /** * ### Option to build a S4 (S4DSL) Returns a S4 (S4DSL) randomly built with * random depth and with one possibility 1: C S4 | S2 S4 | empty. * * @param includeUnit Boolean that defines if the command is related or not * with "u" parameter * @return a S4DSL instance. */ public S4DSL buildS4Grammar(boolean includeUnit) { S4DSL root = buildS4RandomlyGrammar(includeUnit); if (root.getFirstDSL() instanceof EmptyDSL) { return root; } S4DSL child = root; for (int j = 1; j < (rand.nextInt(S4_Grammar_Depth) + 1); j++) { S4DSL next = buildS4RandomlyGrammar(includeUnit); child.setNextCommand(next); child = next; if (child.getFirstDSL() instanceof EmptyDSL) { return root; } } return root; } /** * ### Option to build a S3 (S3DSL) Returns a S3 (S3DSL) as S3 -> for(u) * {S4} where all S4's elements is generated with parameter "u". * * @return a S3DSL instance. */ public S3DSL buildS3Grammar() { S3DSL s3 = new S3DSL(buildS4Grammar(true)); while (s3.translate().equals("for(u) ()")) { s3 = new S3DSL(buildS4Grammar(true)); } return s3; } /** * Returns a S1 (S1DSL) with terminal EmptyDSL, S1 -> empty. * * @return a S1DSL instance with an EmptyDSL defined */ public S1DSL buildTerminalS1Grammar() { return new S1DSL(buildEmptyDSL()); } /** * Returns a S1 (S1DSL) with C(CDSL), S1 -> C S1. * * @return a S1DSL instance with a C (CSDL) defined */ public S1DSL buildS1WithCGrammar() { return new S1DSL(buildCGramar(false)); } /** * Returns a S1 (S1DSL) with S2(S2DSL), S1 -> S2 S1. * * @return a S1DSL instance with a S2 (S2DSL) defined */ public S1DSL buildS1WithS2Grammar() { return new S1DSL(buildS2Grammar(false)); } /** * Returns a S1 (S1DSL) with S3(S3DSL), S1 -> S3 S1. * * @return a S1DSL instance with an S3 (S3DSL) defined */ public S1DSL buildS1WithS3Grammar() { return new S1DSL(buildS3Grammar()); } /** * Returns a S1 (S1DSL) with one possibility 1: C S1 | S2 S1 | S3 S1 | * empty. Obs.: S1 (next) is always defined as null. * * @return a S1DSL instance */ public S1DSL buildS1RandomlyGrammar() { double p = Math.random(); if (p < 0.3) { return buildS1WithCGrammar(); } else if (p > 0.3 && p < 0.6) { return buildS1WithS2Grammar(); } else if (p > 0.6 && p < 0.9) { return buildS1WithS3Grammar(); } else { return buildTerminalS1Grammar(); } } /** * ### Option to build a S1 (S1DSL) Returns a S1 (S1DSL) randomly built with * random depth and with one possibility 1: C S1 | S2 S1 | S3 S1 | empty. * Obs.: The S1 never will be empty as translation equals to "" * * @return a S1DSL instance. */ public S1DSL buildS1Grammar() { S1DSL root = buildS1RandomlyGrammar(); while (root.translate().equals("")) { root = buildS1RandomlyGrammar(); } S1DSL child = root; for (int j = 1; j < (rand.nextInt(S1_Grammar_Depth) + 1); j++) { S1DSL next = buildS1RandomlyGrammar(); child.setNextCommand(next); child = next; if (child.getCommandS1() instanceof EmptyDSL) { return root; } } return root; } /** * Return the total of nodes in the tree * * @param root - the node (iNodeDSLTree) that will be considered root * @return int value with the total number of nodes found bellow the root */ public static int getNumberofNodes(iNodeDSLTree root) { if (root == null) { return 0; } return 1 + getNumberofNodes(root.getRightNode()) + getNumberofNodes(root.getLeftNode()); } /** * Print the tree line to line * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void simpleTreePreOrderPrint(iNodeDSLTree root) { StringBuilder sb = new StringBuilder(); traversePreOrder(sb, root); System.out.println(sb.toString()); } public static void traversePreOrder(StringBuilder sb, iNodeDSLTree node) { if (node != null) { iDSL temp = (iDSL) node; sb.append(temp.getClass().getName() + " " + temp.translate()); sb.append("\n"); traversePreOrder(sb, node.getRightNode()); traversePreOrder(sb, node.getLeftNode()); } } /** * Print the tree in four different layouts 1 - class name + translate of * the DSL 2 - class name 3 - translate of the DSL 4 - DSL variations * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void fullPreOrderPrint(iNodeDSLTree root) { formatedFullTreePreOrderPrint(root); formatedDSLTreePreOrderPrint(root); formatedGrammarTreePreOrderPrint(root); formatedStructuredDSLTreePreOrderPrint(root); } /** * Print the tree using layout 1 - class name + translate of the DSL * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void formatedFullTreePreOrderPrint(iNodeDSLTree root) { StringBuilder sb = new StringBuilder(); traversePreOrderFormated(sb, "", "", root, 1); System.out.println(sb.toString()); } /** * Print the tree using layout 2 - class name * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void formatedDSLTreePreOrderPrint(iNodeDSLTree root) { StringBuilder sb = new StringBuilder(); traversePreOrderFormated(sb, "", "", root, 2); System.out.println(sb.toString()); } /** * Print the tree using layout 3 - translate of the DSL * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void formatedGrammarTreePreOrderPrint(iNodeDSLTree root) { StringBuilder sb = new StringBuilder(); traversePreOrderFormated(sb, "", "", root, 3); System.out.println(sb.toString()); } /** * Print the tree using layout 4 - DSL variations * * @param root - the node (iNodeDSLTree) that will be considered root */ public static void formatedStructuredDSLTreePreOrderPrint(iNodeDSLTree root) { StringBuilder sb = new StringBuilder(); traversePreOrderFormated(sb, "", "", root, 4); System.out.println(sb.toString()); } public static void traversePreOrderFormated(StringBuilder sb, String padding, String pointer, iNodeDSLTree node, int idForm) { if (node != null) { iDSL temp = (iDSL) node; sb.append(padding); sb.append(pointer); if (idForm == 1) { sb.append(temp.getClass().getName() + " " + temp.translate()); } else if (idForm == 2) { sb.append(temp.getClass().getName()); } else if (idForm == 3) { sb.append(temp.translate()); } else { sb.append(node.getFantasyName()); } sb.append("\n"); StringBuilder paddingBuilder = new StringBuilder(padding); paddingBuilder.append("│ "); String paddingForBoth = paddingBuilder.toString(); String pointerForRight = "└──"; String pointerForLeft = (node.getRightNode() != null) ? "├──" : "└──"; traversePreOrderFormated(sb, paddingForBoth, pointerForLeft, node.getLeftNode(), idForm); traversePreOrderFormated(sb, paddingForBoth, pointerForRight, node.getRightNode(), idForm); } } /** * Returns a reference of the tree related with the position in pre-order * * @param nNode index of the node to be returned * @param root Root of the three * @return an iNodeDSLTree reference related with the position @param nNode */ public static iNodeDSLTree getNodeByNumber(int nNode, iNodeDSLTree root) { if (nNode > getNumberofNodes(root)) { return null; } nodeSearchControl counter = new nodeSearchControl(); HashSet<iNodeDSLTree> list = new HashSet<>(); return walkTree(root, counter, nNode, list); } /** * Return all nodes in the tree. * * @param root the root node * @return a HashSet of nodes. */ public static HashSet<iNodeDSLTree> getAllNodes(iNodeDSLTree root) { nodeSearchControl counter = new nodeSearchControl(); HashSet<iNodeDSLTree> list = new HashSet<>(); walkTree(root, counter, getNumberofNodes(root), list); return list; } public static iNodeDSLTree walkTree(iNodeDSLTree root, nodeSearchControl count, int target, HashSet<iNodeDSLTree> list) { if (root == null) { return null; } if (target == count.getNodeCount()) { return root; } if (!list.contains(root)) { list.add(root); count.incrementCounter(); } iNodeDSLTree left = walkTree(root.getLeftNode(), count, target, list); if (left != null) { return left; } iNodeDSLTree right = walkTree(root.getRightNode(), count, target, list); return right; } /** * Returns if a node (iNodeDSLTree) has a S3 (for) as father. It is useful * to determine if the command to be generated needs "u" or not. * * @param node - any node in the tree. * @return True - If @param node has S3 as father False - otherwise. */ public boolean hasS3asFather(iNodeDSLTree node) { if (node == null) { return false; } if (node.getFather() instanceof S3DSL) { return true; } return hasS3asFather((iNodeDSLTree) node.getFather()); } /** * Returns if a node (iNodeDSLTree) has a S2 (If) as father. It is useful to * determine if the command to be generated allows or not empty. * * @param node - any node in the tree. * @return True - If @param node has S2 as father False - otherwise. */ public boolean hasS2asFather(iNodeDSLTree node) { if (node == null) { return false; } if (node.getFather() instanceof S2DSL) { return true; } return hasS2asFather((iNodeDSLTree) node.getFather()); } /** * Modify a DSL according her class. Special cases are: BooleanDSL and * CommandDSL - The generator will change just parameters. * * @param dsl - a iDSL class to be modified * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a new iDSL of the same class as passed. */ public iDSL smallModificationInCommand(iDSL dsl, boolean hasS3Father) { if (dsl instanceof BooleanDSL) { BooleanDSL temp = (BooleanDSL) dsl; String boolName = temp.getBooleanCommand(); String newBooleanCommand = changeJustBooleanParameters(boolName, hasS3Father); temp.setBooleanCommand(newBooleanCommand); return temp; } else if (dsl instanceof CommandDSL) { CommandDSL temp = (CommandDSL) dsl; if (hasS2asFather((iNodeDSLTree) dsl)) { String newCommand = modifyParamsCommand(temp, hasS3Father); temp.setGrammarDSF(newCommand); while (temp.translate().equals("")) { newCommand = modifyParamsCommand(temp, hasS3Father); temp.setGrammarDSF(newCommand); } } return temp; } else if (dsl instanceof CDSL) { CDSL temp = (CDSL) dsl; if (hasS2asFather((iNodeDSLTree) dsl)) { CDSL n = buildTerminalCGrammar(hasS3Father); temp.setNextCommand(n.getNextCommand()); temp.setRealCommand(n.getRealCommand()); while (temp.translate().equals("")) { n = buildTerminalCGrammar(hasS3Father); temp.setNextCommand(n.getNextCommand()); temp.setRealCommand(n.getRealCommand()); } } return temp; } else if (dsl instanceof EmptyDSL) { return smallModificationInCommand(((EmptyDSL) dsl).getFather(), hasS3Father); } else if (dsl instanceof S1DSL) { S1DSL temp = (S1DSL) dsl; S1DSL n = buildS1Grammar(); temp.setNextCommand(n.getNextCommand()); temp.setCommandS1(n.getCommandS1()); return temp; } else if (dsl instanceof S2DSL) { S2DSL temp = (S2DSL) dsl; S2DSL n = changeS2DLS(temp.clone(), hasS3Father); temp.setBoolCommand(n.getBoolCommand()); temp.setThenCommand(n.getThenCommand()); temp.setElseCommand(n.getElseCommand()); return temp; } else if (dsl instanceof S3DSL) { S3DSL temp = (S3DSL) dsl; S3DSL n = new S3DSL(buildS4RandomlyGrammar(hasS3Father)); temp.setForCommand(n.getForCommand()); return temp; } else if (dsl instanceof S4DSL) { S4DSL temp = (S4DSL) dsl; S4DSL n = buildS4RandomlyGrammar(hasS3Father); temp.setFirstDSL(n.getFirstDSL()); temp.setNextCommand(n.getNextCommand()); return temp; } return null; } /** * Modify a DSL according her class. Special cases are: BooleanDSL and * CommandDSL - The generator will, randomly, decide if change completely * the actions in these classes or change just some parameters. * * @param dsl - a iDSL class to be modified * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a new iDSL of the same class as passed. */ public iDSL generateNewCommand(iDSL dsl, boolean hasS3Father) { if (dsl instanceof BooleanDSL) { BooleanDSL temp = (BooleanDSL) dsl; String newBooleanCommand = modifyBoolean(temp, hasS3Father); temp.setBooleanCommand(newBooleanCommand); return temp; } else if (dsl instanceof CommandDSL) { CommandDSL temp = (CommandDSL) dsl; if (hasS2asFather((iNodeDSLTree) dsl)) { String newCommand = modifyCommand(temp, hasS3Father); temp.setGrammarDSF(newCommand); while (temp.translate().equals("")) { newCommand = modifyCommand(temp, hasS3Father); temp.setGrammarDSF(newCommand); } } return temp; } else if (dsl instanceof CDSL) { CDSL temp = (CDSL) dsl; if (hasS2asFather((iNodeDSLTree) dsl)) { CDSL n = buildCGramar(hasS3Father); temp.setNextCommand(n.getNextCommand()); temp.setRealCommand(n.getRealCommand()); while (temp.translate().equals("")) { n = buildCGramar(hasS3Father); temp.setNextCommand(n.getNextCommand()); temp.setRealCommand(n.getRealCommand()); } } return temp; } else if (dsl instanceof EmptyDSL) { return generateNewCommand(((EmptyDSL) dsl).getFather(), hasS3Father); } else if (dsl instanceof S1DSL) { S1DSL temp = (S1DSL) dsl; S1DSL n = buildS1Grammar(); temp.setNextCommand(n.getNextCommand()); temp.setCommandS1(n.getCommandS1()); return temp; } else if (dsl instanceof S2DSL) { S2DSL temp = (S2DSL) dsl; S2DSL n = modifyS2DLS(temp.clone(), hasS3Father); temp.setBoolCommand(n.getBoolCommand()); temp.setThenCommand(n.getThenCommand()); temp.setElseCommand(n.getElseCommand()); return temp; } else if (dsl instanceof S3DSL) { S3DSL temp = (S3DSL) dsl; S3DSL n = buildS3Grammar(); temp.setForCommand(n.getForCommand()); return temp; } else if (dsl instanceof S4DSL) { S4DSL temp = (S4DSL) dsl; S4DSL n = buildS4Grammar(hasS3Father); temp.setFirstDSL(n.getFirstDSL()); temp.setNextCommand(n.getNextCommand()); return temp; } return null; } /** * Generates a new BooleanDSL with some probability to modify its completely * or partially. * * @param bGrammar - the original BooleanDSL that will be changed. * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a String with the new conditional command. */ public String modifyBoolean(BooleanDSL bGrammar, boolean hasS3Father) { double p = Math.random(); if (p < 0.4) { //change completely the boolean command. return buildBGrammar(hasS3Father).getBooleanCommand(); } else { String boolName = bGrammar.getBooleanCommand(); //change the parameters return changeJustBooleanParameters(boolName, hasS3Father); } } public String changeJustBooleanParameters(String boolName, boolean includeUnit) { String sName = boolName.substring(0, boolName.indexOf("(")); List<ParameterDSL> parameters = getParameterForBoolean(sName, includeUnit); if (includeUnit && !boolName.contains(",u")) { parameters = getParameterForBoolean(sName, false); } int infLimit, supLimit; String discreteValue; sName += "("; int iParam = rand.nextInt(parameters.size()); String[] params = boolName.replace(sName, "").replace("(", "").replace(")", ""). split(","); for (int i = 0; i < parameters.size(); i++) { sName = sName.trim(); if (i != iParam) { sName += params[i] + ","; } else { ParameterDSL p = (ParameterDSL) parameters.toArray()[iParam]; if ("u".equals(p.getParameterName())) { sName += "u,"; } else if (p.getDiscreteSpecificValues() == null) { infLimit = (int) p.getInferiorLimit(); supLimit = (int) p.getSuperiorLimit(); int parametherValueChosen = rand.nextInt(supLimit - infLimit) + infLimit; sName += parametherValueChosen + ","; } else { int idChosen = rand.nextInt(p.getDiscreteSpecificValues().size()); discreteValue = p.getDiscreteSpecificValues().get(idChosen); sName += discreteValue + ","; } } } sName = sName.substring(0, sName.length() - 1).trim().concat(")"); if (boolName.equals(sName)) { sName = changeJustBooleanParameters(boolName, includeUnit); } return sName; } public List<ParameterDSL> getParameterForBoolean(String boolName, boolean includeUnit) { if (includeUnit) { for (FunctionsforDSL f : grammar.getConditionalsForGrammarUnit()) { if (f.getNameFunction().equals(boolName)) { return f.getParameters(); } } } else { for (FunctionsforDSL f : grammar.getConditionalsForGrammar()) { if (f.getNameFunction().equals(boolName)) { return f.getParameters(); } } } return null; } /** * Generates a new CommandDSL with some probability to modify its completely * or partially. * * @param temp - the original CommandDSL that will be changed. * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a String with the new C command. */ public String modifyCommand(CommandDSL temp, boolean hasS3Father) { double p = Math.random(); if (p < 0.4) { //change completely the C command . return buildTerminalCGrammar(hasS3Father).getRealCommand().translate(); } else { String cName = temp.getGrammarDSF(); //change the parameters return changeJustCommandParameters(cName, hasS3Father); } } /** * Generates modifications in CommandDSL without probability of modify its * completely. * * @param temp - the original CommandDSL that will be changed. * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a String with the new C command. */ public String modifyParamsCommand(CommandDSL temp, boolean hasS3Father) { String cName = temp.getGrammarDSF(); //change the parameters return changeJustCommandParameters(cName, hasS3Father); } public String changeJustCommandParameters(String cName, boolean hasS3Father) { String sName = cName.substring(0, cName.indexOf("(")); List<ParameterDSL> parameters = getParameterForCommand(sName, hasS3Father); if (hasS3Father && !cName.contains(",u")) { parameters = getParameterForCommand(sName, false); } int infLim, supLim; String discreteValue; sName += "("; int iParam = rand.nextInt(parameters.size()); String[] params = cName.replace(sName, "").replace("(", "").replace(")", ""). split(","); for (int i = 0; i < parameters.size(); i++) { sName = sName.trim(); if (i != iParam) { sName += params[i] + ","; } else { ParameterDSL p = (ParameterDSL) parameters.toArray()[iParam]; if ("u".equals(p.getParameterName())) { sName += "u,"; } else if (p.getDiscreteSpecificValues() == null) { infLim = (int) p.getInferiorLimit(); supLim = (int) p.getSuperiorLimit(); int parametherValueChosen; if (supLim != infLim) { parametherValueChosen = rand.nextInt(supLim - infLim) + infLim; } else { parametherValueChosen = supLim; } sName += parametherValueChosen + ","; } else { int idChosen = rand.nextInt(p.getDiscreteSpecificValues().size()); discreteValue = p.getDiscreteSpecificValues().get(idChosen); sName += discreteValue + ","; } } } sName = sName.substring(0, sName.length() - 1).trim().concat(")"); if (cName.equals(sName)) { sName = changeJustCommandParameters(cName, hasS3Father); } return sName; } public List<ParameterDSL> getParameterForCommand(String comName, boolean includeUnit) { if (includeUnit) { for (FunctionsforDSL f : grammar.getBasicFunctionsForGrammarUnit()) { if (f.getNameFunction().equals(comName)) { return f.getParameters(); } } } else { for (FunctionsforDSL f : grammar.getBasicFunctionsForGrammar()) { if (f.getNameFunction().equals(comName)) { return f.getParameters(); } } } return null; } /** * Generates a new S2DSL with some probability to modify its completely or * partially. * * @param temp - the original S2DSL that will be changed. * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a S2DSL with modification. */ public S2DSL modifyS2DLS(S2DSL temp, boolean hasS3Father) { double p = Math.random(); if (p < 0.25) { //change te S2 completly return buildS2Grammar(hasS3Father); } else if (p >= 0.25 && p < 0.5) { //change boolean iBooleanDSL b = new BooleanDSL(modifyBoolean((BooleanDSL) ((S5DSL) temp.getBoolCommand()).getBoolCommand(), hasS3Father)); S5DSL s5 = new S5DSL(b); if (rand.nextFloat() < this.S5_Grammar_Chances_Not) { s5.setNotFactor(S5DSLEnum.NOT); }else{ s5.setNotFactor(S5DSLEnum.NONE); } temp.setBoolCommand(s5); return temp; } else if (p >= 0.5 && p < 0.75) { //change then CDSL then = buildCGramar(hasS3Father); while (then.translate().equals("")) { then = buildCGramar(hasS3Father); } temp.setThenCommand(then); return temp; } else if (p >= 0.75 && p < 1.0) { //change else CDSL els = buildCGramar(hasS3Father); temp.setElseCommand(els); return temp; } return buildS2Grammar(hasS3Father); } /** * Generates a new S2DSL without probability of modify its completely. * * @param temp - the original S2DSL that will be changed. * @param hasS3Father - If the iDSL is child of a S3SDL (for structure) * @return a S2DSL with modification. */ public S2DSL changeS2DLS(S2DSL temp, boolean hasS3Father) { double p = Math.random(); if (p < 0.34) { //change boolean iBooleanDSL b = new BooleanDSL(modifyBoolean( (BooleanDSL) ((S5DSL) temp.getBoolCommand()).getBoolCommand(), hasS3Father)); S5DSL s5 = new S5DSL(b); if (rand.nextFloat() < this.S5_Grammar_Chances_Not) { s5.setNotFactor(S5DSLEnum.NOT); }else{ s5.setNotFactor(S5DSLEnum.NONE); } temp.setBoolCommand(s5); return temp; } else if (p >= 0.35 && p < 0.68) { //change then CDSL then = buildCGramar(hasS3Father); while (then.translate().equals("")) { then = buildCGramar(hasS3Father); } temp.setThenCommand(then); return temp; } else { //change else CDSL els = buildCGramar(hasS3Father); temp.setElseCommand(els); return temp; } } /** * Change randomly the iDSL producing alterations in the structure Obs.: It * is guarantee that the iDSL will be modified. * * @param dsl - the DSL to be modified * @return a new iDSL based on the original. */ public iDSL composeNeighbour(iDSL dsl) { String originalDSL = dsl.translate(); int nNode = rand.nextInt(BuilderDSLTreeSingleton.getNumberofNodes((iNodeDSLTree) dsl)) + 1; //System.out.println("Node selected " + nNode); iNodeDSLTree targetNode = BuilderDSLTreeSingleton.getNodeByNumber(nNode, (iNodeDSLTree) dsl); generateNewCommand((iDSL) targetNode, hasS3asFather(targetNode)); while (dsl.translate().equals(originalDSL) || dsl.translate().equals("")) { dsl = composeNeighbour(dsl); } return dsl; } /** * #### Static variation of composeNeighbour method Change randomly the iDSL * producing alterations in the structure Obs.: It is guarantee that the * iDSL will be modified. * * @param dsl - the DSL to be modified * @return a new iDSL based on the original. */ public static iDSL getNeighbourAgressively(iDSL dsl) { return BuilderDSLTreeSingleton.getInstance().composeNeighbour(dsl); } /** * Change randomly the iDSL producing alterations in the structure Obs.: It * is guarantee that the iDSL will be modified. * * This version is more conservative changing with high probability terminal * parts of the DSL. * * @param dsl - the DSL to be modified * @return a new iDSL based on the original. */ public iDSL composeNeighbourPassively(iDSL dsl) { if (get_neighbour_type() == NeighbourTypeEnum.LIMITED) { return composeNeighbourWithSizeLimit(dsl); } String originalDSL = dsl.translate(); //get all necessary nodes HashSet<iNodeDSLTree> nodes = getNodesWithoutDuplicity(dsl); // re-count the nodes List<iNodeDSLTree> fullNodes = countNodes(nodes); //shuffle then Collections.shuffle(fullNodes); //select the node and change int nNode = rand.nextInt(nodes.size()); iNodeDSLTree targetNode = (iNodeDSLTree) nodes.toArray()[nNode]; generateNewCommand((iDSL) targetNode, hasS3asFather(targetNode)); //guarantee some modification while (dsl.translate().equals(originalDSL) || dsl.translate().equals("")) { dsl = composeNeighbourPassively(dsl); } return dsl; } /** * Change randomly the iDSL producing alterations in the structure Obs.: It * is guarantee that the iDSL will be modified. * * This version is more conservative changing with high probability terminal * parts of the DSL. * * This method limits the size of the AST that will be generated. The * technique of removing rules is not necessary with this method. * * * @param dsl - the DSL to be modified * @return a new iDSL based on the original. */ public iDSL composeNeighbourWithSizeLimit(iDSL dsl) { String originalDSL = dsl.translate(); //get all necessary nodes HashSet<iNodeDSLTree> nodes = getNodesWithoutDuplicity(dsl); if (count_by_commands(nodes) >= this.MAX_SIZE) { dsl = get_ast_with_small_modifications(dsl); } else { dsl = get_new_ast_with_modifications(dsl); } //guarantee some modification while (dsl.translate().equals(originalDSL) || dsl.translate().equals("")) { dsl = composeNeighbourWithSizeLimit(dsl); } return dsl; } private iDSL get_ast_with_small_modifications(iDSL ast) { HashSet<iNodeDSLTree> nodes = getNodesWithoutDuplicity(ast); // re-count the nodes List<iNodeDSLTree> fullNodes = countNodes(nodes); //shuffle then Collections.shuffle(fullNodes); //select the node and change int nNode = rand.nextInt(nodes.size()); iNodeDSLTree targetNode = (iNodeDSLTree) nodes.toArray()[nNode]; smallModificationInCommand((iDSL) targetNode, hasS3asFather(targetNode)); return ast; } private iDSL get_new_ast_with_modifications(iDSL ast) { HashSet<iNodeDSLTree> nodes = getNodesWithoutDuplicity(ast); redefine_param(nodes.size()); // re-count the nodes List<iNodeDSLTree> fullNodes = countNodes(nodes); //shuffle then Collections.shuffle(fullNodes); //select the node and change int nNode = rand.nextInt(nodes.size()); iNodeDSLTree targetNode = (iNodeDSLTree) nodes.toArray()[nNode]; generateNewCommand((iDSL) targetNode, hasS3asFather(targetNode)); return ast; } public HashSet<iNodeDSLTree> getNodesWithoutDuplicity(iDSL dsl) { HashSet<iNodeDSLTree> list = new HashSet<>(); collectNodes((iNodeDSLTree) dsl, list); return list; } public static iNodeDSLTree collectNodes(iNodeDSLTree root, HashSet<iNodeDSLTree> list) { if (root == null) { return null; } if (!list.contains(root)) { list.add(root); } iNodeDSLTree left = collectNodes(root.getLeftNode(), list); if (left != null) { return left; } iNodeDSLTree right = collectNodes(root.getRightNode(), list); return right; } public List<iNodeDSLTree> countNodes(HashSet<iNodeDSLTree> nodes) { List<iNodeDSLTree> counted = new ArrayList<>(); for (iNodeDSLTree node : nodes) { int total = 0; if (node instanceof BooleanDSL) { total = countParameters(((BooleanDSL) node).getBooleanCommand()) - 1; } else if (node instanceof CommandDSL) { total = countParameters(((CommandDSL) node).getGrammarDSF()) - 1; } else if (node instanceof S2DSL) { S2DSL s2 = (S2DSL) node; //include Boolean total = countParameters(s2.getBoolCommand().translate()); for (int i = 0; i < total; i++) { counted.add(s2.getBoolCommand()); } total = 0; } counted.add(node); for (int i = 0; i < total; i++) { counted.add(node); } } return counted; } public int countParameters(String command) { String[] items = command.replace("(", ",").split(","); return items.length; } /** * #### Static variation of composeNeighbourPassively method Change randomly * the iDSL * * Change randomly the iDSL producing alterations in the structure Obs.: It * is guarantee that the iDSL will be modified. * * This version is more conservative changing with high probability terminal * parts of the DSL. * * @param dsl - the DSL to be modified * @return a new iDSL based on the original. */ public static iDSL changeNeighbourPassively(iDSL dsl) { BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); if (builder.get_neighbour_type() == NeighbourTypeEnum.LIMITED) { dsl = builder.composeNeighbourWithSizeLimit(dsl); while (builder.count_by_commands(builder.getNodesWithoutDuplicity(dsl)) > builder.MAX_SIZE) { dsl = builder.composeNeighbourWithSizeLimit(dsl); } return dsl; } return builder.composeNeighbourPassively(dsl); } private void redefine_param(int size) { // if (size > (this.MAX_SIZE / 2) + 1) { // this.C_Grammar_Depth = 1; // this.S1_Grammar_Depth = 1; // this.S4_Grammar_Depth = 1; // } else { // this.C_Grammar_Depth = 2; // this.S1_Grammar_Depth = 3; // this.S4_Grammar_Depth = 2; // } } private int count_by_commands(HashSet<iNodeDSLTree> nodes) { int count = 0; for (iNodeDSLTree node : nodes) { if (node instanceof CommandDSL) { count++; } else if (node instanceof S2DSL) { count++; } else if (node instanceof S3DSL) { count++; } } return count; } }
48,691
36.112805
103
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/builderDSLTree/BuilderSketchDSLSingleton.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.grammar.dslTree.builderDSLTree; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.FunctionsforDSL; import ai.synthesis.dslForScriptGenerator.DSLTableGenerator.ParameterDSL; 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.iCommandDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; /** * * @author rubens */ public class BuilderSketchDSLSingleton { private static BuilderSketchDSLSingleton uniqueInstance; private static final Random rand = new Random(); /** * The constructor is private to keep the singleton working properly */ public BuilderSketchDSLSingleton() { } /** * Get a instance of the class BuilderSketchDSLSingleton. * * @return the singleton instance of the class BuilderSketchDSLSingleton */ public static synchronized BuilderSketchDSLSingleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new BuilderSketchDSLSingleton(); } return uniqueInstance; } /** * Consist of build an initial iDSL preformed. * * Obs.: The preformed model is built inside of the method. * * @return a preformed iDSL starts from S1DSL. */ public iDSL getSketchTypeOne() { // attack harvest train //building sketch CDSL CTrain = buildCGrammarbyName(false, "train"); CDSL Charvest = buildCGrammarbyName(false, "harvest"); CDSL Cattack = buildCGrammarbyName(false, "attack"); //setting order Charvest.setNextCommand(CTrain); CTrain.setNextCommand(Cattack); S1DSL s1 = new S1DSL(Charvest, new EmptyDSL()); return s1; } /** * Consist of build an initial iDSL preformed. * * Obs.: The preformed model is built inside of the method. * * @return a preformed iDSL starts from S1DSL. */ public iDSL getSketchTypeTwo() { // attack harvest train //building sketch CDSL CTrain = buildCGrammarbyName(true, "train"); CDSL Charvest = buildCGrammarbyName(true, "harvest"); CDSL Cattack = buildCGrammarbyName(true, "attack"); BooleanDSL B = BuilderDSLTreeSingleton.getInstance().buildBGrammar(true); S5DSL s5 = new S5DSL(B); if (rand.nextFloat() < 0.5) { s5.setNotFactor(S5DSLEnum.NOT); } //setting order CTrain.setNextCommand(Charvest); S2DSL ifDSl = new S2DSL(s5, Cattack, Cattack.clone()); S4DSL comFor = new S4DSL(CTrain); comFor.setNextCommand(new S4DSL(ifDSl)); S3DSL forDSL = new S3DSL(comFor); S1DSL s1 = new S1DSL(forDSL, new EmptyDSL()); return s1; } /** * Builds a CDSL by the name of the command. * * @param includeUnit - If the father is a S3 (for) * @param commandName - Name of the command that will be generated * @return a CDSL with alterations in one of the parameters.. */ public CDSL buildCGrammarbyName(boolean includeUnit, String commandName) { String sCommand = ""; int infLim; int supLim; String discreteValue; FunctionsforDSL cGrammar; cGrammar = getCommandGrammar(includeUnit, commandName); sCommand += cGrammar.getNameFunction() + "("; for (ParameterDSL p : cGrammar.getParameters()) { if ("u".equals(p.getParameterName())) { sCommand += "u,"; } else if (p.getDiscreteSpecificValues() == null) { infLim = (int) p.getInferiorLimit(); supLim = (int) p.getSuperiorLimit(); int parametherValueChosen; if (supLim != infLim) { parametherValueChosen = rand.nextInt(supLim - infLim) + infLim; } else { parametherValueChosen = supLim; } sCommand += parametherValueChosen + ","; } else { int idChosen = rand.nextInt(p.getDiscreteSpecificValues().size()); discreteValue = p.getDiscreteSpecificValues().get(idChosen); sCommand += discreteValue + ","; } } sCommand = sCommand.substring(0, sCommand.length() - 1); sCommand += ") "; iCommandDSL c = new CommandDSL(sCommand); return new CDSL(c); } /** * Return a specific C command by looking for its name. * * @param includeUnit - If the parameter is related with S3 (for) * @param name - Name of the command. * @return a Function for be used. */ public FunctionsforDSL getCommandGrammar(boolean includeUnit, String name) { FunctionsforDSL grammar = BuilderDSLTreeSingleton.getInstance().getGrammar(); if (includeUnit == false) { for (FunctionsforDSL f : grammar.getBasicFunctionsForGrammar()) { if (f.getNameFunction().equals(name)) { return f; } } } else { for (FunctionsforDSL f : grammar.getBasicFunctionsForGrammarUnit()) { if (f.getNameFunction().equals(name)) { return f; } } } return null; } /** * This method modify the commandDSL and BooleanDSL changing the parameters * The focus of this method is to be used as support for sketch features. * * obs.: This method change the DSL passed, be careful to send a clone, if * necessary. * * @param dsl The initial node of the DSL */ public void modifyTerminalParameters(iDSL dsl) { String originalDSl = dsl.translate(); BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); HashSet<iNodeDSLTree> nodes = new HashSet<>(builder.countNodes(builder.getNodesWithoutDuplicity(dsl))); List<iNodeDSLTree> commandNodes = new ArrayList<>(getJustCCommands(nodes)); List<iNodeDSLTree> boolNodes = new ArrayList<>(getJustBoolean(nodes)); Collections.shuffle(commandNodes); if (boolNodes.isEmpty()) { //select just between C commands CommandDSL tNode = (CommandDSL) commandNodes.toArray()[rand.nextInt(commandNodes.size())]; tNode.setGrammarDSF( builder.changeJustCommandParameters(tNode.getGrammarDSF(), builder.hasS3asFather(tNode)) ); } else { //choose between all nodes boolNodes.addAll(commandNodes); Collections.shuffle(boolNodes); iNodeDSLTree tNode = (iNodeDSLTree) boolNodes.toArray()[rand.nextInt(boolNodes.size())]; boolean hasS3Father = builder.hasS3asFather(tNode); if (tNode instanceof CommandDSL) { CommandDSL tC = (CommandDSL) tNode; tC.setGrammarDSF( builder.changeJustCommandParameters(tC.getGrammarDSF(), hasS3Father) ); } else { BooleanDSL tB = (BooleanDSL) tNode; if (Math.random() < 0.6) { tB.setBooleanCommand( builder.changeJustBooleanParameters(tB.getBooleanCommand(), hasS3Father) ); } else { tB.setBooleanCommand( builder.buildBGrammar(hasS3Father).getBooleanCommand() ); } } } while (originalDSl.equals(dsl.translate())) { modifyTerminalParameters(dsl); } } /** * Return just nodes related with CommandDSL * * @param nodes a list of iNodeDSLTree * @return a filtered list of iNodeDSLTree just with CommandDSL instances. */ private HashSet<iNodeDSLTree> getJustCCommands(HashSet<iNodeDSLTree> nodes) { HashSet<iNodeDSLTree> filtered = new HashSet<>(); for (iNodeDSLTree node : nodes) { if (node instanceof CommandDSL) { filtered.add(node); } } return filtered; } /** * Return just nodes related with BooleanDSL * * @param nodes a list of iNodeDSLTree * @return a filtered list of iNodeDSLTree just with BooleanDSL instances. */ private HashSet<iNodeDSLTree> getJustBoolean(HashSet<iNodeDSLTree> nodes) { HashSet<iNodeDSLTree> filtered = new HashSet<>(); for (iNodeDSLTree node : nodes) { if (node instanceof BooleanDSL) { filtered.add(node); } } return filtered; } /** * This method modify the commandDSL or BooleanDSL changing just parameters * The focus of this method is to be used as support for sketch features. * * obs.: This method change the DSL passed, be careful to send a clone, if * necessary. * * @param dsl The initial node of the DSL */ public static void neightbourParametersChange(iDSL dsl) { getInstance().modifyTerminalParameters(dsl); } }
9,937
36.220974
111
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/builderDSLTree/NeighbourTypeEnum.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.grammar.dslTree.builderDSLTree; /** * * @author rubens */ public enum NeighbourTypeEnum { NON_LIMITED, LIMITED; }
328
20.933333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/builderDSLTree/localTestsValidation.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.grammar.dslTree.builderDSLTree; import ai.synthesis.grammar.dslTree.CommandDSL; import ai.synthesis.grammar.dslTree.S1DSL; import ai.synthesis.grammar.dslTree.S2DSL; import ai.synthesis.grammar.dslTree.S3DSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashSet; import java.util.HashSet; import java.util.Random; /** * * @author rubens */ public class localTestsValidation { public static void main(String[] args) { BuilderSketchDSLSingleton sketch = BuilderSketchDSLSingleton.getInstance(); BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); Random rand = new Random(); //crio 2 indivíduos, que representam os pais. iDSL ind1 = builder.buildS1Grammar(); iDSL ind2 = builder.buildS1Grammar(); //pego todos os nós HashSet<iNodeDSLTree> nodes1 = builder.getNodesWithoutDuplicity(ind1); HashSet<iNodeDSLTree> nodes2 = builder.getNodesWithoutDuplicity(ind2); //definos pontos de corte (exemplo apenas) int cut_point = Integer.max(2,rand.nextInt(Integer.min(nodes1.size(), nodes2.size()))); iNodeDSLTree node1 = BuilderDSLTreeSingleton.getNodeByNumber(cut_point, (iNodeDSLTree) ind1); iNodeDSLTree node2 = BuilderDSLTreeSingleton.getNodeByNumber(cut_point, (iNodeDSLTree) ind2); //exemplo de uma criação de um novo indivíduo //Considerando que dividimos as arvores em um mesmo ponto de corte, gerando // parte a e parte b, vou juntar parte a do invidíduo 1 e parte b do 2. iDSL partea = (iDSL) node1.getFather().clone(); iDSL parteb = (iDSL) ((iDSL)node2).clone(); //É necessário validar se as partes podem ser combinadas, ou seja // segundo a DSL, é preciso ver se os nós podem ser combinados, já // que não podemos copiar apenas uma parte do if, por exemplo, // e tentar combinar com outra árvore. //Vou fazer algo bem gambiarra aqui, apenas para rodar ;) while(!(partea instanceof iS1ConstraintDSL)){ cut_point = rand.nextInt(Integer.min(nodes1.size(), nodes2.size())); partea = (iDSL) BuilderDSLTreeSingleton.getNodeByNumber(cut_point, (iNodeDSLTree) ind1); } while(!(parteb instanceof S1DSL)){ cut_point = rand.nextInt(Integer.min(nodes1.size(), nodes2.size())); parteb = (iDSL) BuilderDSLTreeSingleton.getNodeByNumber(cut_point, (iNodeDSLTree) ind2); } System.out.println("Fragmento 1: " + partea.friendly_translate()); System.out.println("Fragmento 2: " +parteb.friendly_translate()); System.out.println("Novo filho"); S1DSL sTemp = new S1DSL((iS1ConstraintDSL)partea, (S1DSL) parteb); System.out.println(sTemp.friendly_translate()); //builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) t); //builder.composeNeighbourPassively(t); //System.out.println(t.translate()); //builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) t); // for (int i = 0; i < 100000000; i++) { // builder.changeNeighbourPassively(t); // HashSet<iNodeDSLTree> nodes = builder.getNodesWithoutDuplicity(t); // if(count_by_commands(nodes) > 12){ // System.out.println("Size= " + count_by_commands(nodes) + " " + t.translate()); // System.out.println("Size= " + count_by_commands(nodes) + " " + t.friendly_translate()); // System.out.println("---"); // } // // } /* save configuration saveSerial(t); iDSL tDes = recovery();System.out.println(partea.friendly_translate()); System.out.println("Original ="+ t.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) t); System.out.println("Serializabe System.out.println(partea.friendly_translate());="+tDes.translate()); builder.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) tDes); */ /* Random rand = new Random(); BuilderSketchDSLSingleton sketch = BuSystem.out.println(partea.friendly_translate());ilderSketchDSLSingleton.getInstance(); for (int i = 0; i < 100; i++) { iDSL t1 = sketch.getSketchTypeTwo(); System.out.println(t1.translate()); for (int j = 0; j < 10; j++) { sketch.modifyTerminalParameters(t1);System.out.println(partea.friendly_translate()); System.out.println(" "+t1.translate()); } } */ } private static void saveSerial(iDSL t) { try { FileOutputStream fout = new FileOutputStream("dsl1.ser"); ObjectOutputStream out = new ObjectOutputStream(fout); out.writeObject(t); out.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } private static iDSL recovery() { iDSL dsl = null; try { FileInputStream fIn = new FileInputStream("dsl1.ser"); ObjectInputStream in = new ObjectInputStream(fIn); dsl = (iDSL) in.readObject(); in.close(); fIn.close(); } catch (Exception e) { e.printStackTrace(); } return dsl; } private static int count_by_commands(HashSet<iNodeDSLTree> nodes) { int count = 0; for (iNodeDSLTree node : nodes) { if (node instanceof CommandDSL) { count++; } else if (node instanceof S2DSL) { count++; } else if (node instanceof S3DSL) { count++; } } return count; } private static boolean combine_parts(iDSL partea, iDSL parteb) { iNodeDSLTree n1 = (iNodeDSLTree) partea; try { n1.setFather(parteb); parteb.friendly_translate(); } catch (Exception e) { return false; } return true; } public void oldteste() { BuilderDSLTreeSingleton builder = BuilderDSLTreeSingleton.getInstance(); S1DSL c; c = builder.buildS1Grammar(); System.out.println(c.translate()); /* System.out.println(c.translate()); int totalNodes = BuilderDSLTreeSingleton.getNumberofNodes(c); System.out.println("Qtd Nodes " + totalNodes); builder.formatedStructuredDSLTreePreOrderPrint(c); int nNode = rand.nextInt(totalNodes)+1; System.out.println("Looking for node "+nNode+"....."); iNodeDSLTree targetNode = BuilderDSLTreeSingleton.getNodeByNumber(nNode, c); System.out.println("Fantasy name = "+targetNode.getFantasyName()+" "+ targetNode); iDSL castNode = (iDSL) targetNode; System.out.println(castNode+" "+castNode.translate()); BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint(targetNode); System.out.println("Has S3 as father? "+builder.hasS3asFather(targetNode)); iDSL n = builder.generateNewCommand(castNode, builder.hasS3asFather(targetNode)); castNode = n; System.out.println("\nNew tree"); System.out.println("New comamand"+castNode+" "+castNode.translate()); BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) castNode); //c = (c.getClass().cast(builder.replaceDSLByNeighbour(c, castNode,builder.hasS3asFather(targetNode)))); System.out.println(c.translate()); builder.formatedStructuredDSLTreePreOrderPrint(c); */ for (int i = 0; i < 500; i++) { c = builder.buildS1Grammar(); System.out.println(i + " " + c.translate()); //BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) c); //callAlgorithm(c.translate()); //changing /* int nNode = rand.nextInt(BuilderDSLTreeSingleton.getNumberofNodes(c)) + 1; System.out.println("Node selected " + nNode); iNodeDSLTree targetNode = BuilderDSLTreeSingleton.getNodeByNumber(nNode, c); builder.generateNewCommand((iDSL) targetNode, builder.hasS3asFather(targetNode)); System.out.println(i + " " + c.translate()); nNode = rand.nextInt(BuilderDSLTreeSingleton.getNumberofNodes(c)) + 1; */ for (int j = 0; j < 10; j++) { builder.composeNeighbourPassively(c); System.out.println(i + " " + c.translate()); } /* builder.composeNeighbour(c); System.out.println(i + " " + c.translate()); for (int j = 0; j < 10; j++) { builder.composeNeighbour(c); System.out.println(i + " " + c.translate()); } */ //BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) c); //callAlgorithm(c.translate()); System.out.println("_____________________________________________"); } } }
9,776
40.604255
131
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iBooleanDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iBooleanDSL extends iDSL, iNodeDSLTree{ }
331
21.133333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iCommandDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iCommandDSL extends iDSL{ }
317
20.2
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iDSL.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.grammar.dslTree.interfacesDSL; import java.io.Serializable; /** * * @author rubens */ public interface iDSL extends Serializable{ public String translate(); public String friendly_translate(); public String formmated_translation(); public Object clone(); }
484
23.25
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iEmptyDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iEmptyDSL extends iCommandDSL{ }
322
20.533333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iNodeDSLTree.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.grammar.dslTree.interfacesDSL; import java.io.Serializable; /** * * @author rubens */ public interface iNodeDSLTree extends Serializable{ public iDSL getFather(); public void setFather(iDSL father); public iDSL getRightChild(); public iDSL getLeftChild(); public iNodeDSLTree getRightNode(); public iNodeDSLTree getLeftNode(); public String getFantasyName(); public void removeRightNode(); public void removeLeftNode(); }
673
25.96
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iS1ConstraintDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iS1ConstraintDSL extends iDSL{ }
322
20.533333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iS4ConstraintDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iS4ConstraintDSL extends iDSL{ }
322
20.533333
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/interfacesDSL/iS5ConstraintDSL.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.grammar.dslTree.interfacesDSL; /** * * @author rubens */ public interface iS5ConstraintDSL extends iDSL, iNodeDSLTree{ }
336
21.466667
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/utils/ReduceDSLController.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.grammar.dslTree.utils; import ai.core.AI; import ai.synthesis.dslForScriptGenerator.DSLCommand.AbstractBasicAction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicBoolean.IfFunction; import ai.synthesis.dslForScriptGenerator.DSLCommand.DSLBasicLoops.ForFunction; 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.CDSL; 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.builderDSLTree.BuilderDSLTreeSingleton; import ai.synthesis.grammar.dslTree.interfacesDSL.iCommandDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iEmptyDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iNodeDSLTree; import ai.synthesis.grammar.dslTree.interfacesDSL.iS1ConstraintDSL; import ai.synthesis.grammar.dslTree.interfacesDSL.iS4ConstraintDSL; import java.util.ArrayList; 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.PlayerAction; import rts.units.UnitTypeTable; /** * * @author rubens */ public class ReduceDSLController { static String initialState; private final static int CYCLES_LIMIT = 200; private static final boolean APPLY_RULES_REMOVAL = false; 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, GameState gs) { System.out.println(ai1 + " " + ai2); boolean gameover = false; //JFrame w = PhysicalGameStatePanel.newVisualizer(gs, 640, 640, false, PhysicalGameStatePanel.COLORSCHEME_BLACK); do { try { 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(); } catch (Exception ex) { Logger.getLogger(ReduceDSLController.class.getName()).log(Level.SEVERE, null, ex); } } 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; } public static void removeUnactivatedParts(iDSL dsl, List<ICommand> commands) { if (APPLY_RULES_REMOVAL) { System.out.println("------------------------------------------------------------"); //get all unactivated elements List<iDSL> parts = getUnactivatedParts(commands); //System.out.println(" -- Old DSL " + dsl.translate()); //log -- remove this for (iDSL part : parts) { System.out.println(" -- Part to remove " + part.translate()); } //remove the iDSL fragments from the DSL. //removeParts(parts); for (iDSL part : parts) { List<iDSL> tp = new ArrayList<>(); tp.add(part); removeParts(tp); checkAndRemoveInconsistentIf(dsl); } //check if the DSL continues working. //verifyIntegrity((iNodeDSLTree) dsl); //check for if without then and else. if (dsl.translate().contains("if")) { checkAndRemoveInconsistentIf(dsl); } //BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) dsl); if (dsl.translate().contains("for(u) ()")) { removeInconsistentFor(dsl); } //log -- remove this System.out.println(" -- New DSL " + dsl.translate()); //BuilderDSLTreeSingleton.formatedStructuredDSLTreePreOrderPrint((iNodeDSLTree) dsl); System.out.println("--------------------------------\n"); } } private static List<iDSL> getUnactivatedParts(List<ICommand> commands) { //List<iDSL> tparts = new ArrayList<>(); HashSet<iDSL> tparts = new HashSet<>(); for (ICommand command : commands) { if (command instanceof AbstractBasicAction) { AbstractBasicAction t = (AbstractBasicAction) command; if (!t.isHasDSLUsed()) { tparts.add(t.getDslFragment()); } } else if (command instanceof ForFunction) { ForFunction t = (ForFunction) command; tparts.addAll(getUnactivatedParts(t.getCommandsFor())); } else if (command instanceof IfFunction) { IfFunction t = (IfFunction) command; tparts.addAll(getUnactivatedParts(t.getCommandsThen())); if (!t.getCommandsElse().isEmpty()) { tparts.addAll(getUnactivatedParts(t.getCommandsElse())); } } } return new ArrayList<>(tparts); } private static void removeParts(List<iDSL> parts) { for (iDSL part : parts) { removeFromFather((iNodeDSLTree) part); } } private static void removeFromFather(iNodeDSLTree part) { iNodeDSLTree father = (iNodeDSLTree) part.getFather(); if (father.getRightNode() == part) { father.removeRightNode(); } else if (father.getLeftChild() == part) { father.removeLeftNode(); } //check integrity verifyIntegrity(father); } private static void verifyIntegrity(iNodeDSLTree part) { //if father is a S2DSL check if then exists. If not, check if the S2DSL will //be removed or if the else will replace his parent. if (part instanceof S2DSL) { S2DSL inst = (S2DSL) part; //check if the command will be removed if (inst.getThenCommand() == null && inst.getElseCommand() == null) { removeFromFather(part); } else if (inst.getThenCommand() == null && inst.getElseCommand() != null && !(inst.getElseCommand() instanceof iEmptyDSL)) { //removeS2DSLInFather(inst.getFather(), inst, inst.getElseCommand()); inst.setThenCommand(new CDSL(new EmptyDSL())); } } else if (part instanceof S3DSL) {//if father is a S3DSL and all commands were removed, remove for. S3DSL fInst = (S3DSL) part; if (fInst.getForCommand() == null) { removeS3DSLInFather(fInst.getFather(), fInst); } } else if (part instanceof S4DSL) {//if father is a S4DSL without commands inside, remove it. S4DSL s4 = (S4DSL) part; if (s4.getRightChild() == null && s4.getLeftChild() == null) { removeS4DSLInfather(s4.getFather(), s4); } else if (s4.getRightChild() == null && s4.getLeftChild() instanceof S4DSL) { iDSL grandS4 = s4.getFather(); if (grandS4 instanceof S4DSL) { S4DSL tgrandS4 = (S4DSL) grandS4; if (tgrandS4.getLeftChild() == s4) { tgrandS4.setNextCommand((S4DSL) s4.getLeftChild()); } } else if (grandS4 instanceof S3DSL && s4.getLeftChild() instanceof S4DSL) { S3DSL grandF = (S3DSL) s4.getFather(); grandF.setForCommand((S4DSL) s4.getLeftChild()); } } } else if (part instanceof CDSL) {//if CDSL has null element check if it will be removed ou reorganized. CDSL c = (CDSL) part; //remove if left and right is null if (c.getRightChild() == null && c.getLeftChild() == null) { removeFromFather(part); } else if (c.getRightNode() == null && c.getLeftNode() != null) { //change father by CDSL in left changeActualCDSLByLeftCDSL(c.getFather(), c, c.getLeftChild()); } } else if (part instanceof S1DSL) { S1DSL s1 = (S1DSL) part; if (s1.getCommandS1() == null && s1.getNextCommand() == null) { s1.setCommandS1(new EmptyDSL()); } else if (s1.getCommandS1() == null && s1.getNextCommand() != null && s1.getNextCommand() instanceof iS1ConstraintDSL) { s1.setCommandS1((iS1ConstraintDSL) s1.getNextCommand()); s1.removeLeftNode(); } else if (s1.getCommandS1() == null) { s1.setCommandS1(new EmptyDSL()); } else if (s1.getCommandS1() instanceof iEmptyDSL && s1.getNextCommand() != null && !(s1.getNextCommand().getCommandS1() instanceof EmptyDSL)) { if (s1.getNextCommand().getCommandS1() instanceof iS1ConstraintDSL) { s1.setCommandS1(s1.getNextCommand().getCommandS1()); s1.removeLeftNode(); } else { System.err.println(s1.getNextCommand().translate()); System.err.println(s1.getNextCommand()); } } if (s1.getFather() != null && s1.getFather() instanceof S1DSL) { verifyIntegrity((iNodeDSLTree) s1.getFather()); } } } private static void removeS2DSLInFather(iDSL father, S2DSL ifToRemove, CDSL CommandToReplace) { //by theory the father of a S2DSL is a S1DSL, if we change is in the future, we need to modify this method. if (!(father instanceof S1DSL) && !(father instanceof S4DSL)) { System.err.println("Problem at removeS2DSLInFather."); System.err.println(father.translate()); return; } if (father instanceof S1DSL) { S1DSL part = (S1DSL) father; //it is always true, but I'll keep it for safe. if (part.getCommandS1() == ifToRemove) { part.setCommandS1(CommandToReplace); } else { System.err.println("Problem at removeS2DSLInFather for replace iftoRemove."); } } else if (father instanceof S4DSL) { S4DSL s4f = (S4DSL) father; s4f.setFirstDSL(CommandToReplace); } } private static void removeS3DSLInFather(iDSL father, S3DSL forToRemove) { //by theory the father of a S3DSL is a S1DSL, if we change is in the future, we need to modify this method. if (!(father instanceof S1DSL)) { System.err.println("Problem at removeS3DSLInFather."); System.err.println(father.translate()); return; } S1DSL part = (S1DSL) father; if (part.getCommandS1() == forToRemove) { part.setCommandS1(new EmptyDSL()); } else { System.err.println("Problem at removeS3DSLInFather for replace forToRemove."); } } private static void removeS4DSLInfather(iDSL father, S4DSL s4ToRemove) { if (father instanceof S4DSL) { S4DSL s4Father = (S4DSL) father; if (s4Father.getLeftChild() == s4ToRemove) { s4Father.removeLeftNode(); verifyIntegrity(s4Father); } } else if (father instanceof S3DSL) { S3DSL s3father = (S3DSL) father; if (s3father.getForCommand() == s4ToRemove) { s3father.removeRightNode(); removeS3DSLInFather(s3father.getFather(), s3father); } } } private static void changeActualCDSLByLeftCDSL(iDSL father, CDSL toRemove, iDSL toReplace) { if (father instanceof S1DSL) { S1DSL s1 = (S1DSL) father; if (s1.getRightChild() == toRemove) { s1.setCommandS1((iS1ConstraintDSL) toReplace); } } else if (father instanceof S2DSL) { S2DSL s2 = (S2DSL) father; if (s2.getThenCommand() == toRemove) { s2.setThenCommand((CDSL) toReplace); } else if (s2.getElseCommand() == toRemove) { s2.setElseCommand((CDSL) toReplace); } } else if (father instanceof S4DSL) { S4DSL s4 = (S4DSL) father; if (s4.getFirstDSL() == toRemove) { s4.setFirstDSL((iS4ConstraintDSL) toReplace); } } else if (father instanceof CDSL) { CDSL c = (CDSL) father; if (c.getNextCommand() == toRemove) { c.setNextCommand((CDSL) toReplace); } else if (c.getRealCommand() == toRemove) { if (toReplace instanceof iCommandDSL) { c.setRealCommand((iCommandDSL) toReplace); if (c.getNextCommand() == toReplace) { c.removeLeftNode(); } } else if (toReplace instanceof CDSL) { iDSL grandf = c.getFather(); changeActualCDSLByLeftCDSL(grandf, c, toReplace); } } } } private static void removeInconsistentFor(iDSL dsl) { HashSet<iNodeDSLTree> nodes = BuilderDSLTreeSingleton.getAllNodes((iNodeDSLTree) dsl); for (iNodeDSLTree node : nodes) { if (node instanceof S3DSL) { if (((S3DSL) node).translate().equals("for(u) ()")) { S1DSL father = (S1DSL) ((S3DSL) node).getFather(); if (father.getCommandS1() == node) { father.setCommandS1(new EmptyDSL()); } } } } } private static void checkAndRemoveInconsistentIf(iDSL dsl) { HashSet<iNodeDSLTree> nodes = BuilderDSLTreeSingleton.getAllNodes((iNodeDSLTree) dsl); for (iNodeDSLTree node : nodes) { if (node instanceof S2DSL) { S2DSL s2 = (S2DSL) node; if (s2.getThenCommand() != null && s2.getElseCommand() != null && s2.getThenCommand().translate().equals("") && s2.getElseCommand().translate().equals("")) { iNodeDSLTree father = (iNodeDSLTree) s2.getFather(); if (father.getRightChild() == s2) { father.removeRightNode(); } else if (father.getLeftNode() == s2) { father.removeLeftNode(); } verifyIntegrity(father); } else if (s2.getThenCommand() != null && s2.getThenCommand().translate().equals("") && s2.getElseCommand() == null) { iNodeDSLTree father = (iNodeDSLTree) s2.getFather(); if (father.getRightChild() == s2) { father.removeRightNode(); } else if (father.getLeftNode() == s2) { father.removeLeftNode(); } verifyIntegrity(father); } else if (s2.getThenCommand() != null && s2.getThenCommand().translate().equals("") && s2.getElseCommand() != null && !(s2.getElseCommand().translate().equals(""))) { s2.setThenCommand(s2.getElseCommand()); s2.removeLeftNode(); } } } } }
17,557
43.450633
123
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/dslTree/utils/SerializableController.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.grammar.dslTree.utils; import ai.synthesis.grammar.dslTree.interfacesDSL.iDSL; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * * @author rubens */ public class SerializableController { public static void saveSerializable(iDSL t, String fileName, String path) { try { FileOutputStream fout = new FileOutputStream(path+fileName, false); ObjectOutputStream out = new ObjectOutputStream(fout); out.writeObject(t); out.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } public static iDSL recoverySerializable(String fileName, String path) { iDSL dsl = null; try { FileInputStream fIn = new FileInputStream(path+fileName); ObjectInputStream in = new ObjectInputStream(fIn); dsl = (iDSL) in.readObject(); in.close(); fIn.close(); } catch (Exception e) { e.printStackTrace(); } return dsl; } }
1,337
28.086957
79
java
MicroRTS
MicroRTS-master/src/ai/synthesis/grammar/model/ProgramScript.java
package ai.synthesis.grammar.model; import java.io.PrintWriter; import java.util.ArrayList; /** * * @author rubens julian */ public class ProgramScript { private ArrayList<Integer> Genes; public ProgramScript() { this.Genes = new ArrayList<>(); } public ArrayList<Integer> getGenes() { return Genes; } public void setGenes(ArrayList<Integer> genes) { Genes = genes; } public void addGene(Integer gene){ this.Genes.add(gene); } public String print(){ String crom=""; crom = Genes.stream().map((gene) -> " "+gene).reduce(crom, String::concat); //System.out.print(gene+" "); return crom; } public void print(PrintWriter f0){ System.out.print("Chromosome "); f0.print("Chromosome "); for (Integer gene : Genes) { System.out.print(gene+" "); f0.print(gene+" "); } System.out.println(""); f0.println(""); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((Genes == null) ? 0 : Genes.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProgramScript other = (ProgramScript) obj; if (Genes == null) { if (other.Genes != null) return false; } else if (!Genes.equals(other.Genes)) return false; return true; } }
1,449
17.589744
92
java