Exemplo n.º 1
0
        private void CreateFiles(int generation, int individual, Individual genes)
        {
            // assign robot name
            var robotId = RobotFileCreator.GetRobotId(generation, individual);

            // create dir path and directory
            var robotDirectoryPath = Path.Combine(_directoryPath, robotId);

            Directory.CreateDirectory(robotDirectoryPath);

            var dirPathFull = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName),
                                           robotDirectoryPath);

            var dllFileCreator    = new DllFileCreator();
            var battleFileCreator = new BattleFileCreator();
            var robotFileCreator  = new RobotFileCreator();
            var stateCreator      = new RobotStateFileCreator();

            var dnaTranslator = new DnaToCode(genes);                   //In later iteration, replace with Factory

            // create files, compile robot
            robotFileCreator.CreateRobotFiles(robotDirectoryPath, robotId, dnaTranslator);
            stateCreator.CreateStateFiles(robotDirectoryPath, robotId, dnaTranslator);
            dllFileCreator.CreateDll(_dllDirectoryPath, robotDirectoryPath, robotId, dnaTranslator);
            battleFileCreator.CreateBattleFiles(robotDirectoryPath, NameSpace, robotId);

            // run battles
            RoboCodeMatchHandler.RunBattles(dirPathFull);
        }
        internal void CreateRobotFiles(string filePath, string robotId, DnaToCode dnaTranslator)
        {
            //Create Robot_gX_iY.cs
            FileCreator.CreateFile(
                filePath,
                $"{robotId}{FileCreator.CodeFileExtension}",
                GetFileText(robotId, filePath, dnaTranslator),
//				GetBotZero(robotId),
                true
                );
        }
        } = new Random();                                             // for random colors

        internal void CreateStateFiles(string filePath, string robotId, DnaToCode dnaTranslator)
        {
            for (var i = 0; i <= 1; i++)
            {
                FileCreator.CreateFile(
                    filePath,
                    $"{robotId}_State{i}{FileCreator.CodeFileExtension}",
                    GetFileText(i, robotId, dnaTranslator),
                    true
                    );
            }
        }
        private static string GetFileText(int stateNumber, string robotId, DnaToCode dnaTranslator)
        {
            return($@"using System;
using System.Drawing;
using Alvtor_Hartho_15.FSM;
namespace {FileCreator.NameSpace}
{{
	public class State{stateNumber} : State
	{{
		public {robotId} OurRobot {{ get; set; }}
		public State{stateNumber} ({robotId} ourRobot) : base (ourRobot)
		{{
			OurRobot = ourRobot;
		}}

		public override State StateChangeRelevance()
		{{
			if ({(stateNumber == 0 ? dnaTranslator.GetFirstToSecondStateTransitionContent() : dnaTranslator.GetSecondToFirstStateTransitionContent())})
				return new State{(stateNumber == 0 ? stateNumber+1 : stateNumber-1)} (OurRobot);

			return this;
		}}

		public override void EnterState()
		{{
			OurRobot.BodyColor = Color.{(stateNumber == 0 ? "Green" : "Red")};
//			OurRobot.BodyColor = Color.FromArgb({Random.Next(256)}, {Random.Next(256)}, {Random.Next(256)});
			{(stateNumber == 0 ? dnaTranslator.GetFirstStateEnterMethodContent() : dnaTranslator.GetSecondStateEnterMethodContent())}
		}}

		public override void DoStateAction()
		{{
			{(stateNumber == 0 ? dnaTranslator.GetFirstStateDoStateActionMethodContent() : dnaTranslator.GetSecondStateDoStateActionMethodContent())}
		}}

		public override void ExitState()
		{{
			{(stateNumber == 0 ? dnaTranslator.GetFirstStateLeaveMethodContent() : dnaTranslator.GetSecondStateLeaveMethodContent())}
		}}
	}}
}}");
        }
        internal string GetFileText(string robotId, string filePath, DnaToCode dnaTranslator)
        {
            var imports = $"using System;" +
                          "\nusing System.Drawing;" +
                          "\nusing System.Collections.Generic;" +
                          "\nusing Robocode;" +
                          "\nusing Santom;" +
                          "\nusing Alvtor_Hartho_15.FSM;" +
                          "\nusing ExampleSetup.Robocode;" +
                          "\n";

            var classInfo = $"\nnamespace {FileCreator.NameSpace} {{    //GARICS: Genetic Algorithm Robot in C Sharp" +
                            "\npublic class " + robotId + " : Alvtor_Hartho_15.Garics {";

            var fields = "\n" + dnaTranslator.GetVariableDeclarations();

            var runMethod = "\n\t\tpublic override void Run() {" +
                            "\n\t\t\tTargetedEnemy = new EnemyData();" +
                            "\n\t\t\tIsAdjustRadarForGunTurn = true;" +
                            "\n\t\t\tIsAdjustGunForRobotTurn = true;" +
                            "\n\t\t\tEnemyDataDictionary = new Dictionary<string, EnemyData>();" +
                            "\n\t\t\tStateManager = new StateManagerScript(new State0(this));" +
                            "\n" + dnaTranslator.GetVariableInitialisations() +
                            "\n" +
                            "\n\t\t\twhile (true) {" +
                            "\n\t\t\t\tStateManager.FrameCheck();" +
                            "\n\t\t\t\tScan();" +
                            "\n\t\t\t\tOldEnemy = TargetedEnemy;" +
                            "\n\t\t\t}" +
                            "\n\t\t}" +
                            "\n";

            const string methods = "\n\t\tpublic override void OnScannedRobot(ScannedRobotEvent e) {" +
                                   "\n\t\t\tUpdateEnemyData(e);" +
                                   "\n\t\t}";

            const string end = "\n\t}" +
                               "\n}";

            return(imports + /*GetRobotAssemblyInfo() +*/ classInfo + fields + runMethod + methods + end);
        }
Exemplo n.º 6
0
        internal void CreateDll(string dllDirPath, string robotDirPath, string robotId, DnaToCode dnaTranslator, int numberOfStates = 2)
        {
            var          robotPath   = Path.Combine(robotDirPath, robotId); // the path to the robot, including dirs
            var          dllPath     = Path.Combine(dllDirPath, $"Alvtor_Hartho_15-{robotId}.dll");
            const string helpersPath = @"../../../Helpers/Robot/";
            var          files       = new string[17]; // initialise array to hold all states and robot

            files[0] = $"{robotPath}.{FileExtension}"; //add robot to the array


            for (var i = 0; i < numberOfStates; i++)     // add states to the array
            {
                files[i + 1] = $"{robotPath}_state{i}.{FileExtension}";
            }

            string[] dependencies =
            {
                "Helpers/EnemyDataHelpers",
                "FSM/StateManagerScript",
                "FSM/State",
                "Garics/Garics",
                "Helpers/Battlefield",
                "Helpers/Direction",
                "Helpers/EnemyData",
                "Helpers/Point2D",
                "Helpers/Point2DHelpers",
                "Helpers/Vector2D",
                "Helpers/Vector2DHelpers",
                "Helpers/UtilsVector",
                "Helpers/RobotVectors",
                "Helpers/MathHelpers"
            };

            for (var i = 0; i < dependencies.Length; i++)
            {
                files[i + 3] = $"{helpersPath}{dependencies[i]}.{FileExtension}";
            }

            var parameters = new CompilerParameters
            {
                GenerateInMemory        = false,       // save assembly as physical file
                IncludeDebugInformation = true,        // generate debug info
                TreatWarningsAsErrors   = true,        // treat warnings as errors
                CompilerOptions         = "/optimize", //optimize output
//			    MainClass = robotId, // Specify the class that contains the Main method of the executable. Probably useless with dlls
                OutputAssembly       = dllPath,
                GenerateExecutable   = false,           //create .dll, not .exe
                ReferencedAssemblies =
                {
                    "mscorlib.dll",
                    "System.Core.dll",
                    "Robocode.dll",
                    "System.dll",
                    "System.net.dll",                 // For helpers
//				    "Helpers.dll",
//				    "System.Collections.Generic.dll",
                    "System.Drawing.dll",
                }
            };

            // create provider and generate results
            var codeProvider = new CSharpCodeProvider(new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }, { "AssemblyVersion", "4.5.2.6" }, { "AssemblyTitle", "GARICS" }
            });                                                                                                                                                                                    // NOTE: removed constructor parameter: new Dictionary<string, string> {{"CompilerVersion", "v4.0"}}


            Process currentProcess = Process.GetCurrentProcess();
            string  folder         = Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), helpersPath);
            string  filter         = "*.cs";

            string[] filez0 = { $"{robotPath}.{FileExtension}", $"{robotPath}_state0.{FileExtension}", $"{robotPath}_state1.{FileExtension}" };
            string[] filez1 = Directory.GetFiles(Path.Combine(folder, "Helpers"), filter);
            string[] filez2 = Directory.GetFiles(Path.Combine(folder, "FSM"), filter);
            string[] filez3 = Directory.GetFiles(Path.Combine(folder, "Garics"), filter);
            string[] filez  = filez0.Concat(filez1.Concat(filez2.Concat(filez3))).ToArray();       //Should rename from filez to something more appropriate

//	        var results = codeProvider.CompileAssemblyFromFile(parameters, files);
            var results = codeProvider.CompileAssemblyFromFile(parameters, filez);


            results.Errors.Cast <CompilerError>().ToList().ForEach(error =>
                                                                   Console.WriteLine($"Error: {error.FileName}: {error.ErrorText} ({error.Line}, {error.Column})")); // log errors in console

            // try loading the assembly
            try
            {
//			    Assembly.LoadFrom("./Helpers.dll");
//			    Assembly.LoadFrom($"{dllDirPath}/Alvtor_Hartho_15-{robotId}.dll");

                Assembly.LoadFrom(dllPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Caught exception: {ex.Message}");
                var typeLoadException = ex as ReflectionTypeLoadException;
                var loaderExceptions  = typeLoadException?.LoaderExceptions;
                if (loaderExceptions != null)
                {
                    Console.WriteLine(loaderExceptions);
                }
            }
        }