Example #1
0
 public ConsoleSession(byte columns, byte rows, ConsoleManager consoleManager)
 {
     Columns = columns;
     Rows = rows;
     ConsoleManager = consoleManager;
     text = new byte[Columns * Rows];
     textcolor = new byte[Columns * Rows];
 }
	public static ConsoleManager getInstance ()
	{
		if ( _meInstance == null )
		{
			_meInstance = GameObject.Find ( "_ConsoleObject" ).GetComponent < ConsoleManager > ();
		}
		
		return _meInstance;
	}
Example #3
0
        public GameManager()
        {
            _gameSize = new Size(BlockSize * 4, BlockSize * 4);
            _consoleManager = new ConsoleManager();
            _consoleState = _consoleManager.SaveConsoleState();

            _consoleManager.SetForGraphics();
            _consoleManager.ResizeConsoleWindow(_gameSize);
        }
        public void ConsoleManager_Constructor_CreatesConsoleManager()
        {
            // Arrange
              var processFactory = new MockProcessFactory();

              // Act
              var cm = new ConsoleManager(processFactory);

              // Assert
              Assert.IsInstanceOfType(cm, typeof(ConsoleManager));
        }
	public static ArrayList prepareCommand ( ArrayList allCommands, string name, Pointer < float > pointerValue, string valueType, ConsoleManager.CallBackFunction callBack, string commandType, string password = NO_PASSWORD )
	{
		ArrayList command = new ArrayList ();
		command.Add ( name );
		command.Add ( pointerValue );
		command.Add ( valueType );
		command.Add ( callBack );
		command.Add ( commandType );
		command.Add ( password );
		
		allCommands.Add ( command );
		return new ArrayList ();
	}
        public void ConsoleManager_InvokeCommand_AddsHistory()
        {
            // Arrange
              var processFactory = new MockProcessFactory
              {
            MockCreateProcess_StartInfo = startInfo => new MockProcessWrapper()
              };

              var cm = new ConsoleManager(processFactory);

              // Act
              cm.InvokeCommand("hello", "world");

              // Assert
              Assert.AreEqual(cm.History.ElementAt(0), "hello world");
        }
        public SelectDevkitDialog(IServiceProvider sp)
        {
            this.Consoles = new ObservableCollection<ConsoleWrapper>();
            InitializeComponent();
            this.DataContext = this;
            this.Loaded += SelectDevkitDialog_Loaded;
            this.notificationService = sp.GetService(typeof(IUserNotificationService)) as IUserNotificationService;

            this.consoleManager = new ConsoleManager();
            this.removals = new List<ConsoleWrapper>();
            InitConsolesList();

            this.consoleManager.ConsoleAdded += OnConsolesChanged;
            this.consoleManager.ConsoleRemoved += OnConsolesChanged;
            this.consoleManager.DefaultConsoleChanged += OnConsolesChanged;
        }
Example #8
0
        public void SetDungeonEventObjectInformation(int id, string uniqueName)
        {
            if (_currentGuid != null && uniqueName != null)
            {
                try
                {
                    var dun = GetCurrentDungeon((Guid)_currentGuid);
                    if (dun == null || _currentGuid == null || dun.DungeonEventObjects?.Any(x => x.Id == id) == true)
                    {
                        return;
                    }

                    var eventObject = new DungeonEventObject()
                    {
                        UniqueName  = uniqueName,
                        IsBossChest = DungeonObjectData.IsBossChest(uniqueName),
                        Id          = id
                    };

                    dun.DungeonEventObjects?.Add(eventObject);

                    dun.Faction = DungeonObjectData.GetFaction(uniqueName);

                    if (dun.Mode == DungeonMode.Unknown)
                    {
                        dun.Mode = DungeonObjectData.GetDungeonMode(uniqueName);
                    }
                }
                catch (Exception e)
                {
                    ConsoleManager.WriteLineForError(MethodBase.GetCurrentMethod().DeclaringType, e);
                    Log.Error(MethodBase.GetCurrentMethod().DeclaringType, e);
                }
            }

            SetDungeonStatsDay();
            SetDungeonStatsTotal();
        }
        public void OnBeginPlay()
        {
            Assert.IsFalse(variable.IsBool);
            Assert.IsFalse(variable.IsFloat);
            Assert.IsFalse(variable.IsString);
            Assert.IsTrue(variable.IsInt);
            Assert.IsTrue(variable.GetInt() == variableValue);

            variable.SetOnChangedCallback(VariableEvent);

            ConsoleManager.RegisterCommand(consoleCommand, "Executes a test command", ConsoleCommand);

            Assert.IsTrue(ConsoleManager.IsRegisteredVariable(consoleCommand));

            Engine.AddActionMapping(pauseResumeAction, pauseResumeKey);
            Engine.AddAxisMapping(mouseXAction, mouseXKey);
            Engine.AddAxisMapping(mouseYAction, mouseYKey);

            playerInput.AddActionMapping(playerCommandAction, playerCommandKey);

            InputComponent inputComponent = playerController.InputComponent;

            Assert.IsFalse(inputComponent.HasBindings);

            inputComponent.BindAction(pauseResumeAction, InputEvent.Pressed, PauseResume, true);
            inputComponent.BindAction(playerCommandAction, InputEvent.Pressed, PlayerCommand, true);
            inputComponent.BindAxis(mouseXAction, MouseXMessage);
            inputComponent.BindAxis(mouseYAction, MouseYMessage);

            Assert.IsTrue(inputComponent.HasBindings);
            Assert.IsTrue(inputComponent.ActionBindingsNumber == 2);

            const string removableAction = "TestRemovable";
            const string removableKey    = Keys.R;

            playerInput.AddActionMapping(removableAction, removableKey, ctrl: true, alt: true);
            playerInput.RemoveActionMapping(removableAction, removableKey);
        }
