Esempio n. 1
0
    // Start is called before the first frame update
    void Start()
    {
        #if UNITY_EDITOR || DEVELOPMENT_BUILD
        if (Instance == null)
        {
            // Sets instance settings
            Instance = this;
            DontDestroyOnLoad(gameObject);
            DebugEnabled = false;

            // Gets the references
            debugCanvas   = GetComponentInChildren <Canvas>().gameObject;               //gets first canvas (debug canvas)
            debugPanel    = debugCanvas.GetComponentInChildren <Image>().gameObject;    // gets first image (debug panel)
            debugModeText = debugCanvas.GetComponentInChildren <TMP_Text>().gameObject; // gets first text (debug mode text)

            // Sets Debug UI to false
            debugPanel.SetActive(false);
            debugModeText.SetActive(false);
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
        #else
        // Destroys debug manager and children if not in UNITY_EDITOR or DEVELOPMENT_BUILD
        Destroy(gameObject);
        #endif
    }
Esempio n. 2
0
    public void OnLoadComplete(AssetRequest assetRequest)
    {
        isLoadDone = true;
        GameObject asset = assetRequest.asset as GameObject;

        gameObject           = GameObject.Instantiate <GameObject>(asset);
        transform            = gameObject.transform;
        m_PositionController = gameObject.AddComponent <PositionController>();
        // 绘制可视区域
        m_DrawTool = gameObject.AddComponent <DebugController>();
        m_DrawTool.DrawViewArea(battleEntity.GetViewRange());     //可见范围
        m_DrawTool.DrawAttackArea(battleEntity.GetAttackRange()); //攻击范围

        m_AnimController      = gameObject.AddComponent <AnimationController>();
        m_HeroStateController = new HeroStateController(battleEntity, m_AnimController);

        InitPosition(Vector3.zero);

        if (m_LoadedCallback != null)
        {
            m_LoadedCallback(gameObject);
        }

        // todo 找一个区分玩家与友军的标记
        if (camp == BattleCamp.FRIENDLY)
        {
            GameMsg.instance.SendMessage(GameMsgDef.PlayerActor_Created, this, camp == BattleCamp.ENEMY);
        }

        gameObject.name = string.Format("[{0}][{1}][UID:{2}][CID:{3}][Lv:{4}][Speed:{5}]",
                                        battleEntity.GetName(), camp.ToString(), battleEntity.GetUniqueID(), battleEntity.GetID(), battleEntity.GetLevel(), battleEntity.GetMoveSpeed());
        GameMsg.instance.SendMessage(GameMsgDef.BattleActor_Created, this, camp == BattleCamp.ENEMY);
    }
Esempio n. 3
0
 //Funciones
 private string OnTriggerEnter2D(Collider2D collision)
 {
     if (collision.CompareTag("CrossWalkQuestion"))
     {
         DebugController.LogMessage("COLISION CON CROSSWALK");
         correctAnswer = collision.GetComponent <CrosswalkTrigger>().GetCrosswalk.GetCrossWalkType.ToString(); // GetComponent<Crosswalk>().GetCrossWalkType.ToString();
         //Cada que entra a una señal, actia el canvas que le permite decidir si la quiere identificar o no//
         //Tambien defne la repuesta correcta como el nobre del cruce en el que acaba de entrar//
         if (correctAnswer == "Cebra" && canAnswer == true)
         {
             return(null);
         }
         if (correctAnswer == "Bocacalle" && canAnswer == true)
         {
             return(null);
         }
         else
         {
             return(null);
         }
     }
     else
     {
         return(null);
     }
 }
Esempio n. 4
0
    private void Awake()
    {
        _instance = this;

        _playerControls = new PlayerControls();

        _playerControls.Player.ToggleDebug.performed += context => OnToggleDebug();

        _playerControls.Player.ReturnDebug.performed += context => OnReturn();

        RESTART_LEVEL = new DebugCommand("restart_lvl", "Restarts the current level", "restart_lvl", () =>
        {
            var currentLevel = SceneManager.GetActiveScene();

            SceneManager.LoadScene(currentLevel.name);
        });

        SHOW_HELP = new DebugCommand("help", "Shows all commands", "help", () =>
        {
            showHelp = true;
        });

        commandList = new List <object>
        {
            RESTART_LEVEL,
            SHOW_HELP
        };
    }
Esempio n. 5
0
 /// <summary>
 /// Called when a entity started crossing the crosswalk.
 /// </summary>
 /// <param name="_entity">Entity that started crossing.</param>
 public void OnStartedCrossing(EntityController _entity)
 {
     //DebugController.LogMessage($"Entity started crossing {  _entity.gameObject.name }");
     ClearTicket(_entity);
     SetTurnForCrossingEntity(_entity.GetEntityType);
     if (_entity.GetEntityType.Equals(EntityType.Pedestrian))
     {
         if (!crossingPedestrians.ContainsKey(_entity))
         {
             _entity.GetMovableComponent.AddOnMovement(OnEntityMoved);
             CrossingInfo newInfo = new CrossingInfo();
             newInfo.lastPosition = _entity.transform.position;
             crossingPedestrians.Add(_entity, newInfo);
         }
     }
     else if (_entity.GetEntityType.Equals(EntityType.Vehicle))
     {
         if (!crossingVehicle.ContainsKey(_entity))
         {
             if (crossingPedestrians.Count > 0)
             {
                 DebugController.LogMessage("This car is crossing with pedestrians doing it at the same time: " + _entity.gameObject.name);
                 // TODO remover eso de aca
                 if (_entity.gameObject.CompareTag("Car") && _entity.gameObject.name != "PlayerCar_PFB Variant")
                 {
                     _entity.SetCrossingWithPedestrianValue(true);
                 }
             }
             _entity.GetMovableComponent.AddOnMovement(OnEntityMoved);
             CrossingInfo newInfo = new CrossingInfo();
             newInfo.lastPosition = _entity.transform.position;
             crossingVehicle.Add(_entity, newInfo);
         }
     }
 }
        public void PassFormBody()
        {
            var controller = new DebugController
            {
                ControllerContext = new ControllerContext()
            };

            controller.ControllerContext.HttpContext = new DefaultHttpContext();
            controller.ControllerContext.HttpContext.Request.Method = "POST";
            controller.ControllerContext.HttpContext.Request.Headers["Content-Type"] = "application/x-www-form-urlencoded";

            var body = new MemoryStream(Encoding.UTF8.GetBytes("foo=bar&baz=qux"));

            controller.ControllerContext.HttpContext.Request.Body = body;

            var result = controller.Index() as ViewResult;
            var model  = result.Model as DebugViewModel;

            model.Should().NotBeNull();

            model.Form.Length.Should().Be(2);

            model.Form[0].Key.Should().Be("foo");
            model.Form[0].Value.Should().Be("bar");

            model.Form[1].Key.Should().Be("baz");
            model.Form[1].Value.Should().Be("qux");
        }
Esempio n. 7
0
 public Executor(ExecuteInfo[] executeInfos, string stdinText)
 {
     this.executeInfos = executeInfos;
     this.stdinText    = stdinText;
     controller        = new DebugController();
     dict = new Dictionary <FlowSourceManager, ExecuteInfo>();
 }
Esempio n. 8
0
 private void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
 }
