public Client()
    {
        var factory = new StateFactory();
        var first   = new State1(factory, this);

        CurrentState = factory.GetOrCreate <State1>(() => first);
    }
Esempio n. 2
0
        private void NodeChosen(Node node, GameInfo gameInfo, IGameState waitState)
        {
            gameInfo.Fsm.Remove(waitState);
            gameInfo.ClearTargets();
            gameInfo.PanCameraToObject(gameInfo.CurrentPlayer);
            var currentPlayer = gameInfo.CurrentPlayer;

            currentPlayer.NextNode = node;

            // Give the player a passport for the island they are going to arrive at
            var assetResponse = currentPlayer.Accept(new PassportStamp(((Travel)node.BindedLogic.PureLogic).IslandType));

            // Give the player a car modification if required

            currentPlayer.SetTransport(TransportType);

            if (assetResponse == AssetResponse.CollectedAllPassportStamps)
            {
                if (gameInfo.GameRuleType == GameRuleType.Passport)
                {
                    gameInfo.Fsm.LazyPush(StateFactory.GetState(GameStates.GameStates.EndGame));
                }
            }

            gameInfo.CreateMessage(String.Format("You have been given a {0} passport token!", IslandType));

            gameInfo.Fsm.Push(StateFactory.GetState(GameStates.GameStates.VisuallyMovePlayer));
        }
        public void StoryCardLogicTest()
        {
            StoryCardData target  = new StoryCardData();
            var           stories = StoryCardData.PopulateStoryCards();

            StateFactory.SetInstance(new StateFactory());
            StateFactory.AddFactory(GameStates.Wait, new WaitFactory());

            var gameTime = new GameTime();
            var player   = new Player();

            player.Initialize();
            player.Accept(new Transport(TransportType.Car, String.Empty, int.MaxValue, null, null, 0));
            var world = new List <WorldObject> {
                new StartingNode(Vector2.Zero), new Spinner(Vector2.Zero)
            };
            var gameInfo = new GameInfo(world, new[] { player }, 100, GameRuleType.Retirement);

            gameInfo.GetNextPlayer();

            foreach (var story in stories)
            {
                var performingLogic = story.PureLogic;

                Assert.IsNotNull(performingLogic);
                try {
                    var returnedStates = story.PureLogic.PerformLogic(gameTime, gameInfo);
                } catch (Exception e) {
                    Console.WriteLine(e);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);
            SafeDispose(ref vertexBuffers);
            SafeDispose(ref indexBuffers);

            surfaceShader = Game.Content.Load <Ubershader>("surface");
            factory       = new StateFactory(surfaceShader, typeof(SurfaceFlags), Primitive.TriangleList, VertexInputElement.FromStructure <VertexColorTextureTBN>());


            scene = Game.Content.Load <Scene>(@"Scenes\testScene");

            vertexBuffers = scene.Meshes
                            .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                            .ToArray();

            indexBuffers = scene.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();


            surfaceProps = scene.Materials
                           .Select(mtrl => new SurfaceProperties()
            {
                Diffuse   = LoadTexture2D(mtrl.TexturePath, "|srgb", defaultDiffuse),
                Specular  = LoadTexture2D(mtrl.TexturePath, "_spec", defaultSpecular),
                NormalMap = LoadTexture2D(mtrl.TexturePath, "_local", defaultNormalMap),
                Emission  = LoadTexture2D(mtrl.TexturePath, "_glow|srgb", defaultEmission),
            })
                           .ToArray();
        }
Esempio n. 5
0
 public Robot(ITable table, int lateralSpeed, IDisplayConsole displayConsole)
 {
     Table           = table;
     LateralSpeed    = lateralSpeed;
     CurrentState    = StateFactory.CreateInactive(this);
     _displayConsole = displayConsole;
 }
Esempio n. 6
0
 private void BStart_Click(object sender, EventArgs e)
 {
     skills       = new SkillManager(keyEvents, this);
     stateFactory = new StateFactory(this, keyEvents, skills, this);
     currentState = stateFactory.NewState <Searching>();
     PlayerTimer.Start();
 }
        public override void doAction(Comedian bot)
        {
            //Go to Sleep State if bedtime
            if ((bot.WakeTime > bot.SleepTime && (DateTime.Now.TimeOfDay < bot.WakeTime && DateTime.Now.TimeOfDay >= bot.SleepTime)) || (bot.WakeTime < bot.SleepTime && (DateTime.Now.TimeOfDay < bot.WakeTime || DateTime.Now.TimeOfDay >= bot.SleepTime)))
            {
                attentionCounter = ++attentionCounter % 4;

                if (attentionCounter == 0) //8 seconds elapsed
                {
                    //Say Good Night
                    lock (bot.OutgoingMessage)
                    {
                        bot.OutgoingMessage.Enqueue(new ChatMessage(bot.PSource, bot.retrieve(bot.PSource)[0], bot.PSource.MasterAccount, new TextMessage(getAIMLResponse("SayStatementPattern sleepy", getPrimaryUser(bot), bot))));
                    }
                    bot.setNextState(StateFactory.getBotState("Sleep", bot));
                }
            }
            else if ((bot.OffWorkTime > bot.WorkTime && (DateTime.Now.TimeOfDay < bot.OffWorkTime && DateTime.Now.TimeOfDay >= bot.WorkTime)) || (bot.OffWorkTime < bot.WorkTime && (DateTime.Now.TimeOfDay < bot.OffWorkTime || DateTime.Now.TimeOfDay >= bot.WorkTime)))
            {
                attentionCounter = ++attentionCounter % 30;

                if (attentionCounter == 0) //1 minute elapsed
                {
                    //Say Time for Work
                    lock (bot.OutgoingMessage)
                    {
                        bot.OutgoingMessage.Enqueue(new ChatMessage(bot.PSource, bot.retrieve(bot.PSource)[0], bot.PSource.MasterAccount, new TextMessage(getAIMLResponse("SayStatementPattern time for work", getPrimaryUser(bot), bot))));
                    }
                    bot.setNextState(StateFactory.getBotState("Busy", bot));
                }
            }
        }
Esempio n. 8
0
        public override IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
        {
            var currentPlayer = gameInfo.CurrentPlayer;

            currentPlayer.CareerType = CareerType.CollegeCareer;

            // Test if they're already taken the exam before
            if (currentPlayer.PassedExam)
            {
                return(null);
            }

            var waitState = StateFactory.GetState(GameStates.GameStates.Wait);

            if (currentPlayer.CurrentlyTakingExam)
            {
                return(TestPassedExamLogic(gameInfo, waitState));
            }


            if (currentPlayer.CareerType != CareerType.CollegeCareer)
            {
                return(CreateAlert(gameInfo, waitState, "You can only take an exam if you took college path", icon: "Images/AlertIcons/Fail"));
            }

            // Strip their roll amount;
            currentPlayer.RollAmount = 0;

            // Set their taking exam boolean to be true
            currentPlayer.CurrentlyTakingExam = true;

            return(TakeExamLogic(gameInfo));
        }
Esempio n. 9
0
        public async Task TimerTest()
        {
            await using var serving = await WebSocketHost.ServeAsync();

            var tp = Services.GetRequiredService <ITimeService>();

            var pub = await Publisher.PublishAsync(_ => tp.GetTimeAsync());

            var rep = Replicator.GetOrAdd <DateTime>(pub.Ref);
            await rep.RequestUpdateAsync().AsAsyncFunc()
            .Should().CompleteWithinAsync(TimeSpan.FromMinutes(1));

            var count = 0;

            using var state = StateFactory.NewLive <DateTime>(
                      o => o.WithZeroUpdateDelay(),
                      async(_, ct) => await rep.Computed.UseAsync(ct));
            state.Updated += s => {
                Out.WriteLine($"Client: {s.Value}");
                count++;
            };

            await TestEx.WhenMet(
                () => count.Should().BeGreaterThan(2),
                TimeSpan.FromSeconds(5));
        }
Esempio n. 10
0
 public override void doAction(Comedian bot)
 {
     if ((bot.WakeTime > bot.SleepTime && (DateTime.Now.TimeOfDay >= bot.WakeTime || DateTime.Now.TimeOfDay < bot.SleepTime)) || (bot.WakeTime < bot.SleepTime && (DateTime.Now.TimeOfDay >= bot.WakeTime && DateTime.Now.TimeOfDay < bot.SleepTime)))
     {
         bot.setNextState(StateFactory.getBotState("Greeting", bot));
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Load content
        /// </summary>
        public void LoadContent()
        {
            uberShader = Content.Load <Ubershader>("render");
            factory    = new StateFactory(uberShader, typeof(RenderFlags), Primitive.TriangleList, VertexInputElement.FromStructure <CubeVertex>());
            texture    = Content.Load <Texture2D>(@"Scenes\lena");

            vb = new VertexBuffer(GraphicsDevice, typeof(CubeVertex), 24);
            ib = new IndexBuffer(GraphicsDevice, 36);

            // create a new space with physics
            space = new Space();

            // update gravity force
            space.ForceUpdater.Gravity = new Vector3BEPU(0, -9.81f, 0);

            // add ground, ground has infinite mass
            Box ground = new Box(new Vector3BEPU(0, 0, 0), 50, 1, 50);

            space.Add(ground);

            // create boxes with random position and add color as a tag, then add box to space
            for (int i = 0; i < numberOfBoxes; i++)
            {
                Vector3Fusion vector = RandomExt.NextVector3(random, new Vector3Fusion(-10, 20, -10), new Vector3Fusion(10, 80, 10));
                Box           box    = new Box(new Vector3BEPU(vector.X, vector.Y, vector.Z), 1, 1, 1, 1);

                box.Tag = RandomExt.NextColor(random);
                space.Add(box);
            }
        }
Esempio n. 12
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);

            skySphere   = Game.Content.Load <Scene>("skySphere");
            cloudSphere = Game.Content.Load <Scene>("cloudSphere");
            clouds      = Game.Content.Load <Texture2D>("clouds|srgb");
            cirrus      = Game.Content.Load <Texture2D>("cirrus|srgb");
            noise       = Game.Content.Load <Texture2D>("cloudNoise");
            arrows      = Game.Content.Load <Texture2D>("arrowsAll");

            vertexBufferBlur = new VertexBuffer(Game.GraphicsDevice, typeof(VertexColorTextureTBN), 6);
            vertexBuffers    = skySphere.Meshes
                               .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                               .ToArray();

            indexBuffers = skySphere.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();

            cloudVertexBuffers = cloudSphere.Meshes
                                 .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                                 .ToArray();

            cloudIndexBuffers = cloudSphere.Meshes
                                .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                                .ToArray();

            sky     = Game.Content.Load <Ubershader>("sky");
            factory = new StateFactory(sky, typeof(SkyFlags), (ps, i) => EnumFunc(ps, (SkyFlags)i));
        }
Esempio n. 13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void InstancingDemo_Reloading(object sender, EventArgs e)
 {
     SafeDispose(ref factory);
     us      = Content.Load <Ubershader>("test");
     factory = new StateFactory(us, typeof(UberFlags), Primitive.TriangleList, VertexInputElement.FromStructure(typeof(Vertex)), BlendState.Additive, RasterizerState.CullNone, DepthStencilState.None);
     tex     = Content.Load <Texture2D>("block");
 }
Esempio n. 14
0
        public Form1()
        {
            InitializeComponent();
            DoubleBuffered = true;

            _state = StateFactory.GetPawnStartingState(8, 8);
        }
Esempio n. 15
0
        public void LoadContent()
        {
            effect  = Game.Content.Load <Ubershader>("debugRender.hlsl");
            factory = effect.CreateFactory(typeof(RenderFlags), (ps, i) => Enum(ps, (RenderFlags)i));

            //factory		=	effect.CreateFactory( typeof(RenderFlags), Primitive.LineList, VertexInputElement.FromStructure( typeof(LineVertex) ), BlendState.AlphaBlend, RasterizerState.CullNone, DepthStencilState.Default );
        }
Esempio n. 16
0
 public ErrorState(GumballMachine gumballMachine, StateFactory stateFactory, Exception exception = null)
     : base(gumballMachine, stateFactory)
 {
     _exception = exception;
     _name      = this.GetType().Name;
     Console.WriteLine($"[{_name}] Manager informed that machine is in error state.");
 }
Esempio n. 17
0
 public ActionsOr(Path path = null)
 {
     StateFactory.ValidateType(typeof(T));
     this.Path    = path ?? Path.Root;
     this.Tag     = 0;
     this.Variant = new Actions(this.Path.GetNested(0));
 }
Esempio n. 18
0
 public Account(string n, int firstDeposit = 0)
 {
     _name   = n;
     balance = firstDeposit;
     // Simplifying Method Calls - Replace Constructor with Factory Method
     _state = StateFactory.CreateAccount(firstDeposit, this);
 }
Esempio n. 19
0
 public Maybe(Path path = null)
 {
     StateFactory.ValidateType(typeof(T));
     this.Path    = path ?? Path.Root;
     this.Tag     = 0;
     this.Variant = new None(this.Path.GetNested(0));
 }
Esempio n. 20
0
        public async Task StandaloneComputedTest()
        {
            var users = Services.GetRequiredService <IUserService>();
            var time  = Services.GetRequiredService <ITimeService>();

            var u = new User()
            {
                Id   = int.MaxValue,
                Name = "Chuck Norris",
            };
            await users.CreateAsync(u, true);

            using var sText = await StateFactory.NewLive <string>(
                      o => o.WithInstantUpdates(),
                      async (s, cancellationToken) => {
                var norris = await users.TryGetAsync(int.MaxValue, cancellationToken).ConfigureAwait(false);
                var now    = await time.GetTimeAsync().ConfigureAwait(false);
                return($"@ {now:hh:mm:ss.fff}: {norris?.Name ?? "(none)"}");
            }).UpdateAsync(false);

            sText.Updated += (s, _) => Log.LogInformation($"{s.Value}");

            for (var i = 1; i <= 10; i += 1)
            {
                u.Name = $"Chuck Norris Lvl{i}";
                await users.UpdateAsync(u);

                await Task.Delay(100);
            }

            var text = await sText.UseAsync();

            text.Should().EndWith("Lvl10");
        }
Esempio n. 21
0
        public async Task SuppressTest()
        {
            var time   = Services.GetRequiredService <ITimeService>();
            var count1 = 0;
            var count2 = 0;

#pragma warning disable 1998
            var s1 = await StateFactory.NewComputed <int>(async (s, ct) => count1++).UpdateAsync(false);

            var s2 = await StateFactory.NewComputed <int>(async (s, ct) => count2++).UpdateAsync(false);

#pragma warning restore 1998
            var s12 = await StateFactory.NewComputed <(int, int)>(
                async (s, cancellationToken) => {
                var a       = await s1.UseAsync(cancellationToken);
                using var _ = Computed.Suppress();
                var b       = await s2.UseAsync(cancellationToken);
                return(a, b);
            }).UpdateAsync(false);

            var v12a = await s12.UseAsync();

            s1.Computed.Invalidate(); // Should increment c1 & impact c12
            var v12b = await s12.UseAsync();

            v12b.Should().Be((v12a.Item1 + 1, v12a.Item2));
            s2.Computed.Invalidate(); // Should increment c2, but shouldn't impact c12
            var v12c = await s12.UseAsync();

            v12c.Should().Be(v12b);
        }
Esempio n. 22
0
    void GenerateSprite(Node node)
    {
        if (node.GetType() == typeof(HouseNode))
        {
            var houseSprite = Instantiate(housePrefab) as GameObject;
            houseSprite.name = "HouseNode#" + node.nodeId;
            houseSprite.transform.position = node.coordinates;
        }
        else
        {
            var isRoot       = ((SwitchNode)node).isRoot;
            var switchPrefab = Instantiate(isRoot? rootObject : switchableObject) as GameObject;

            var handler = switchPrefab.GetComponent <SwitchHandler>();

            switchPrefab.name = node.nodeId;
            if (!isRoot)
            {
                ((SwitchNode)node).switchObject.state = StateFactory.Create(handler.currentIndex);
            }
            if (handler != null)
            {
                Subscribe(handler);
            }
            switchPrefab.transform.position = node.coordinates;
            (node as SwitchNode).childs.ForEach((Node switchNodeChild) =>
            {
                GenerateSprite(switchNodeChild);
            });
        }
    }
    private void Start()
    {
        //Set up state machine
        Dictionary <EnemyAIStateType, BaseState> stateMachineDictionary = new Dictionary <EnemyAIStateType, BaseState>();

        foreach (EnemyAIStateType state in EnemyStates)
        {
            stateMachineDictionary.Add(state, StateFactory.CreateBaseState(state, this));
        }
        stateMachine      = new EnemyAIStateMachine(stateMachineDictionary);
        TargetDestination = null;

        enemyController = GetComponent <Enemy>();
        MovementData    = (EnemyMovementData)enemyController.GetFiringData();

        navMeshAgent = GetComponent <NavMeshAgent>();

        //navMeshAgent.updateRotation = false;
        navMeshAgent.acceleration = MovementData.NavMeshAcceleration; // 8; //enemy
        navMeshAgent.angularSpeed = MovementData.NavMeshAngularSpeed; //120; // enemy
        navMeshAgent.speed        = MovementData.NavMeshVelocity;     //3; //

        //Events
        enemyController.UpdateTargetedPlayer += EnemyController_UpdateTargetedPlayer;
        bulletDetector.AddDangerousBullet    += BulletDetector_AddDangerousBullet;
    }
Esempio n. 24
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            stereo = Game.Content.Load <Ubershader>("stereo");

            SafeDispose(ref factory);
            factory = stereo.CreateFactory(typeof(Flags), Primitive.TriangleList, VertexInputElement.Empty, BlendState.Opaque, RasterizerState.CullNone, DepthStencilState.None);
        }