Example #10
0
        public void Shutdown(bool terminate = true)
        {
            lock (_bootInProgressLocker)
            {
                if (ConsoleManager == null)
                {
                    return;
                }

                ConsoleManager.Warning("Core", "Shutting down IHI!");

                if (CoreManager.ServerCore.OfficalEventFirer == null)
                {
                    return;
                }

                IHIEventArgs eventArgs = new IHIEventArgs();
                CoreManager.ServerCore.OfficalEventFirer.Fire("shutdown:before", eventArgs);
                CoreManager.ServerCore.OfficalEventFirer.Fire("shutdown:after", eventArgs);

                if (WebAdminManager == null)
                {
                    return;
                }

                WebAdminManager.Stop();

                Config = null;

                System.Console.Beep(4000, 100);
                System.Console.Beep(3500, 100);
                System.Console.Beep(3000, 100);
                System.Console.Beep(2500, 100);
                System.Console.Beep(2000, 100);
                System.Console.Beep(1500, 100);
                System.Console.Beep(1000, 100);
            }
        }
Example #11
0
    private Point ParseSeat(string x)
    {
        var binary = x.Select(x => ParseChar(x));
        var binStr = binary.Select(x => x ? '1' : '0').ToList();

        binStr.Insert(7, '-');

        var row  = FromBinary(binary.SkipLast(3));
        var col  = FromBinary(binary.Skip(7));
        var seat = new Point(row, col);

        if (col >= 4)
        {
            System.Console.ForegroundColor = ConsoleColor.Green;
        }
        else
        {
            System.Console.ForegroundColor = ConsoleColor.Blue;
        }
        Console.WriteLine($"Seat {x} → {new string(binStr.ToArray())} → row {row.ToString("000")}, col {col.ToString("00")} → ID {GetSeatId(seat)}");

        return(seat);
    }
Example #12
0
    //-----------------------------------------------------------------

    public override long Part1(string input)
    {
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(100);
            _itteration?.SetValue(i);
            var f = (float)RandomGen.NextDouble();
            _aFloat?.SetValue(f);
            _aFormatedFloat?.SetValue(f);
            Console.WriteLine("Itteration " + i);


            var percent = i * 1f / 9f;
            _percent1?.SetValue(percent);
            _percent2?.SetValue(percent);
            _percent3?.SetValue(percent);
            _percent4?.SetValue(percent);
            _percent5?.SetValue(percent);
            _percent6?.SetValue(percent);
        }

        return((long)(RandomGen.NextDouble() * 1000));
    }
Example #13
0
        /// <summary>
        /// Returns true if an existing discovery is succesfully selected and upgraded
        /// </summary>
        /// <returns></returns>
        ResearchResult _tryUpgradeDiscovery()
        {
            var nonMaxxed = DiscoveryLevels.Where(a => (a.Value < ResearchHandler.MaxResearchLevel));

            if (nonMaxxed.Count() != 0)
            {
                var resToUpgrade = nonMaxxed.ElementAt(Rand.Random.Next(0, nonMaxxed.Count()));
                DiscoveryLevels[resToUpgrade.Key] += 1;

#if DEBUG
                ConsoleManager.WriteLine("Discovered " + resToUpgrade.Key.ToString() + " level " + DiscoveryLevels[resToUpgrade.Key], ConsoleMessageType.Debug);
#endif

                return(new ResearchResult()
                {
                    Discovery = resToUpgrade.Key, Level = resToUpgrade.Value
                });
            }
            else
            {
                return(null);
            }
        }