Esempio n. 9
0
    private GameObject cellSpaceLine;//单元空间的预制体

    private void Awake()
    {
        _instance = this;

        points    = new List <DebugPoint>();
        lines     = new List <DebugLine>();
        pathLines = new List <DebugLine>();
    }
Esempio n. 10
0
 public Executor(string scriptFilePath, Layer[] layers)
 {
     ScriptFilePath   = scriptFilePath;
     Layers           = layers;
     debugController  = new DebugController();
     controllerClient = new TcpDebugControllerClient(debugController);
     items            = new Dictionary <string, object>();
     AddItem("AllLayers", layers);
 }
Esempio n. 11
0
 // Use this for initialization
 public virtual void Start()
 {
     body         = GetComponent <Rigidbody2D>();
     lastPosition = body.position;
     audioSource  = GetComponent <AudioSource>();
     debugInfo    = new Hashtable();
     debugInfo.Add("HP", 0);
     debug      = new DebugController();
     beenThrown = false;
 }
Esempio n. 12
0
 public override void OnIntersectionEntered(ICrossable _intersection)
 {
     DebugController.LogMessage("Entered crosswalk");
     if (currentCrossingZone == null || !currentCrossingZone.Equals(_intersection))
     {
         currentCrossingZone?.OnFinishedCrossing(this);
         currentCrossingZone = (Intersection)_intersection;
         transitionController?.OnIntersectionEntered();
     }
 }
