コード例 #1
0
        // Serialize the game state into a JSON format.
        public static void SerializeGameState(GameState gs, BasePacman pController)
        {
            // Doesn't seem like a neater way of doing this unfortunately :/
            GameStateSerialize _serializeObject = new GameStateSerialize()
            {
                PacmanX = gs.Pacman.Node.X,
                PacmanY = gs.Pacman.Node.Y,

                BlueX = gs.Blue.Node.X,
                BlueY = gs.Blue.Node.Y,

                PinkX = gs.Pink.Node.X,
                PinkY = gs.Pink.Node.Y,

                BrownX = gs.Brown.Node.X,
                BrownY = gs.Brown.Node.Y,

                RedX = gs.Red.Node.X,
                RedY = gs.Red.Node.Y,

                RedEntered   = gs.Red.Entered,
                BlueEntered  = gs.Blue.Entered,
                BrownEntered = gs.Brown.Entered,
                PinkEntered  = gs.Pink.Entered,

                PinkFleeing  = gs.Pink.Fleeing,
                BrownFleeing = gs.Brown.Fleeing,
                BlueFleeing  = gs.Blue.Fleeing,
                RedFleeing   = gs.Red.Fleeing,

                LevelsCleared = gs.Level,

                LivesLeft     = gs.Pacman.Lives,
                Timer         = (int)gs.Timer,
                Score         = gs.Pacman.Score,
                TimeCaptured  = DateTime.Now,
                GameOverCount = gs.m_GameOverCount
            };

            // Return the string output from serializing our object.
            string _output = JsonConvert.SerializeObject(_serializeObject, Formatting.Indented);
            //string _outputTwo = JsonConvert.SerializeObject(gs, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Error });

            // Output the JSON serialization to the text file.
            StreamWriter _writer = new StreamWriter(string.Format("{3}\\gamestate_{0}_{1}_{2}.txt",
                                                                  pController.Name.ToString(),
                                                                  DateTime.Now.ToString("hhmmddss"),
                                                                  pController._testStats.TotalGames.ToString(),
                                                                  pController._testLogFolder.FullName.ToString()), false);

            _writer.WriteLine(_output);

            _writer.Flush();
            _writer.Close();
        }
コード例 #2
0
        public GameRunnerResults RunGames(int gamesToPlay, BasePacman controller, int RandomSeed = 0, List <double> gameParameters = null)
        {
            grr = new GameRunnerResults();

            gs = gameParameters == null ? new GameState(RandomSeed) : new GameState(gameParameters, RandomSeed);

            gs.GameOver += new EventHandler(GameOverHandler);
            gs.StartPlay();

            // Turn off the logging
            if (controller.GetType() == typeof(LucPac))
            {
                LucPac.REMAIN_QUIET = true;
            }

            if (controller.GetType() == typeof(LucPacScripted))
            {
                LucPacScripted.REMAIN_QUIET = true;
            }

            gs.Controller = controller;

            Stopwatch watch      = new Stopwatch();
            int       percentage = -1;
            int       lastUpdate = 0;

            watch.Start();
            while (grr.gamesPlayed < gamesToPlay)
            {
                int newPercentage = (int)Math.Floor(((float)grr.gamesPlayed / gamesToPlay) * 100);
                if (newPercentage != percentage || grr.gamesPlayed - lastUpdate >= 100)
                {
                    lastUpdate = grr.gamesPlayed;
                    percentage = newPercentage;
                }
                // update gamestate
                Direction direction = controller.Think(gs);
                gs.Pacman.SetDirection(direction);

                // update game
                gs.Update();
            }
            watch.Stop();

            // shut down controller
            controller.SimulationFinished();

            return(grr);
        }
コード例 #3
0
        /// <summary>
        /// Attempt to load in the controller that we want to use
        /// </summary>
        /// <param name="name">The type name of the controller in question</param>
        private static void tryLoadController(string name)
        {
            byte[]   assemblyBytes    = LoadBytes(Path.Combine(PacmanAIDir, "PacmanAI.dll"));
            byte[]   assemblyPdbBytes = LoadBytes(Path.Combine(PacmanAIDir, "PacmanAI.pdb"));
            Assembly assembly         = Assembly.Load(assemblyBytes, assemblyPdbBytes);

            Type[] _types = assembly.GetTypes();
            foreach (Type type in assembly.GetTypes())
            {
                if (type.BaseType == typeof(BasePacman))
                {
                    BasePacman pacman = (BasePacman)Activator.CreateInstance(type);
                    if (pacman.Name == name)
                    {
                        controller    = pacman;
                        gs.Controller = pacman;
                        return;
                    }
                }
            }
        }