Example #14
0
        /// <summary>
        /// Runs AI game.
        /// </summary>
        /// <param name="command">The AI command.</param>
        private void RunGame(Command command)
        {
            var colorArgument         = command.GetArgument <string>(0);
            var preferredTimeArgument = command.GetArgument <float>(1);
            var helperTasksCount      = command.GetArgument <int>(2);

            var colorParseResult = Enum.TryParse(colorArgument, true, out Color color);

            if (!colorParseResult)
            {
                ConsoleManager.WriteLine($"$rInvalid color type ($R{color}$r)");
                return;
            }

            _playerColor      = color;
            _preferredTime    = preferredTimeArgument;
            _helperTasksCount = helperTasksCount;

            if (_playerColor == Color.Black)
            {
                MoveAI();
            }
        }
Example #15
0
        /// <summary>Reads the working package file.</summary>
        /// <returns>The <see cref="string" />.</returns>
        public static string Read()
        {
            if (PackageManager.WorkingPackage == null)
            {
                ConsoleManager.WriteOutput(Descriptions.CommandDescriptions[12]);
                ConsoleManager.WriteOutput("Usage: Read");
                Console.WriteLine();
            }
            else
            {
                try
                {
                    StringManager.DrawPackageTable(PackageManager.WorkingPackage);
                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    ExceptionsManager.WriteException(e.Message);
                }
            }

            return(string.Empty);
        }
Example #16
0
    private (int indexStart, int indexEnd)? FindContiguousSum(List <long> numbers, long target)
    {
        for (int left = 0; left < numbers.Count - 1; left++)
        {
            var sum   = numbers[left];
            var right = left;

            _progress?.SetValue(left / (float)numbers.Count);
            _currentIndex?.SetValue(left);
            do
            {
                right++;
                sum += numbers[right];
                if (sum == target)
                {
                    return(left, right);
                }
            } while (sum < target && right < numbers.Count);

            Console.WriteLine($"{left.ToString("000")} to {right.ToString("000")} = {sum}");
        }
        return(null);
    }
Example #17
0
    //-----------------------------------------------------------------

    public override long Part1(string input)
    {
        LinkedList <int> cups = PlayGameWithLinkedList(input, 100, 10, true);

        Console.WriteLine($"-- Final --\ncups: {cups.GetPrintStr()}");

        var score    = "";
        var scoreCup = cups.Find(1);

        while (cups.Count != 0)
        {
            var lastCup = scoreCup;
            scoreCup = scoreCup.NextOrFirst();
            cups.Remove(lastCup);
            if (scoreCup != null)
            {
                score += scoreCup.Value.ToString();
            }
        }
        score = score.Remove(score.Length - 1);

        return(long.Parse(score));
    }
Example #18
0
    public static void PrintLogInfo(ManualLogSource log)
    {
        var consoleTitle = $"BepInEx {Paths.BepInExVersion} - {Paths.ProcessName}";

        log.Log(LogLevel.Message, consoleTitle);

        if (ConsoleManager.ConsoleActive)
        {
            ConsoleManager.SetConsoleTitle(consoleTitle);
        }

        //See BuildInfoAttribute for more information about this section.
        var attributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), false);

        if (attributes.Length > 0)
        {
            var attribute = (BuildInfoAttribute)attributes[0];
            log.Log(LogLevel.Message, attribute.Info);
        }

        Logger.Log(LogLevel.Info, $"System platform: {GetPlatformString()}");
        Logger.Log(LogLevel.Info, $"Process bitness: {(PlatformUtils.ProcessIs64Bit ? "64-bit (x64)" : "32-bit (x86)")}");
    }
Example #19
0
        static void Run()
        {
            while (true)
            {
                //TODO: move to time with autoreset disabled

                if (TimeKeeper.MsSinceInitialization - _lastUpdateTimeStamp >=
                    _simulatorConfig.MainManagerUpdateIntervalMS)
                {
                    _lastUpdateTimeStamp = TimeKeeper.MsSinceInitialization;

                    _mainManager.Update(null, null);

                    if (TimeKeeper.MsSinceInitialization - _lastUpdateTimeStamp >
                        _simulatorConfig.MainManagerUpdateIntervalMS)
                    {
                        ConsoleManager.WriteLine("WARNING: TIMED UPDATES LATE IN SIMULATOR",
                                                 ConsoleMessageType.Warning);
                    }
                }
                Thread.Sleep(1);
            }
        }