Esempio n. 25
0
            public IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
            {
                var currentPlayer = gameInfo.CurrentPlayer;

                var currentNode        = currentPlayer.CurrentNode;
                var returnedGameStates = new List <IGameState> {
                    StateFactory.GetState(GameStates.EndExecute)
                };



                if (currentNode.HasStopLogic)
                {
                    // TODO
                    currentPlayer.RollAmount = 0;
                }

                // TODO might not work anymore
                if (currentNode.HasPassingLogic || currentNode.HasStopLogic || currentNode.HasBeginningLogic || currentPlayer.RollAmount <= 1)
                {
                    returnedGameStates.Add(currentNode.BindedLogic);
                }

                return(returnedGameStates.ToArray());
            }
        public async Task AutoRecomputeTest()
        {
            var time = Services.GetRequiredService <ITimeService>();
            var c    = await Computed.CaptureAsync(
                _ => time.GetTimeWithOffsetAsync(TimeSpan.FromSeconds(1)));

            var count = 0L;

            using var state = StateFactory.NewLive <DateTime>(
                      o => o.WithZeroUpdateDelay(),
                      async(_, ct) => await c.UseAsync(ct));
            state.Updated += s
                             => Log.LogInformation($"{++count} -> {s.Value:hh:mm:ss:fff}");

            await TestEx.WhenMet(
                () => count.Should().BeGreaterThan(2),
                TimeSpan.FromSeconds(5));

            var lastCount = count;

            state.Dispose();

            await Task.Delay(1000);

            count.Should().Be(lastCount);
        }