Esempio n. 13
0
        public TcpDebugControllerClient(DebugController debugController)
        {
            this.debugController = debugController;
            breakPoints          = new Dictionary <string, int[]>();
            dict = new Dictionary <string, FlowSourceManager>();

            debugController.OperationWaited   += debugController_OperationWaited;
            debugController.OperationAccepted += debugController_OperationAccepted;
            debugController.SourceChanged     += debugController_SourceChanged;
            debugController.ErrorOccurred     += debugController_ErrorOccurred;
            LogManager.Instance.LogReceived   += Instance_LogReceived;
        }
Esempio n. 14
0
        public void SessionVariablesTest()
        {
            DebugController   controller = new DebugController();
            PartialViewResult result;

            result = controller.SessionVariables();
            DebugSessionVariablesViewModel model = result.ViewData.Model as DebugSessionVariablesViewModel;

            //Assert.AreEqual(expected, actual);
            Assert.IsNotNull(result);
            Assert.IsNotNull(model);
        }
Esempio n. 15
0
 private new void OnTriggerEnter2D(Collider2D collision)
 {
     if (collision.CompareTag("Pedestrian") || collision.CompareTag("Car"))
     {
         DebugController.LogMessage("¡¡ME CHOQUE CON EL MACHETAZO!!");
         OnEntityCollision(collision.gameObject.GetComponent<EntityController>());
         GameManager.didPlayerLose = true;
         CanvasManager._instance.GenerateFeedback("Crash");
         CanvasManager._instance.ActivateCheckOrCross(false);
         StartCoroutine(CrashCR());
     }
 }
Esempio n. 16
0
        public FlowScriptManager(PPDDevice device, ISound sound)
        {
            priorityManagers             = new List <IPriorityManager>();
            engine                       = new Engine();
            engine.Error                += engine_Error;
            BPMManager                   = new BPMManager();
            UpdateManager                = new UpdateManager(engine);
            CalculatePositionManager     = new CalculatePositionManager(engine);
            ProcessEvaluateManager       = new ProcessEvaluateManager(engine);
            CreateMarkManager            = new CreateMarkManager(engine);
            ProcessMarkBPMManager        = new ProcessMarkBPMManager(engine);
            ProcessMissPressManager      = new ProcessMissPressManager(engine);
            ProcessAllowedButtonsManager = new ProcessAllowedButtonsManager(engine);
            InputManager                 = new InputManager();
            PauseManager                 = new PauseManager(engine);
            priorityManagers.AddRange(new IPriorityManager[] {
                UpdateManager,
                CalculatePositionManager,
                ProcessEvaluateManager,
                CreateMarkManager,
                ProcessMarkBPMManager,
                ProcessMissPressManager,
                ProcessAllowedButtonsManager,
            });
            GameResultManager = new GameResultManager();
            StageManager      = new StageManager(device);
            afterLoadList     = new Dictionary <string, object>();

            scriptList = new List <KeyValuePair <MemoryStream, ScriptInfo> >();
            ModManager.Instance.WaitForLoadFinish();
            if (!ModManager.Instance.Initialized)
            {
                ModManager.Instance.EnumerateClasses();
            }

            if (PPDSetting.Setting.IsDebug && TcpDebugControllerBase.IsListening())
            {
                debugController  = new DebugController();
                controllerClient = new TcpDebugControllerClient(debugController);
                try
                {
                    controllerClient.Create();
                }
                catch
                {
                    MessageBox.Show("Failed to create debug connection");
                    debugController  = null;
                    controllerClient = null;
                }
            }
        }