Example #20
0
        internal static void Load()
        {
            try
            {
                Paths.SetExecutablePath(typeof(HN.Program).Assembly.GetName().Name);

                Logger.Listeners.Add(new ConsoleLogger());
                AccessTools.PropertySetter(typeof(TraceLogSource), nameof(TraceLogSource.IsListening)).Invoke(null, new object[] { true });
                ConsoleManager.Initialize(true);

                // Start chainloader for plugins
                var chainloader = new HacknetChainloader();
                chainloader.Initialize();
                chainloader.Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal loading exception:");
                Console.WriteLine(ex);
                Console.ReadLine();
                Environment.Exit(1);
            }
        }
        public InventoryPutItemEvent(Dictionary <byte, object> parameters) : base(parameters)
        {
            ConsoleManager.WriteLineForNetworkHandler(GetType().Name, parameters);

            try
            {
                if (parameters.ContainsKey(0))
                {
                    ObjectId = parameters[0].ObjectToLong();
                }

                if (parameters.ContainsKey(2))
                {
                    InteractGuid = parameters[2].ObjectToGuid();
                }
            }
            catch (Exception e)
            {
                ObjectId     = null;
                InteractGuid = null;
                ConsoleManager.WriteLineForError(MethodBase.GetCurrentMethod().DeclaringType, e);
            }
        }
Example #22
0
        public async Task <string> RunInterfaceAsync(List <HistoryItem> history)
        {
            var historyToDisplay = history.Select(x => x.CmdLine).Distinct().ToList();
            var control          = Build(historyToDisplay);

            ConsoleManager.Setup();
            ConsoleManager.Content = control;

            ConsoleManager.Resize(new ConsoleGUI.Space.Size(Console.WindowWidth, Console.WindowHeight));
            ConsoleManager.AdjustWindowSize();

            var inputListener = new IInputListener[]
            {
                this,
                listView,
                searchBox
            };

            quit = false;

            while (!quit)
            {
                ConsoleManager.AdjustBufferSize();
                ConsoleManager.ReadInput(inputListener);

                if (updateSearch)
                {
                    updateSearch = false;
                    var searchResults = historyToDisplay.Where(x => x.ToLowerInvariant().Contains(searchBox.Text.ToLowerInvariant())).ToList();
                    listView.Items = searchResults;
                }

                await Task.Delay(50);
            }

            return(listView.SelectedItem);
        }
Example #23
0
    public void ManageEnemyTurn()
    {
        if (enemy.healthBar.value * 100 > 50)
        {
            float totalDamage = enemy.CalculateDamage() * player.defense;
            StartCoroutine(ChangeSliderValue(player.healthBar, totalDamage, "Player"));
            enemy.GetComponent <AudioSource> ().Play();
            ConsoleManager.AddText(player.id + " was wounded for " + totalDamage + "\n");
            if (player.healthBar.value <= 0)
            {
                panelDefeat.SetActive(true);
            }
        }

        if (enemy.healthBar.value * 100 < 25)
        {
            //Cover("Enemy");
        }
        else
        {
            int chance = Random.Range(0, 1);

            if (chance == 1)
            {
                float totalDamage = 10 - player.defense;
                StartCoroutine(ChangeSliderValue(player.healthBar, totalDamage, "Player"));
                if (player.healthBar.value <= 0)
                {
                    panelDefeat.SetActive(true);
                }
            }
            else
            {
                //Cover("Enemy");
            }
        }
    }
Example #24
0
        public MasterServerManager(MasterServerConfig c, GalacticProperties gp, IDatabaseManager dbm, IDbIdIoService dbIdIoService, RedisServer redisServer, SlaveServerConfigService slaveServerConfigService)
        {
            _redisServer              = redisServer;
            _databaseManager          = dbm;
            _dbIdIoService            = dbIdIoService;
            _slaveServerConfigService = slaveServerConfigService;
            MasterServerConfig        = c;
            GalacticProperties        = gp;

            SlaveID = _slaveServerConfigService.CurrentServiceId;

            if (!_checkForMasterServer())
            {
                List <PSystemModel> allSystems = new List <PSystemModel>(_databaseManager.GetAllSystemsAsync().Result);
                _promoteToMasterServer(MasterServerConfig, GalacticProperties, allSystems, _databaseManager, _dbIdIoService, _redisServer);
            }
            else
            {
#if DEBUG
                ConsoleManager.WriteLine("Existing master server detected. Initializating as slave only.", ConsoleMessageType.Debug);
#endif
            }

            if (!IsMasterServer)
            {
                ConsoleManager.WriteLine("Initializing as slave only.", ConsoleMessageType.Notification);//Leaving this here to remember to log it later, might be useful
            }

            _connectToServer();

            redisServer.Subscribe(MessageTypes.Redis_SlaveConnectionResponse, _handleSlaveConnectionResponse);


            _pingTimer          = new Timer(c.SlaveHeartbeatPeriodMS);
            _pingTimer.Elapsed += _updateSlaveHeartbeat;
            _pingTimer.Start();
        }