Esempio n. 27
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            shader = Game.Content.Load <Ubershader>("hdr");
            //noiseTex	=	Game.Content.Load<DiscTexture>(@"noise\hdrDitherNoise");
            //noiseTex	=	Game.Content.Load<DiscTexture>(@"noise\bayerMatrix8x8");

            factory = shader.CreateFactory(typeof(Flags), Primitive.TriangleList, VertexInputElement.Empty, BlendState.Opaque, RasterizerState.CullNone, DepthStencilState.None);
        }
Esempio n. 28
0
 public GumballMachine(int numberOfGumballs)
 {
     _name         = this.GetType().Name;
     _stateFactory = new StateFactory(this);
     _stateFactory.SetStartingState(_stateFactory.GetNoCoinState());
     LoadNextState();
     AddGumballs(numberOfGumballs);
 }
Esempio n. 29
0
        void Game_Reloading(object sender, EventArgs e)
        {
            SafeDispose(ref factory);

            texture = Game.Content.Load <Texture2D>("particle2");
            shader  = Game.Content.Load <Ubershader>("test");
            factory = new StateFactory(shader, typeof(Flags), (ps, i) => EnumAction(ps, (Flags)i));
        }
Esempio n. 30
0
 public ParseEngine(Grammar grammar, ParseEngineOptions options)
 {
     Grammar      = grammar;
     Options      = options;
     NodeSet      = new ForestNodeSet();
     StateFactory = new StateFactory(DottedRules);
     Initialize();
 }
    protected StateManager()
    {
        //Initialize variable
        m_Factory		= null;
        m_Running		= true;
        m_Touches		= new FTouch[] {};
        m_Initialized	= false;
        m_RemovalDepth	= 0;

        //Listen
        ListenForUpdate(onUpdate);
        ListenForResize(onResize);
        EnableMultiTouch();
    }
 public void setup(StateFactory factory)
 {
     //Set factory
     m_Factory = factory;
 }
Esempio n. 33
0
		/// <summary>
		/// 
		/// </summary>
		void LoadContent ()
		{
			stereo	=	Game.Content.Load<Ubershader>("stereo");
			factory	=	stereo.CreateFactory( typeof(Flags), Primitive.TriangleList, VertexInputElement.Empty, BlendState.Opaque, RasterizerState.CullNone, DepthStencilState.None );
		}