コード例 #4
0
        public static GameState SimulateGame(GameState pGameState, BasePacman pController, int pSteps)
        {
            int       _currentlevel    = pGameState.Level;
            int       _gameoverCount   = pGameState.m_GameOverCount;
            GameState _gameStateCloned = pGameState; // (GameState) pGameState.Clone();

            // Set the random controller to the game state that we are focusing on
            _gameStateCloned.Controller = pController;

            // Loop through the maximum amount of steps and then perform the
            // simulation on the game state
            while (pSteps-- > 0 &&
                   _gameStateCloned.Level == _currentlevel &&
                   _gameoverCount == _gameStateCloned.m_GameOverCount)
            {
                _gameStateCloned.UpdateSimulated();
            }

            // SaveStateAsImage(_gameStateCloned, LucPac.INSTANCE, "_simulatedgame");

            return(_gameStateCloned);
        }
コード例 #5
0
        public static void RunGameLinear(GameData CustomData)
        {
            Reset();
            try
            {
                // Set the new count of games that we want to simulate.
                gamesToPlay = CustomData.GamesToPlay;


                // Get some strange invocation error here.
                // tryLoadController(_agentName);

                BasePacman controller = null;

                if (CustomData.EvolvedValues.Count < 25 && CustomData.EvolvedValues.Count > 0)
                {
                    gs = new GameState(CustomData.EvolvedValues, CustomData.RandomSeed);
                }
                else
                {
                    gs = new GameState(CustomData.RandomSeed);
                }

                //BasePacman controller = new TestPac();

                controller = GetNewController(CustomData);

                /*if(CustomData.AIToUse.Equals("LucPacScripted"))
                 * {
                 *  controller = new LucPacScripted();
                 *  LucPacScripted.REMAIN_QUIET = true;
                 * }
                 * if (CustomData.AIToUse.Equals("MMPac"))
                 * {
                 *  //use CustomData.NeuralNetwork in constructor
                 *  controller = new MMPac.MMPac(CustomData.MapData.EvolvedValues);
                 * }
                 * if (CustomData.AIToUse.Equals("MMLocPac"))
                 * {
                 *  //use CustomData.NeuralNetwork in constructor
                 *  if (CustomData.MapData.EvolvedValues.Count < 25)
                 *      controller = new MMPac.MMLocPac("NeuralNetworkLocPac.nn");
                 *  else
                 *      controller = new MMPac.MMLocPac(CustomData.MapData.EvolvedValues);
                 * }
                 * if(CustomData.AIToUse.Equals("LucPac"))
                 * {
                 *  controller = new LucPac();
                 *  LucPac.REMAIN_QUIET = true;
                 * }*/


                gs.GameOver += new EventHandler(GameOverHandler);
                gs.StartPlay();

                gs.Controller = controller;

                Stopwatch watch           = new Stopwatch();
                int       percentage      = -1;
                int       lastUpdate      = 0;
                int       lastGamesPlayed = 0;
                watch.Start();
                while (gamesPlayed < gamesToPlay)
                {
                    int newPercentage = (int)Math.Floor(((float)gamesPlayed / gamesToPlay) * 100);
                    if (newPercentage != percentage || gamesPlayed - lastUpdate >= 100)
                    {
                        lastUpdate = gamesPlayed;
                        percentage = newPercentage;
                        Console.Clear();

                        /*Console.Write("Current parameter set: ");
                         * foreach(var X in CustomData.MapData.EvolvedValues)
                         * {
                         *  Console.Write(X + ", ");
                         * }*/
                        Console.WriteLine();
                        Console.WriteLine("Simulating ... " + percentage + "% (" + gamesPlayed + " : " + gamesToPlay + ")");
                        //Console.WriteLine(" - Elapsed: " + formatSeconds((watch.ElapsedMilliseconds / 1000.0) + "") + "s, Estimated total: " + formatSeconds(((watch.ElapsedMilliseconds / 1000.0) / percentage * 100) + "") + "s");
                        Console.WriteLine(" - Current best: " + highestScore);
                        Console.WriteLine(" - Current worst: " + lowestScore);
                        if (gamesPlayed > 0)
                        {
                            Console.WriteLine(" - Current avg.: " + (totalScore / gamesPlayed));
                        }

                        /*for (int i = scores.Count - 1; i >= 0 && i > scores.Count - 100; i--)
                         * {
                         *  Console.Write(scores[i] + ",");
                         * }*/
                    }
                    // update gamestate
                    Direction direction = controller.Think(gs);
                    gs.Pacman.SetDirection(direction);

                    // update game
                    gs.Update();
                    ms += GameState.MSPF;

                    if (lastGamesPlayed != gamesPlayed)
                    {
                        //Game finished, recreate controller
                        controller    = GetNewController(CustomData);
                        gs.Controller = controller;

                        lastGamesPlayed = gamesPlayed;
                    }
                    else
                    {
                        if (ms - lastMs > 3600000)
                        {
                            gs.InvokeGameOver();
                        }
                    }
                }
                watch.Stop();

                // shut down controller
                controller.SimulationFinished();

                JArray o            = JArray.FromObject(Scores);
                JArray JGameLengths = JArray.FromObject(GameLengths);
                JArray JPowerPills  = JArray.FromObject(PowerPillsEaten);

                JArray JPills  = JArray.FromObject(PillsEaten);
                JArray JGhosts = JArray.FromObject(GhostsEaten);

                Dictionary <string, object> collection = new Dictionary <string, object>()
                {
                    { "Scores", o },
                    { "Lengths", JGameLengths },
                    { "PowerPills", JPowerPills },
                    { "Pills", JPills },
                    { "Ghosts", JGhosts }
                };

                JObject Result = new JObject(
                    new JProperty("metrics",
                                  JObject.FromObject(collection)
                                  )
                    );

                Results = Result.ToString();

                // output results
                Console.Clear();
                long seconds = ms / 1000;
                Console.WriteLine("Games played: " + gamesPlayed);
                Console.WriteLine("Avg. score: " + (totalScore / gamesPlayed));
                Console.WriteLine("Highest score: " + highestScore + " points");
                Console.WriteLine("Lowest score: " + lowestScore + " points");
                Console.WriteLine("Max Pills Eaten: " + maxPillsEaten);
                Console.WriteLine("Min Pills Eaten: " + minPillsEaten);
                Console.WriteLine("Average Pills Eaten: " + pillsEatenTotal / gamesPlayed);
                Console.WriteLine("Max Ghosts Eaten: " + maxGhostsEaten);
                Console.WriteLine("Min Ghosts Eaten: " + minGhostsEaten);
                Console.WriteLine("Average Ghosts Eaten: " + totalGhostsEaten / gamesPlayed);
                Console.WriteLine("Longest game: " + ((float)longestGame / 1000.0f) + " seconds");
                Console.WriteLine("Total simulated time: " + (seconds / 60 / 60 / 24) + "d " + ((seconds / 60 / 60) % 24) + "h " + ((seconds / 60) % 60) + "m " + (seconds % 60) + "s");
                Console.WriteLine("Avg. simulated time pr. game: " + ((float)ms / 1000.0f / gamesPlayed) + " seconds");
                Console.WriteLine("Simulation took: " + (watch.ElapsedMilliseconds / 1000.0f) + " seconds");
                //Console.WriteLine("Speed: " + (ms / watch.ElapsedMilliseconds) + " (" + ((ms / watch.ElapsedMilliseconds) / 60) + "m " + ((ms / watch.ElapsedMilliseconds) % 60) + " s) simulated seconds pr. second");
                Console.WriteLine("For a total of: " + gamesPlayed / (watch.ElapsedMilliseconds / 1000.0f) + " games pr. second");
            }
            catch (Exception e)
            {
                // Log error.
                Console.WriteLine("Error happened. " + e.Message);
            }
            //return Results;
        }