Example #25
0
        public void RunInCmd(EventHandler <MessageHandler.MessageEventArgs> logger = null)
        {
            try
            {
                if (IsWin10)
                {
                    ConsoleManager.EnableVtMode();
                }

                ServiceMode = false;

                MessageHandler.Message += logger ?? CommandlineLogger;

                OnStart(Environment.GetCommandLineArgs());

                Console.Title = $@"{ServiceName} - Press Escape to Exit";

                while (!(Console.KeyAvailable && Console.ReadKey(true).Key.Equals(ConsoleKey.Escape)))
                {
                    Thread.Sleep(10);
                }

                OnStop();

                MessageHandler.Message -= logger ?? CommandlineLogger;

                if (IsWin10)
                {
                    ConsoleManager.DisableVtMode();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey();
            }
        }
Example #26
0
        /// <summary>
        ///     Initializes a new instance of the <see cref = "Crawl" /> class.
        /// </summary>
        /// <param name = "crawler">The crawler.</param>
        /// <param name="actionManager"></param>
        /// <param name="crawlRequestManager"></param>
        /// <param name="discoveryManager"></param>
        /// <param name="htmlManager"></param>
        /// <param name="politenessManager"></param>
        /// <param name="ruleManager"></param>
        /// <param name = "processData">if set to <c>true</c> [process data].</param>
        public Crawl(ApplicationSettings applicationSettings, WebSettings webSettings, Crawler <TArachnodeDAO> crawler, ActionManager <TArachnodeDAO> actionManager, ConsoleManager <TArachnodeDAO> consoleManager, CookieManager cookieManager, CrawlRequestManager <TArachnodeDAO> crawlRequestManager, DataTypeManager <TArachnodeDAO> dataTypeManager, DiscoveryManager <TArachnodeDAO> discoveryManager, EncodingManager <TArachnodeDAO> encodingManager, HtmlManager <TArachnodeDAO> htmlManager, PolitenessManager <TArachnodeDAO> politenessManager, ProxyManager <TArachnodeDAO> proxyManager, RuleManager <TArachnodeDAO> ruleManager, bool processData)
        {
            _applicationSettings = applicationSettings;
            _webSettings         = webSettings;

            UncrawledCrawlRequests = new PriorityQueue <CrawlRequest <TArachnodeDAO> >();
            UnassignedDiscoveries  = new HashSet <string>();

            _crawler = crawler;

            _crawlInfo.MaximumCrawlDepth = 1;

            _actionManager       = actionManager;
            _consoleManager      = consoleManager;
            _cookieManager       = cookieManager;
            _crawlRequestManager = crawlRequestManager;
            _dataTypeManager     = dataTypeManager;
            _discoveryManager    = discoveryManager;
            _encodingManager     = encodingManager;
            _htmlManager         = htmlManager;
            _politenessManager   = politenessManager;
            _proxyManager        = proxyManager;
            _ruleManager         = ruleManager;

            _processData = processData;

            _arachnodeDAO = (TArachnodeDAO)Activator.CreateInstance(typeof(TArachnodeDAO), _applicationSettings.ConnectionString, _applicationSettings, _webSettings, false, false);
            _arachnodeDAO.ApplicationSettings = applicationSettings;

            //_arachnodeDAO.OpenCommandConnections();

            _dataManager    = new DataManager <TArachnodeDAO>(_applicationSettings, _webSettings, _actionManager, _dataTypeManager, _discoveryManager, _ruleManager, _arachnodeDAO);
            _fileManager    = new FileManager <TArachnodeDAO>(_applicationSettings, _webSettings, _discoveryManager, _arachnodeDAO);
            _imageManager   = new ImageManager <TArachnodeDAO>(_applicationSettings, _webSettings, _discoveryManager, _arachnodeDAO);
            _webClient      = new WebClient <TArachnodeDAO>(_applicationSettings, _webSettings, _consoleManager, _cookieManager, _proxyManager);
            _webPageManager = new WebPageManager <TArachnodeDAO>(_applicationSettings, _webSettings, _discoveryManager, _htmlManager, _arachnodeDAO);
        }
Example #27
0
        public static void Main(string[] args)
        {
            var logPath = "application.log";

            var logger = new AggregatedLogger(
                new FileLogger(logPath),
                new ConsoleLogger()
                );

            IConsoleManager consoleManager = new ConsoleManager();
            var             environment    = new AppEnvironment(consoleManager);

            try
            {
                var envelopes = environment.Parse(args);

                var analysis = environment.CheckEnvelopes(envelopes);

                do
                {
                    consoleManager.WriteLine($"{analysis}");

                    envelopes = environment.RequestExtraEnvelopes();

                    if (envelopes == null)
                    {
                        break;
                    }

                    analysis = environment.CheckEnvelopes(envelopes);
                }while (envelopes.Any());
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.Message);
            }
        }