Esempio n. 17
0
    public void CheckAllInfractions(Crosswalk _crosswalk)
    {
        if (!isAlreadyReported)
        {
            isAlreadyReported = true;
            if (_crosswalk != null)
            {
                ActivePedestrianCount = _crosswalk.GetNumberOfCrossingPedestrians;
                DebugController.LogWarningMessage("Active Pedestrian Count: " + ActivePedestrianCount);
                DebugController.LogErrorMessage("Checking infractions");
                for (int i = 0; i < infractionsArray.Length; i++)
                {
                    if (ActivePedestrianCount > 0)
                    {
                        infractionsArray[i].AreThereCrossingPedestrians = true;
                    }
                    else
                    {
                        infractionsArray[i].AreThereCrossingPedestrians = false;
                    }

                    Debug.LogWarning("1) CheckAllInfractions Running (Evaluando el array de infracciones)");
                    infractionsArray[i].evaluatedObject = controlledObject;
                    infractionsArray[i].CheckForRuleViolation();
                    if (infractionsArray[i].CheckForRuleViolation() == true)
                    {
                        ScoreManager.instance.AddInfraction();
                    }
                }
            }
            else
            {
                for (int i = 0; i < infractionsArray.Length; i++)
                {
                    Debug.LogError("ESTOY EVALUANDO UNA INFRACCION SIN TENER CROSSWALK CERQUITA");
                    infractionsArray[i].AreThereCrossingPedestrians = false;
                    Debug.LogWarning("1) CheckAllInfractions Running (Evaluando el array de infracciones)");
                    infractionsArray[i].evaluatedObject = controlledObject;
                    infractionsArray[i].CheckForRuleViolation();
                    if (infractionsArray[i].CheckForRuleViolation() == true)
                    {
                        ScoreManager.instance.AddInfraction();
                    }
                }
            }
        }
        else
        {
            Debug.LogError("YA ESTA REPORTADO");
        }
    }
Esempio n. 18
0
        /// <summary>
        /// Set up debug UI, register variables for tweaking
        /// </summary>
        private void RegisterDebug()
        {
            DebugController dc = DebugController.instance;

            #region Bodies
            dc.Create(dc.slider).Init(ident: "Bodies", value: numPoints, min: 5, max: 500,
                                      onValueChanged: (int x) => {
                int newCount = x;
                if (newCount > bodies.Count)
                {
                    for (int i = 0, counti = newCount; i < counti; ++i)
                    {
                        GenerateBodies();
                    }
                }
                else if (newCount < bodies.Count)
                {
                    quadtree.clear();
                    for (int i = bodies.Count - 1, counti = newCount; i >= counti; --i)
                    {
                        bodies.RemoveAt(i);
                    }
                }
            }
                                      );
            #endregion

            #region Quadtree Recursion
            dc.Create(dc.slider).Init(ident: "Quadtree Depth", value: Quadtree.maxDepth, min: 1, max: 100,
                                      onValueChanged: (int x) => {
                Quadtree.maxDepth = x;
                quadtree.clear();
            }
                                      );
            #endregion

            #region Quadtree Object Limit
            dc.Create(dc.slider).Init(ident: "Objects Per Quad", value: Quadtree.objectPerQuad, min: 1, max: 100,
                                      onValueChanged: (int x) => {
                Quadtree.objectPerQuad = x;
            }
                                      );
            #endregion

            #region Pause/Play
            dc.Create(dc.button).Init(ident: "Pause", onClick: (DebugButton button) => {
                paused            = !paused;
                button.ident.text = paused ? "Play" : "Pause";
            });
            #endregion
        }
