Beispiel #1
0
        public void MakeNewGeneration(IRules rules)
        {
            var actualBoard = BoardValues.ConvertAll(e => new GamePixel(e.X, e.Y, e.IsAlive()));

            Parallel.For(0, actualBoard.Count, i =>
            {
                var actualPixel   = actualBoard[i];
                var neighborhoods = GetNeighborhoodsNumber(i, WidthElementsNumber, HeightElementsNumber, actualBoard);
                var decision      = rules.ChangeState(neighborhoods, actualPixel.IsAlive());
                switch (decision)
                {
                case ToState.ToDead:
                    BoardValues[i].Kill();
                    break;

                case ToState.ToLive:
                    BoardValues[i].Revive();
                    break;

                case ToState.DoNotChange:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            });
        }
Beispiel #2
0
 /// <summary>
 /// Restituiesce un sensore generico senza funzione di scalatura, gli input non vengono scalati
 /// </summary>
 /// <param name="name"></param>
 /// <param name="id"></param>
 /// <param name="rules"></param>
 protected AbstractSensor(
     string name,
     int id,
     IRules <Tin> rules) : this(name, id)
 {
     Rules = rules;
 }
 public RulesPanelViewModel(RuleViewModelFactory ruleViewModelFactory, PropertiesPanelViewModel propertiesPanelViewModel, IRules rules)
     : base("Rules")
 {
     _propertiesPanelViewModel = propertiesPanelViewModel;
     _rules     = rules;
     IsExpanded = true;
 }
Beispiel #4
0
        public RulerBase(IModifierBus bus, IRules rules, ISubject<IInfo> infoChannel)
        {
            _bus = bus;
            _rules = rules;

            _infoChannel = infoChannel;
        }
Beispiel #5
0
        public static void Main(string[] args)
        {
            output = new ConsoleOutput();
            input  = new ConsoleInput();
            board  = new Board();
            rules  = new MainRules();

            board.MakeBoard(11);
            players = GetPlayers();
            bool preparedToStart = rules.PrepareNewGame(board, players);

            if (preparedToStart)
            {
                output.PrintString(rules.GetIntro());
                output.ShowBoard(board.GetBoard());

                //main loop
                while (rules.GameContinues())
                {
                    int[][] move = input.GetMoveFromPlayer();
                    rules.ApplyMove(move);
                    output.ShowBoard(board.GetBoard());
                }
            }
            else
            {
                output.PrintString("Program unable to prepare game, aborting.");
            }
        }
Beispiel #6
0
 public Map(bool[,] state, IRules rules)
 {
     _state   = state;
     _rules   = rules;
     _xLenght = _state.GetLength(0);
     _yLenght = _state.GetLength(1);
 }
Beispiel #7
0
        public Candidate(
            CurrentState currentState,
            IFiniteStateMachine fsm,
            List <IPeer> peers,
            ILog log,
            IRandomDelay random,
            INode node,
            ISettings settings,
            IRules rules,
            ILoggerFactory loggerFactory)
        {
            try
            {
                _logger = loggerFactory.CreateLogger <Candidate>();
            }
            catch (ObjectDisposedException e)
            {
                //happens because asp.net shuts down services sometimes before onshutdown
            }

            _rules       = rules;
            _random      = random;
            _node        = node;
            _settings    = settings;
            _log         = log;
            _peers       = peers;
            _fsm         = fsm;
            CurrentState = currentState;
            StartElectioneering();
            ResetElectionTimer();
        }
Beispiel #8
0
 /// <summary>
 /// Initializes a SubBoard from the state given by its parameters.
 /// </summary>
 /// <param name="rules"></param>
 /// <param name="board"></param>
 /// <param name="isActive"></param>
 /// <param name="winner"></param>
 public SubBoard(IRules rules, MarkerType[,] board, bool isActive, MarkerType winner)
 {
     _rules   = rules;
     Winner   = winner;
     IsActive = isActive;
     _board   = board;
 }
        public void Should_Check_LoopThroughEachCell(int cellX, int cellY, State expected) // TODO: change method name
        {
            // arrange
            var fileInput  = new FileReader();
            var grid       = new Universe(fileInput);
            var gridLength = 3;
            var gridWidth  = 3;

            grid.SetUpGrid(gridLength, gridWidth);
            grid.Initialise();
            var rules = new IRules[]
            {
                new OvercrowdingRule(grid),
                new ReproductionRule(grid),
                new SurvivalRule(grid),
                new UnderpopulationRule(grid)
            };
            var logger = new Mock <ILogger <GameController> >();
            var game   = new GameController(grid, logger.Object, fileInput);

            // act
            game.LoopThroughEachCell();
            // assert
            Assert.Equal(expected, grid.Grid[cellX, cellY].CellState);
        }
Beispiel #10
0
            public void AddComponent(Discipline discipline, IRules rules, double coeficient)
            {
                var component = new ResultsListColumnComponent(discipline, rules, coeficient);

                this.components.Add(component);
                isSingleDiscipline   = coeficient == 1.0f && this.components.Count == 1;
                hasFinalPoints       = components.All(c => c.Rules.HasPoints); // all disciplines support points
                primaryComponent     = components.Select(c => c.Rules.PrimaryComponent).FirstOrDefault();
                hasSecondaryDuration = components.Select(c => c.Rules.HasDuration && c.Rules.PrimaryComponent == PerformanceComponent.Duration).FirstOrDefault();
                bool hasPerformance = components.Select(c => c.Rules.Name).Distinct().Count() == 1;  // all disciplines have same rules

                if (!hasPerformance)
                {
                    primaryComponent     = PerformanceComponent.None;
                    hasSecondaryDuration = false;
                }
                if (!discipline.AnnouncementsPublic)
                {
                    allowAnnouncements = allowPrivateData;
                }
                if (!discipline.ResultsPublic)
                {
                    allowResults = allowPrivateData;
                }
            }
Beispiel #11
0
 /// <summary>
 /// Add a new rule to our engine, its key is the settings section in the web.config
 /// </summary>
 /// <param name="SettingsSection"></param>
 /// <param name="NewRule"></param>
 public void AddRule(string SettingsSection, IRules NewRule)
 {
     if (!rules.ContainsKey(SettingsSection))
     {
         rules.Add(SettingsSection, NewRule);
     }
 }
Beispiel #12
0
 /// <summary>
 /// Create menu.
 /// </summary>
 /// <param name="rules">'Game of life' rules implementation</param>
 public Menu(IRules rules, IPlayerInterface playerInterface, ISaveManager saveManager)
 {
     _playerInterface = playerInterface;
     _saveManager     = saveManager;
     _gameRepo        = new GameRepository();
     _gameManager     = new (playerInterface, _gameRepo, rules);
 }
Beispiel #13
0
 /// <summary>
 /// Calculate new states for each cell. Using specified rules.
 /// </summary>
 private void CalculateNextGeneration(IRules rules)
 {
     foreach (Cell cell in Grid)
     {
         cell.CalculateNextState(rules);
     }
 }
        public RulesTest()
        {
            this.storageAdapter = new Mock <IStorageAdapterClient>();
            this.asaManager     = new Mock <IAsaManagerClient>();
            this.logger         = new Mock <ILogger <Rules> >();
            this.config         = new AppConfig
            {
                ExternalDependencies = new ExternalDependenciesConfig
                {
                    DiagnosticsServiceUrl    = "http://localhost:9006/v1",
                    DiagnosticsMaxLogRetries = 3,
                },
            };
            this.rulesMock           = new Mock <IRules>();
            this.alarms              = new Mock <IAlarms>();
            this.httpClientMock      = new Mock <IHttpClient>();
            this.httpContextAccessor = new Mock <IHttpContextAccessor>();
            this.diagnosticsClient   = new DiagnosticsClient(this.httpClientMock.Object, this.config, new Mock <ILogger <DiagnosticsClient> >().Object, this.httpContextAccessor.Object);

            this.httpContextAccessor
            .Setup(t => t.HttpContext.Request.HttpContext.Items)
            .Returns(new Dictionary <object, object>()
            {
                { "TenantID", TenantId },
            });
            this.asaManager
            .Setup(t => t.BeginRulesConversionAsync())
            .ReturnsAsync(new BeginConversionApiModel());

            this.rules = new Rules(this.storageAdapter.Object, this.asaManager.Object, this.logger.Object, this.alarms.Object, this.diagnosticsClient);
        }
Beispiel #15
0
        /// <summary>
        /// A default implementation for validating entities and behaviors using the specified rules.
        /// </summary>
        /// <param name="rules">The rules.</param>
        /// <param name="entities">The entities.</param>
        /// <exception cref="ValidationFailedException">Thrown if the validation failed.</exception>
        protected void Validate(IRules rules, IEntityCollection entities)
        {
            if (rules == null)
            {
                return;
            }
            if (entities != null)
            {
                foreach (var entity in entities)
                {
                    if (entity is IRuleSubject subject)
                    {
                        subject.Apply(rules);
                    }
                }
            }
            foreach (var behavior in EntityBehaviors.SelectMany(p => p))
            {
                if (behavior is IRuleSubject subject)
                {
                    subject.Apply(rules);
                }
            }

            // Are there still violated rules?
            if (rules.ViolationCount > 0)
            {
                throw new ValidationFailedException(this, rules);
            }
        }
Beispiel #16
0
 /// <summary>
 /// Initializes an empty Board using the given <paramref name="rules"/>.
 /// </summary>
 /// <param name="rules">The rules that the board will adhere to.</param>
 public Board(IRules rules)
 {
     _rules    = rules;
     Winner    = MarkerType.Empty;
     SubBoards = new SubBoard[BoardSize, BoardSize];
     InitializeSubBoards();
 }
Beispiel #17
0
 /// <summary>
 /// Initializes an empty SubBoard that will use the given <paramref name="rules"/>.
 /// </summary>
 /// <param name="rules">The rules that this SubBoard will adhere to.</param>
 public SubBoard(IRules rules)
 {
     _rules   = rules;
     Winner   = MarkerType.Empty;
     _board   = new MarkerType[SubBoardSize, SubBoardSize];
     IsActive = false;
     InitializeEmptyBoard();
 }
 public StrategyService(IRules rules)
 {
     _strategiesMap = new Dictionary <EStrategies, IStrategy>
     {
         { EStrategies.Aggressive, new AggressiveStrategy(rules) },
         { EStrategies.Defensive, new DefensiveStrategy(rules) },
     };
 }
Beispiel #19
0
 /// <summary>
 /// Basic constructor.
 /// </summary>
 /// <param name="gameView">Game window handler.</param>
 /// <param name="gameRepo">Repository with games.</param>
 /// <param name="rules">'Game of life' rules implementation</param>
 public GameManager(IGameView gameView, IGameRepository gameRepo, IRules rules)
 {
     _gameView      = gameView;
     _gameRepo      = gameRepo;
     _rules         = rules;
     _gamesOnScreen = new GameRepository();
     SetupTimer();
 }
 public LifeProcess(ICellService cellService, IRules rules)
 {
     OldGeneration = new List <Cell>();
     NewGeneration = new List <Cell>();
     _cellService  = cellService;
     _neighbours   = new List <Cell>();
     Rules         = rules;
 }
Beispiel #21
0
        public Game(IBoard board, IRules rules)
        {
            Board        = board;
            this.rules   = rules;
            this.player1 = new Player(State.Red);
            this.player2 = new Player(State.Yellow);

            ActivePlayer = this.player1;
        }
Beispiel #22
0
 public RequestVoteTests()
 {
     _rules    = new Rules();
     _settings = new InMemorySettingsBuilder().Build();
     _random   = new RandomDelay();
     _log      = new InMemoryLog();
     _peers    = new List <IPeer>();
     _node     = new NothingNode();
 }
Beispiel #23
0
 public RulesTest()
 {
     this.storageAdapter = new Mock <IStorageAdapterClient>();
     this.logger         = new Mock <ILogger>();
     this.servicesConfig = new Mock <IServicesConfig>();
     this.rulesMock      = new Mock <IRules>();
     this.alarms         = new Mock <IAlarms>();
     this.rules          = new Rules(this.storageAdapter.Object, this.logger.Object, this.alarms.Object);
 }
Beispiel #24
0
 public AlarmsByRuleController(
     IAlarms alarmService,
     IRules ruleService,
     ILogger logger)
 {
     this.alarmService = alarmService;
     this.ruleService  = ruleService;
     this.log          = logger;
 }
Beispiel #25
0
 /// <summary>
 /// Restituisce un sensore generico che usa una funzione di scalatura per calcolare il valore gli input
 /// </summary>
 /// <param name="name"></param>
 /// <param name="id"></param>
 /// <param name="scaleFunction"></param>
 /// <param name="rules"></param>
 protected AbstractSensor(
     string name,
     int id,
     IScale <Tin, Tout> scaleFunction,
     IRules <Tin> rules) : this(name, id, rules)
 {
     Console.WriteLine($"Abstract_{Type}_created({Id})");
     ScaleFunction = scaleFunction;
 }
Beispiel #26
0
 public AppendEntriesTests()
 {
     _rules    = new Rules();
     _settings = new InMemorySettingsBuilder().Build();
     _random   = new RandomDelay();
     _log      = new InMemoryLog();
     _peers    = new List <IPeer>();
     _fsm      = new InMemoryStateMachine();
     _node     = new NothingNode();
 }
 public AllServersConvertToFollowerTests()
 {
     _rules    = new Rules();
     _settings = new InMemorySettingsBuilder().Build();
     _random   = new RandomDelay();
     _log      = new InMemoryLog();
     _peers    = new List <IPeer>();
     _fsm      = new InMemoryStateMachine();
     _node     = new NothingNode();
 }
Beispiel #28
0
 public RequestVoteTests()
 {
     _loggerFactory = new Mock <ILoggerFactory>();
     _rules         = new Rules(_loggerFactory.Object, new NodeId(default(string)));
     _settings      = new InMemorySettingsBuilder().Build();
     _random        = new RandomDelay();
     _log           = new InMemoryLog();
     _peers         = new List <IPeer>();
     _node          = new NothingNode();
 }
        public static string Compute(int i)
        {
            Divider  = new DivisibleRules();
            Contener = new ContentRules();
            string message = string.Empty;

            message = Divider.Apply(i);
            message = message += Contener.Apply(i);
            return(string.IsNullOrEmpty(message) ? i.ToString() : message);
        }
Beispiel #30
0
        /// <inheritdoc/>
        void IRuleSubject.Apply(IRules rules)
        {
            var p     = rules.GetParameterSet <ComponentRuleParameters>();
            var nodes = Nodes.Select(name => p.Factory.GetSharedVariable(name)).ToArray();

            foreach (var rule in rules.GetRules <IConductiveRule>())
            {
                rule.AddPath(this, ConductionTypes.None, nodes[0], nodes[1]);
            }
        }
Beispiel #31
0
 public AllServersApplyToStateMachineTests()
 {
     _rules    = new Rules();
     _settings = new InMemorySettingsBuilder().Build();
     _random   = new RandomDelay();
     _peers    = new List <IPeer>();
     _log      = new InMemoryLog();
     _fsm      = new Rafty.FiniteStateMachine.InMemoryStateMachine();
     _node     = new NothingNode();
 }
Beispiel #32
0
 /// <summary>
 /// Gets a tableaux from cascade of cards.
 /// </summary>
 /// <param name="cascade">The cascade to get tableaux from.</param>
 /// <param name="rules">The rules to use when determining what makes a tableaux.</param>
 /// <returns>
 /// A list of linking cards from the top of a cascade
 /// </returns>
 public static List<Card> GetTableauxFromCascade(Cascade cascade, IRules rules)
 {
     List<Card> tableaux = new List<Card>();
     for (int i = (cascade.Count - 1); i > 0; i--)
     {
         tableaux.Add(cascade[i]);
         if (!rules.DoCardsLinkInCascade(cascade[i], cascade[i - 1]))
             break;
     }
     tableaux.Reverse();
     return tableaux;
 }
Beispiel #33
0
 public BratController()
 {
     rules = RulesManager.CreateByEntity<BratEntity, int>();
 }
Beispiel #34
0
 public VeiculoController()
 {
     rules = RulesManager.CreateByEntity<VeiculoEntity, int>();
 }
 public TestemunhaController()
 {
     rules = RulesManager.CreateByEntity<TestemunhaEntity, int>();
 }
Beispiel #36
0
 public static void SetRulesManagerInterface(IRules rules)
 {
     _rulesManager = rules;
 }
Beispiel #37
0
 public PolicialController()
 {
     rules = RulesManager.CreateByEntity<PolicialEntity, string>();
 }
Beispiel #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Game"/> class.
 /// </summary>
 /// <param name="rules">The rules.</param>
 public Game(IRules rules)
 {
     _states = new Stack<State>();
     _rules = rules;
     InitializeGame();
 }
 public static void SetRulesManagerInterface(IRules CustomRules)
 {
     _rulesManager = CustomRules;
 }
Beispiel #40
0
 public VitimaController()
 {
     rules = RulesManager.CreateByEntity<VitimaEntity, int>();
 }