Example #28
0
    //-----------------------------------------------------------------

    public override long Part2(string input)
    {
        var program = CodeCompiler.ParseProgram(input);

        for (var instructionLine = 7; instructionLine < program.Instructions.Count; instructionLine++)
        {
            var instruction = program.Instructions[instructionLine];
            if (instruction.Operation == "jmp")
            {
                program.Instructions[instructionLine] = new CodeInstruction("nop", instruction.Argument);
            }
            else if (instruction.Operation == "nop")
            {
                program.Instructions[instructionLine] = new CodeInstruction("jmp", instruction.Argument);
            }
            else
            {
                continue;
            }

            Console.WriteLine($"Trying with change of line {instructionLine}\n");

            int infinitProtection = 10000;
            while (infinitProtection-- > 0)
            {
                if (program.IsProgramDone)
                {
                    return(program.CurrentState.Accumulator);
                }
                program.Step();
                //Console.WriteLine(program.GetStateString());
            }

            program = CodeCompiler.ParseProgram(input);
        }
        return(0);
    }
Example #29
0
        public int[,] Transformed()
        {
            //int[] tab = size_tab();
            int[] tab = { 40, 40 };

            int[,] tableau = new int[40, 40];
            ConsoleManager.Show();

            for (int i = 0; i < tableau.GetLength(0); i++)
            {
                for (int j = 0; j < tableau.GetLength(1); j++)
                {
                    tableau[i, j] = 1;
                }
            }
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    tableau[i, j] = -1;
                }
            }

            foreach (IMappedImageInfo e in map)
            {
                for (int y = 0; y < e.ImageInfo.Height; y++)
                {
                    for (int x = 0; x < e.ImageInfo.Width; x++)
                    {
                        tableau[y + e.Y, x + e.X] = -1;
                        ////probleme d'inexation commen tretrouver l'indexe en fonction de la largeur de colomne et le reste
                    }
                }
            }

            return(tableau);
        }
        public async Task <SingleResponse <int> > EmployeesActions(EmployeeDto employee)
        {
            using (_httpClient = new HttpClient())
            {
                var endPoint = "Employees/API/";
                _httpClient.BaseAddress = new Uri(_baseAddress);
                _httpClient.DefaultRequestHeaders.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                if (employee.EmployeeId == 0)
                {
                    endPoint += "AddEmployee";
                }
                else
                {
                    endPoint += "EditEmployee";
                }

                var payload  = EncodeContent(employee);
                var response = await _httpClient.PostAsync(endPoint, payload);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <SingleResponse <int> >(responseContent);
                    if (result.Success == 1)
                    {
                        return(result);
                    }
                    ConsoleManager.Show();
                    Console.WriteLine(result.Message);
                    Console.ReadKey();
                }
                return(null);
            }
        }
        /// <summary>
        ///     Uses network discovery to find servers
        /// </summary>
        void DiscoverServers()
        {
            // Discover on default port
            Colorful.Console.WriteLine("Discovering Servers...");
            client.DiscoverLocalPeers(Program.DefaultPort);

            // Check for answers after x seconds
            Thread.Sleep(2000);
            Console.WriteLine($"Found {gameServers.Count} server(s)");

            // Ask user if to continue to discover on custom port
            do
            {
                // Get input
                string s = ConsoleManager.WaitGetPriorityInput("Input server port to continue discovering or leave empty to stop");
                if (s.Length > 0)
                {
                    // Parse input
                    if (int.TryParse(s, out int p))
                    {
                        Colorful.Console.WriteLine("Discovering Servers...");
                        client.DiscoverLocalPeers(p);
                        Thread.Sleep(1200);
                        Console.WriteLine($"Found {gameServers.Count} server(s)");
                    }
                    else
                    {
                        Console.WriteLine("input is not a valid port");
                    }
                }
                else
                {
                    break;  // If input is empty stop discovery
                }
            }while (true);
        }