Esempio n. 19
0
    public T2 GetValue(T1 _key)
    {
        T2 objectToReturn = default(T2);

        if (HasKey(_key))
        {
            objectToReturn = (T2)dictionary[_key];
        }
        else
        {
            DebugController.LogErrorMessage(string.Format("There is no value for that key {0}", _key.ToString()));
        }
        return(objectToReturn);
    }
Esempio n. 20
0
 protected override bool ShouldStop() 
 {
     //NUEVO PUNTO PARA EL LLAMADO DE LA COLISION, PARA NO DEPENDER DEL CHECK DEL ENTITY CONTROLLER//
     bool stop = false;
     RaycastCheckResult collisionCheck = HasCollided();
     if (collisionCheck.collided && collisionCheck.otherEntity.IsOnTheStreet)
     {
         stop = true;
         DebugController.LogErrorMessage("Player should stop!");
         OnEntityCollision(collisionCheck.otherEntity);
     }
     return stop;
     // return input.IsBraking;
 }
Esempio n. 21
0
        private void DebugController_Update(On.DebugController.orig_Update orig, DebugController self)
        {
            orig(self);

            int TrinketCount = self.app.model.characterSheet.trinkets.Count;

            if (Input.GetKey(KeyCode.Alpha1))
            {
                if (!self.app.model.paused)                                                               // If game isn't paused
                {
                    if (TrinketCount == 1 || TrinketCount == 2 || TrinketCount == 3 || TrinketCount == 4) // If trinket exists
                    {
                        self.app.controller.GUINotification(self.app.model.characterSheet.trinkets[0].trinketName + "\n" + self.app.model.characterSheet.trinkets[0].Name, GUINotificationView.NotifyType.General, null, true);
                    }
                }
            }

            if (Input.GetKey(KeyCode.Alpha2))
            {
                if (!self.app.model.paused)
                {
                    if (TrinketCount == 2 || TrinketCount == 3 || TrinketCount == 4)
                    {
                        self.app.controller.GUINotification(self.app.model.characterSheet.trinkets[1].trinketName + "\n" + self.app.model.characterSheet.trinkets[1].Name, GUINotificationView.NotifyType.General, null, true);
                    }
                }
            }

            if (Input.GetKey(KeyCode.Alpha3))
            {
                if (!self.app.model.paused)
                {
                    if (TrinketCount == 3 || TrinketCount == 4)
                    {
                        self.app.controller.GUINotification(self.app.model.characterSheet.trinkets[2].trinketName + "\n" + self.app.model.characterSheet.trinkets[2].Name, GUINotificationView.NotifyType.General, null, true);
                    }
                }
            }

            if (Input.GetKey(KeyCode.Alpha4))
            {
                if (!self.app.model.paused)
                {
                    if (TrinketCount == 4)
                    {
                        self.app.controller.GUINotification(self.app.model.characterSheet.trinkets[3].trinketName + "\n" + self.app.model.characterSheet.trinkets[3].Name, GUINotificationView.NotifyType.General, null, true);
                    }
                }
            }
        }
        public void PassRefererToModel()
        {
            var controller = new DebugController
            {
                ControllerContext = new ControllerContext()
            };

            controller.ControllerContext.HttpContext = new DefaultHttpContext();
            controller.ControllerContext.HttpContext.Request.Headers["Referer"] = "example.com";

            var result = controller.Index() as ViewResult;
            var model  = result.Model as DebugViewModel;

            model.Should().NotBeNull();

            model.Referer.Should().Be("example.com");
        }