コード例 #6
0
        private unsafe void aiRunner()
        {
            // init game state
            gs = new GameState();
            gs.AutomaticLevelChange = false;
            gs.Replay = true;
            gs.StartPlay();
            if (v != null)
            {
                v.SetGameState(gs);
            }
            if (selectedAI != null && selectedAI.Type != null)
            {
                controller = (BasePacman)selectedAI.Type.GetConstructor(new Type[] { }).Invoke(new object[] { });
            }
            else
            {
                controller = null;
            }
            initializePosInfos();
            scores = new List <int>();
            // load resources
            System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream           file    = thisExe.GetManifestResourceStream("MsPacmanController.Resources.screenplayer.png");
            sprites = (Bitmap)Bitmap.FromStream(file);
            unsafe {
                spritesRgbWidth  = sprites.Width;
                spritesRgbHeight = sprites.Height;
                BitmapData spritesBitmapData = sprites.LockBits(new Rectangle(0, 0, sprites.Width, sprites.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
                IntPtr     spritesPtr        = spritesBitmapData.Scan0;
                spritesRgbValues = new int[sprites.Width * sprites.Height];
                Marshal.Copy(spritesPtr, spritesRgbValues, 0, sprites.Width * sprites.Height);
                sprites.UnlockBits(spritesBitmapData);
                for (int i = 0; i < spritesRgbValues.Length; i++)
                {
                    spritesRgbValues[i] = (int)(((uint)spritesRgbValues[i]) - 0xFF000000);
                }
            }
            // init for scoreshot
            scoreShot  = new Bitmap(48, 7);
            scoreGfx   = Graphics.FromImage((Image)scoreShot);
            spriteSums = new int[10];
            for (int i = 0; i < 10; i++)
            {
                int sum = 0;
                for (int y = 0; y < 7; y++)
                {
                    sum += (getSpriteColor(6 + i * 8, 98 + y) << y);
                }
                spriteSums[i] = sum;
                //Console.WriteLine(i + " = " + sum);
            }
            //
            runningPacman = true;
            while (true)
            {
                watch.Start();

                // get window info
                WINDOWINFO info = Comm.GetWindowInfoEasy(msPacmanProcess.MainWindowHandle);
                if (info.dwWindowStatus == 0)
                {
                    break;
                }

                // capture frame
                bitmap = (Bitmap)NativeMethods.GetDesktopBitmap(info.rcClient.Left, info.rcClient.Top, width, height, bitmap);
                unsafe {
                    BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
                    IntPtr     ptr        = bitmapData.Scan0;

                    Marshal.Copy(ptr, colorValues, 0, size);

                    // before we eliminate the maze :)
                    currentMaze = findMaze();

                    // subtract red maze
                    switch (currentMaze)
                    {
                    case Maze.Red: subtractMaze(mazeRedEmpty); break;

                    case Maze.LightBlue: subtractMaze(mazeLightblueEmpty); break;

                    case Maze.Brown: subtractMaze(mazeBrownEmpty); break;

                    case Maze.DarkBlue: throw new ApplicationException("DarkBlue maze not implemented (do it yourself you lazy f**k ;) )");

                    default: subtractMaze(mazeRedEmpty); break;                             // to eliminate alpha values
                    }

                    // Copy the RGB values back to the bitmap
                    //Marshal.Copy(colorValues, 0, ptr, size);

                    bitmap.UnlockBits(bitmapData);
                    NativeMethods.DeleteObject(ptr);
                }

                // remove alpha

                /*for( int i = 0; i < colorValues.Length; i++ ) {
                 *      colorValues[i] = (int)(((uint)colorValues[i]) - 0xFF000000);
                 * }*/

                // update framerate
                if (runningAvg.Count > 8)
                {
                    runningAvg.Dequeue();
                }
                if (runningAvg.Count != 0)
                {
                    msPerFrame = 0;
                    foreach (long ms in runningAvg)
                    {
                        msPerFrame += (int)ms;
                    }
                    msPerFrame /= runningAvg.Count;
                }

                // find scores
                int newScore = findScore();
                if (newScore % 10 != 0)
                {
                    newScore = -1;
                }
                if (newScore < score)
                {
                    scoreToAddToAvg = score;
                    if (score > (int)settings["Highscore"])
                    {
                        settings["Highscore"] = score;
                        settings.Save();
                    }
                }
                if (scoreToAddToAvg != -1 && score < 400 && score > 0)
                {
                    scores.Add(scoreToAddToAvg);
                    if (controller != null)
                    {
                        using (StreamWriter sw = new StreamWriter(File.Open("scores.txt", FileMode.Append))) {
                            sw.WriteLine(controller.Name + "\t\t" + scoreToAddToAvg);
                        }
                    }
                    scoreToAddToAvg = -1;
                }
                score = newScore;
                if (score != -1)
                {
                    determineState();
                    if (currentState == State.StartScreen)
                    {
                        GC.Collect();
                        Comm.AddCredit();
                        Comm.StartGame();
                    }
                    // play
                    play();
                    // update entered/not entered
                    foreach (Ghost ghost in gs.Ghosts)
                    {
                        if (ghost.Node.X >= 10 && ghost.Node.X <= 17 &&
                            ghost.Node.Y >= 12 && ghost.Node.Y <= 16)
                        {
                            ghost.SetEntered(false);
                        }
                        else if (!ghost.Node.Walkable)
                        {
                            ghost.SetEntered(false);
                        }
                        else
                        {
                            ghost.SetEntered(true);
                        }
                    }
                    if (controller != null)
                    {
                        // control
                        direction = controller.Think(gs);
                        //Console.WriteLine(direction);
                        if (direction == Direction.Stall)
                        {
                            if (stall == Direction.None)
                            {
                                direction = gs.Pacman.InverseDirection(gs.Pacman.Direction);
                                stall     = direction;
                            }
                            else
                            {
                                direction = gs.Pacman.InverseDirection(stall);
                                stall     = direction;
                            }
                        }
                        else
                        {
                            stall = Direction.None;
                        }
                        Comm.SendKey(direction);
                    }
                }
                else
                {
                    GC.Collect();
                    currentState = State.BetweenLevels;
                }

                // update status
                this.BeginInvoke(updateMethod);
                watch.Stop();
                // update running avg
                runningAvg.Enqueue(watch.ElapsedMilliseconds);
                // reset
                watch.Reset();
                Thread.Sleep(30);
            }
            runningPacman = false;
            this.BeginInvoke(updateMethod);
        }