Example #32
0
        public PartySilverGainedEvent(Dictionary <byte, object> parameters) : base(parameters)
        {
            ConsoleManager.WriteLineForNetworkHandler(GetType().Name, parameters);

            try
            {
                foreach (var parameter in parameters)
                {
                    Debug.Print($"{parameter}");
                }

                if (parameters.ContainsKey(0))
                {
                    TimeStamp = new GameTimeStamp(parameters[0].ObjectToLong() ?? 0);
                }

                if (parameters.ContainsKey(1))
                {
                    TargetEntityId = parameters[1].ObjectToLong();
                }

                if (parameters.ContainsKey(2))
                {
                    SilverNet = FixPoint.FromInternalValue(parameters[2].ObjectToLong() ?? 0);
                }

                if (parameters.ContainsKey(3))
                {
                    SilverPreTax = FixPoint.FromInternalValue(parameters[3].ObjectToLong() ?? 0);
                }
            }
            catch (Exception e)
            {
                ConsoleManager.WriteLineForError(MethodBase.GetCurrentMethod().DeclaringType, e);
            }
        }
        protected override void OnEventWritten(EventWrittenEventArgs e)
        {
            var color = ConsoleColor.Gray;

            switch (e.Level)
            {
            case EventLevel.Informational:
                color = ConsoleColor.White;
                break;

            case EventLevel.Warning:
                color = ConsoleColor.Yellow;
                break;

            case EventLevel.Error:
            case EventLevel.Critical:
                color = ConsoleColor.Red;
                break;
            }

            ConsoleManager.PushColor(color);
            Console.WriteLine(e.Payload[0]);
            ConsoleManager.PopColor();
        }
Example #34
0
        public static void ChangeTheStatus()
        {
            Console.WriteLine("Enter ID of user:"******"Enter ID of order:");
                int idOfOrder = ConsoleManager.ReadInt();
                if (FindOrderByID(idOfOrder, AccountManager.FindUserById(choiceOfUser)) != null)
                {
                    FindOrderByID(idOfOrder, AccountManager.FindUserById(choiceOfUser)).Status = ChoosenStatus();
                }
                else
                {
                    Console.WriteLine("There is no such order!");
                    Console.WriteLine("Please, type the enter to continue...)");
                }
            }
            else
            {
                Console.WriteLine("There is no such user, \nplease, create it first!");
            }
        }
Example #35
0
        public override void OnEventWritten(EventLevels level, string message)
        {
            ConsoleColor color = ConsoleColor.Gray;

            switch (level)
            {
            case EventLevels.Info:
                color = ConsoleColor.White;
                break;

            case EventLevels.Warning:
                color = ConsoleColor.Yellow;
                break;

            case EventLevels.Error:
            case EventLevels.Critical:
                color = ConsoleColor.Red;
                break;
            }

            ConsoleManager.PushColor(color);
            Console.WriteLine(message);
            ConsoleManager.PopColor();
        }
        /// <summary>
        /// Draws all fields attacked by pieces with the specified color.
        /// </summary>
        /// <param name="command">The Attacks command.</param>
        private void DrawAttacks(Command command)
        {
            var colorArgument = command.GetArgument <string>(0);

            List <Position> attacks;

            if (colorArgument == "all")
            {
                attacks = VisualBoard.FriendlyBoard.GetAttacks();
            }
            else
            {
                var colorTypeParseResult = Enum.TryParse(colorArgument, true, out Color colorType);
                if (!colorTypeParseResult)
                {
                    ConsoleManager.WriteLine($"$rInvalid color parameter ($R{colorArgument}$r)");
                    return;
                }

                attacks = VisualBoard.FriendlyBoard.GetAttacks(colorType);
            }

            VisualBoard.AddExternalSelections(attacks);
        }
        public void ConsoleManager_InvokeCommand_CallsProcessStart()
        {
            var _processStartCalled = false;

              // Arrange
              var processFactory = new MockProcessFactory
              {
            MockCreateProcess_StartInfo = startInfo =>
            {
              return new MockProcessWrapper
              {
            MockStart = () => _processStartCalled = true
              };
            }
              };

              var cm = new ConsoleManager(processFactory);

              // Act
              cm.InvokeCommand("hello", "world");

              // Assert
              Assert.IsTrue(_processStartCalled);
        }
        public void Execute(HashSet <Field> fields)
        {
            int[][] grid = this.generator.GenerateNewSukoku();
            this.solver.SolveSudoku(grid);
            int[][] solvedGrid = this.solver.GetGrid;

            ConsoleManager.SetCursorPosition(BoardConstants.InformationCol, BoardConstants.InformationRow);
            ConsoleManager.SetColor(BoardConstants.DefaultPromptColor);

            if (this.isCorrect(grid, fields))
            {
                ConsoleManager.WriteLine(ButtonsConstants.SolutionIsCorrectMsg);
            }
            else
            {
                ConsoleManager.WriteLine(ButtonsConstants.SolutionIsInCorrectMsg);
            }

            ConsoleManager.SetCursorPosition(0, 0);
            Console.ReadKey();
            Console.Clear();

            Environment.Exit(0);
        }