Esempio n. 23
0
 // Start is called beforz the first frame update
 void Start()
 {
     health          = maxHealth;
     startPos        = transform.position;
     nameTag.text    = photonView.Owner.NickName;
     controller      = GetComponent <CharacterController>();
     debugController = GetComponent <DebugController>();
     audioManager    = GetComponent <AudioManager>();
     m_camera        = Camera.main;
     animator        = GetComponent <Animator>();
     SetAnimation("isIdle", true);
     StartCoroutine("WaitForLoad");
     UpdateHealthUI();
     gunHolderScript = gunHolder.GetComponent <GunHolder>();
     photonView.RPC(nameof(SetupPartyHealthBars), RpcTarget.AllBufferedViaServer);
     StartCoroutine(PlayRepeatingWalkSoundEffect());
 }
        public void PassMethodToModel()
        {
            var controller = new DebugController
            {
                ControllerContext = new ControllerContext()
            };

            controller.ControllerContext.HttpContext = new DefaultHttpContext();
            controller.ControllerContext.HttpContext.Request.Method = "GET";

            var result = controller.Index() as ViewResult;
            var model  = result.Model as DebugViewModel;

            model.Should().NotBeNull();

            model.Method.Should().Be("GET");
        }
Esempio n. 25
0
 public override void OnCrossWalkEntered(ICrossable _crossWalk) 
 {
     DebugController.LogMessage("Player entered crosswalk");
     // Si hay peatones cruzando sacar lo de las infracciones
     Crosswalk cross = ((Crosswalk)_crossWalk);
     if (cross.GetNumberOfCrossingPedestrians > 0)
     {
         if (!cross.CanCrossIfPathIsFree(this))
         {
             ScoreManager.instance.AddInfraction();
             CanvasManager._instance.ActivateCheckOrCross(false);
             CanvasManager._instance.GenerateFeedback("CrossWithPedestrian");
         }
     }
     OnStartedCrossing(_crossWalk);
     _crossWalk.OnStartedCrossing(this);
 }
Esempio n. 26
0
    public static GameObject RaycastForFirstGameObject(GameObject _castingGO, Vector3 _startPosition, Vector3 _direction, float _distance, LayerMask _layersToCheckCollision, Color _debugColor)
    {
        GameObject   goToReturn = null;
        GameObject   objectHit  = null;
        RaycastHit2D castHit    = Physics2D.Raycast(_startPosition, _direction, _distance, _layersToCheckCollision);

        DebugController.DrawDebugRay(_startPosition, _direction, _distance, _debugColor);
        DebugController.DrawDebugRay(_startPosition, _direction, _distance, _debugColor);
        if (castHit.collider)
        {
            objectHit = castHit.collider.gameObject;
            if (objectHit && !objectHit.Equals(_castingGO))
            {
                DebugController.DrawDebugLine(_startPosition, castHit.point, _debugColor.gamma);
                goToReturn = objectHit;
            }
        }
        return(goToReturn);
    }
Esempio n. 27
0
        /// <summary>
        /// Функция последовательной инициализации
        /// </summary>
        public void OnStart()
        {
            _debugController  = FindObjectOfType <DebugController>();
            _debugInitialized = _debugController != null;

            Application.targetFrameRate = 300;
            SetSubscription();

            _untilAllReady    = new WaitUntil(ComponentsAreReady);
            _notCaptureLocked = new WaitUntil(() => !_captureLocked);

            foreach (var deviceController in DeviceControllers)
            {
                deviceController.Initialize();
            }
            hardwareController.Initialize();

            StartCoroutine(EWideFiledRun());
        }
Esempio n. 28
0
    public static void CircleCastForFirstGameObject(GameObject _castingGO, Vector3 _startPosition, float _checkRadius, Vector3 _direction, float _distance, LayerMask _layersToCheckCollision)
    {
        GameObject   goToReturn = null;
        GameObject   objectHit  = null;
        RaycastHit2D castHit    = Physics2D.CircleCast((Vector2)_startPosition, _checkRadius, _direction, _distance, _layersToCheckCollision);

        if (castHit.collider)
        {
            objectHit = castHit.collider.gameObject;
            if (objectHit && !objectHit.Equals(_castingGO))
            {
                DebugController.DrawDebugLine(_startPosition, castHit.point, Color.magenta);
                goToReturn = objectHit;
                DebugController.DrawDebugCircle(_startPosition, _checkRadius, Color.green);
                DebugController.DrawDebugRay(_startPosition, _direction, _distance, Color.green);
                DebugController.DrawDebugCircle(_startPosition + _direction * _distance, _checkRadius, Color.green);
            }
        }
    }