Example #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConsoleSession"/> class.
 /// </summary>
 public ConsoleSession(ConsoleManager consoleManager)
     : this(80, 40, consoleManager)
 {
 }
        public static ConsoleIdentifier GetDefaultConsole()
        {
            using (var manager = new ConsoleManager())
            {
                var defaultConsole = manager.GetDefaultConsole();

                if (defaultConsole == null)
                {
                    return null;
                }

                return new ConsoleIdentifier(defaultConsole.Alias, defaultConsole.Address, true);
            }
        }
        protected override void OnClosed(EventArgs e)
        {
            this.consoleManager.ConsoleAdded -= OnConsolesChanged;
            this.consoleManager.ConsoleRemoved -= OnConsolesChanged;
            this.consoleManager.DefaultConsoleChanged -= OnConsolesChanged;

            this.consoleManager.Dispose();
            this.consoleManager = null;
            base.OnClosed(e);
        }
        public static ConsoleIdentifier CreateConsole(string nameOrAddress)
        {
            using (var manager = new ConsoleManager())
            {
                var consoles = manager.GetConsoles();
                var defaultConsole = manager.GetDefaultConsole();
                XtfConsole console;

                if (string.IsNullOrEmpty(nameOrAddress))
                {
                    // Null means use the default console
                    console = defaultConsole;
                    if (console == null)
                    {
                        return null;
                    }
                }
                else
                {
                    // Try to find a console with an alias matching that given
                    console = consoles.FirstOrDefault(c => StringComparer.OrdinalIgnoreCase.Equals(c.Alias, nameOrAddress));

                    if (console == null)
                    {
                        // Not found by alias, try by address.
                        console = consoles.FirstOrDefault(c => StringComparer.OrdinalIgnoreCase.Equals(c.Address, nameOrAddress));

                        if (console == null)
                        {
                            // Couldn't find one, so we'll assume the value given is an address
                            return new ConsoleIdentifier(nameOrAddress, nameOrAddress, false);
                        }
                    }
                }

                return new ConsoleIdentifier(console.Alias, console.Address, StringComparer.OrdinalIgnoreCase.Equals(console.Alias, defaultConsole.Alias));
            }
        }
Example #43
0
 public static void Setup()
 {
     Controller = new ConsoleManager();
 }
Example #44
0
    // Use this for initialization
    void Start()
    {
        DontDestroyOnLoad(gameObject);

        if (CommandLineManager.IsServer)
        {
            gameServer = gameObject.AddComponent<ServerImplmentation>();
            cmdLineManager = gameObject.AddComponent<ConsoleManager>();
        }
        else
        {
            manager = gameObject.AddComponent<SteamManager>();
            gameClient = new GClient();
            gameClient.DataRecieved += GameClient_DataRecieved;
            gameClient.ConnectionStatusChanged += GameClient_ConnectionStatusChanged;
            gameClient.ConnectingToServer += GameClient_ConnectingToServer;

            gameClient.MatchmakingListFoundServer += GameClient_MatchmakingListFoundServer;

            //request = gameClient.RefreshList(EServerList.LAN);
        }
    }
Example #45
0
 /// <summary>
 /// The entry point of the program.
 /// </summary>
 private static void Main()
 {
     GridManager gridManager = new GridManager();
     IIOManager ioManager = new ConsoleManager();
     GameEngine.Run(gridManager, ioManager);
 }
Example #46
0
        static void Main()
        {
            ConsoleManager consoleManager = new ConsoleManager(new Keyboard(), 150);

            consoleManager.Start();
        }
Example #47
0
 public void CallConsoleManager()
 {
     var cm = new ConsoleManager();
     cm.ShowDialog();
 }