Esempio n. 29
0
 // Use this for initialization
 void Awake()
 {
     if (doNotDestroyOnLoad)
     {
         if (debugState == null)
         {
             DontDestroyOnLoad(gameObject);
             debugState = this;
         }
         else if (debugState != this)
         {
             Destroy(debugState);
         }
     }
     else
     {
         debugState = this;
     }
 }
Esempio n. 30
0
 private void Start()
 {
     CrossableType = CrossableType.CrossWalk;
     //int randomType = UnityEngine.Random.Range(0, Enum.GetNames(typeof(EntityType)).Length);
     //ChangeTurn((EntityType)randomType);
     ChangeTurn(EntityType.Vehicle);
     if (crossAreaBounds)
     {
         crossWalkLenght = crossAreaBounds.bounds.size.x * transform.localScale.x;
     }
     else
     {
         DebugController.LogErrorMessage("Missing crooss are bouds reference.");
     }
     if (connectedPaths == null || connectedPaths.Length.Equals(0))
     {
         DebugController.LogErrorMessage($"{ gameObject.name } has no connectedPaths!");
     }
 }
Esempio n. 31
0
 public override void Activate(object eventData)
 {
     mController = (this.Parent as DebugController);
     mParent = mController.gameObject;
     mCharacterController = (CharacterController)mParent.GetComponent(typeof(CharacterController));
     if (mController.MeshTransform.animation != null)
     {
         mAnimation = mController.MeshTransform.animation;
     }
 }
 void Awake()
 {
     Instance = this;
     logMessages = new List<string>();
 }
Esempio n. 33
0
    public static void Main(string[] args)
    {
        Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
        
        DebugController debugger = new DebugController();
        
        //Load in custom beatmaps if specified
        args = debugger.LoadCustom(args);
        
        //Display a message if no files are specified
        if(args.Length == 0)
        {
            Console.WriteLine("CTB Difficulty Analyzer");
            Console.WriteLine("Just drag your beatmap (.osu file) onto this program to measure difficulty");
            Console.WriteLine("Press any key to exit...");
        }
        //Otherwise try to run the program, and catch and display any exceptions that arise
        else
        {
            Console.WriteLine("Calculating...");
            SortedList<double, string> beatmaps = new SortedList<double, string>();
            List<DiffCalc> calculators = new List<DiffCalc>();
            Stopwatch timer = new Stopwatch();
            try
            {
                int count = 0;
                foreach(string name in args)
                {
                    timer.Start();

                    Beatmap map = new Beatmap(name);
                    DiffCalc calc;
                    try
                    {
                        calc = new DiffCalc(map);
                    }
                    catch(InvalidBeatmapException)
                    {
                        //Skip this beatmap if it's not a standard or ctb map, but only if
                        //it was loaded through debug
                        if(debugger.IsLoadCustom())
                            continue;
                        else
                            throw;
                    }
                    
                    string title = calc.GetBeatmapTitle() + ": \t";
                    double difficulty = calc.GetDifficulty();

                    timer.Stop();
                    
                    title += timer.ElapsedMilliseconds;
                    beatmaps[difficulty] = title;
                    calculators.Add(calc);
                    
                    timer.Reset();
                    count++;
                    Console.Write(Math.Round((double)count * 100 / args.Length) + "%\r");
                }
                
                Console.WriteLine("\n");
                for(int i = beatmaps.Count - 1; i >= 0; i--)
                {
                    string[] titleandtime = beatmaps.Values[i].Split('\t');
                    Console.WriteLine(titleandtime[0] + beatmaps.Keys[i]);
                    Console.WriteLine("Calculation Time (ms): " + titleandtime[1] + "\n");
                }
                
                debugger.WriteDebug(calculators.ToArray());

                Console.WriteLine("\nDone.");
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                //Just in case the timer is still running
                timer.Stop();
            }
        }

        Console.ReadKey();
    }