public void SameFrameReceive() { var key = new EventKey(); var recv = new EventReceiver(key); key.Broadcast(); Assert.True(recv.TryReceive()); Assert.False(recv.TryReceive()); }
public override void Update() { // Check if the door has been pushed on. bool triggered; if (!activated && (triggeredEvent?.TryReceive(out triggered) ?? false)) { CollisionStarted(); } }
public override void Update() { // Check if the coin has been collected bool triggered; if (!activated && (triggeredEvent?.TryReceive(out triggered) ?? false)) { CollisionStarted(); } UpdateAnimation(); }
public override void Update() { // Increase the score if a new pipe has been passed if (pipePassedListener.TryReceive()) { ++currentScore; } // move to game over UI if (gameOverListener.TryReceive()) { currentScore = 0; Entity.Get <UIComponent>().Page = new UIPage { RootElement = gameOverRoot }; } // Update the current score scoreTextBlock.Text = "Score : {0,2}".ToFormat(currentScore); }
public override void Update() { // State control runSpeedEvent.TryReceive(out runSpeed); bool isAttackingNewValue; if (attackEvent.TryReceive(out isAttackingNewValue) && isAttackingNewValue && state != AnimationState.Punching) { currentTime = 0; state = AnimationState.Punching; } switch (state) { case AnimationState.Walking: UpdateWalking(); break; case AnimationState.Punching: UpdatePunching(); break; } }
public override async Task Execute() { Init(); while (Game.IsRunning) { var lost = ballLostListener.TryReceive(); if (lost) { GameOver(); } var shockTreated = brickErasedListener.TryReceive(); if (shockTreated) { CheckIfWon(); } await Script.NextFrame(); } }
public override void Update() { if (brain == null) { return; } if (Train) { var(gen, eval, high, genhigh) = brain.GetStats(); DebugText.Print($"Generation: {gen}\nEvalCount: {eval}\nGen Highscore: {genhigh}\nHighscore: {high}", new Int2(20, 235)); } if (brain.HasPredicted) { // draw lines DrawLines(); if (deathListener.TryReceive()) { brain.Inform(AIInput.CharacterMoveResult.Died); } else { if (pipeReceiver.TryReceive()) { brain.Inform(AIInput.CharacterMoveResult.PipePassed); } else { brain.Inform(AIInput.CharacterMoveResult.Lived); } } } if (Input.IsKeyPressed(Stride.Input.Keys.S)) { brain.SaveState(); } }
private void Move(float speed) { // Character speed Vector3 newMoveDirection; moveDirectionEvent.TryReceive(out newMoveDirection); // Allow very simple inertia to the character to make animation transitions more fluid moveDirection = moveDirection * 0.85f + newMoveDirection * 0.15f; character.SetVelocity(moveDirection * speed); // Broadcast speed as per cent of the max speed RunSpeedEventKey.Broadcast(moveDirection.Length()); // Character orientation if (moveDirection.Length() > 0.001) { yawOrientation = MathUtil.RadiansToDegrees((float)Math.Atan2(-moveDirection.Z, moveDirection.X) + MathUtil.PiOverTwo); } modelChildEntity.Transform.Rotation = Quaternion.RotationYawPitchRoll(MathUtil.DegreesToRadians(yawOrientation), 0, 0); }
public override void Update() { // State control runSpeedEvent.TryReceive(out runSpeed); isGroundedEvent.TryReceive(out bool isGroundedNewValue); if (isGrounded != isGroundedNewValue) { currentTime = 0; isGrounded = isGroundedNewValue; state = (isGrounded) ? AnimationState.Landing : AnimationState.Jumping; } switch (state) { case AnimationState.Walking: UpdateWalking(); break; case AnimationState.Jumping: UpdateJumping(); break; case AnimationState.Airborne: UpdateAirborne(); break; case AnimationState.Landing: UpdateLanding(); break; } }
// Use this if you have a regular controller/gamepad private void UpdatePlayerInput() { var vrController = Hand == HandSide.Left ? vrDeviceSystem.Device?.LeftHand : vrDeviceSystem.Device?.RightHand; if (vrController != null && vrController.State != DeviceState.Invalid) { return; } HandsInput handsInput; if (!handsControlEvent.TryReceive(out handsInput)) { return; } var hand = (int)Hand; var dt = (float)(Game.UpdateTime.Elapsed.Milliseconds * 0.001); // Movement var amountMovement = handsInput.HandMovement[hand] * (dt * MaxMoveSpeed); Entity.Transform.Position += amountMovement; // TODO Hand orientation should match the controller orientation // Grabbed object if (handsInput.HandGrab[hand] >= 0.5f) { GrabNewEntity(); } else { ReleaseGrabbedEntity(); } }
public void DelayedReceiverCreation() { var game = new EventSystemTest(); var frameCount = 0; game.AddTask(async() => { var evt = new EventKey(); EventReceiver rcv = null; while (frameCount < 25) { if (frameCount == 5) { evt.Broadcast(); } if (frameCount == 20) { rcv = new EventReceiver(evt); Assert.False(rcv.TryReceive()); evt.Broadcast(); } if (frameCount == 22) { Assert.NotNull(rcv); Assert.True(rcv.TryReceive()); game.Exit(); } await game.NextFrame(); frameCount++; } }); game.Run(); }
public override void Update() { // Await pressure plate state changes bool newState; if (triggerEventReceiver.TryReceive(out newState)) { if (Enabled) { if (newState != nextState) { nextState = newState; } } } // Button smoothing currentValue += currentDirection * (float)Game.UpdateTime.Elapsed.TotalSeconds; currentValue = MathUtil.Clamp(currentValue, 0.0f, TransitionTime); // Trigger a new state or a toggle when fully pressed down or released if (nextState != currentState) { currentValue += currentDirection * (float)Game.UpdateTime.Elapsed.TotalSeconds; if (nextState) { if (currentValue >= TransitionTime) { // Disable after one press if single activation is on if (SingleActivation) { Enabled = false; } currentState = true; currentValue = TransitionTime; toggledState = !toggledState; Changed.Broadcast(CurrentState); PlayStateSound(); UpdateVisuals(); } } else { if (currentValue <= 0.0f) { currentState = false; currentValue = 0.0f; // Toggle only changed when activated if (!Toggle) { Changed.Broadcast(CurrentState); PlayStateSound(); } UpdateVisuals(); } } } }
public void DelayedReceiverCreation() { var game = new EventSystemTest(); var frameCount = 0; game.AddTask(async () => { var evt = new EventKey(); EventReceiver rcv = null; while (frameCount < 25) { if (frameCount == 5) { evt.Broadcast(); } if (frameCount == 20) { rcv = new EventReceiver(evt); Assert.False(rcv.TryReceive()); evt.Broadcast(); } if (frameCount == 22) { Assert.NotNull(rcv); Assert.True(rcv.TryReceive()); game.Exit(); } await game.NextFrame(); frameCount++; } }); game.Run(); }
public static void RetrieveWeaponState(EventReceiver <bool> toggleAimEvent, EventReceiver <bool> toggleFireEvent, out bool aiming, out bool firing) { toggleAimEvent.TryReceive(out aiming); toggleFireEvent.TryReceive(out firing); aiming = aiming || firing; }
private void Move(float speed) { if (attackCooldown > 0) { return; } // Character speed ClickResult clickResult; if (moveDestinationEvent.TryReceive(out clickResult) && clickResult.Type != ClickType.Empty) { if (clickResult.Type == ClickType.Ground) { attackEntity = null; moveDestination = clickResult.WorldPosition; isRunning = true; } if (clickResult.Type == ClickType.LootCrate) { attackEntity = clickResult.ClickedEntity; Attack(); } } if (!isRunning) { RunSpeedEventKey.Broadcast(0); return; } var direction = moveDestination - Entity.Transform.WorldMatrix.TranslationVector; direction /= 3; var lengthSqr = direction.LengthSquared(); if (lengthSqr < 0.01f) { HaltMovement(); RunSpeedEventKey.Broadcast(0); return; } if (lengthSqr > 1) { direction.Normalize(); } // Allow a very simple inertia to the character to make animation transitions more fluid moveDirection = moveDirection * 0.85f + direction * 0.15f; character.SetVelocity(moveDirection * speed); // Broadcast speed as per cent of the max speed RunSpeedEventKey.Broadcast(moveDirection.Length()); // Character orientation if (moveDirection.Length() > 0.001) { yawOrientation = MathUtil.RadiansToDegrees((float)Math.Atan2(-moveDirection.Z, moveDirection.X) + MathUtil.PiOverTwo); } modelChildEntity.Transform.Rotation = Quaternion.RotationYawPitchRoll(MathUtil.DegreesToRadians(yawOrientation), 0, 0); }
/// <summary> /// Notifies this extension component that it has been registered in the owner's collection of extensions. /// </summary> /// <param name="owner">The extensible owner object that aggregates this extension.</param> public void Attach(IExtensibleCloudServiceComponent owner) { owner.Extensions.Demand <IRoleConfigurationSettingsExtension>(); IRoleConfigurationSettingsExtension roleConfigExtension = owner.Extensions.Find <IRoleConfigurationSettingsExtension>(); this.serviceBusEndpoint = roleConfigExtension.GetServiceBusEndpoint(WellKnownEndpointName.InterRoleCommunication); this.retryPolicy = roleConfigExtension.CommunicationRetryPolicy; if (this.serviceBusEndpoint != null) { // Configure Service Bus credentials and entity URI. var credentials = TransportClientCredentialBase.CreateSharedSecretCredential(this.serviceBusEndpoint.IssuerName, this.serviceBusEndpoint.IssuerSecret); var address = ServiceBusEnvironment.CreateServiceUri(WellKnownProtocolScheme.ServiceBus, this.serviceBusEndpoint.ServiceNamespace, String.Empty); // Configure Service Bus messaging factory and namespace client which is required for subscription management. this.messagingFactory = MessagingFactory.Create(address, credentials); this.managementClient = new ServiceBusNamespaceClient(address, credentials); ConfigureTopicClient(); ConfigureSubscriptionClient(this.ircSubscription = ConfigureSubscription(String.Concat(SubscriptionNamePrefix, this.senderInstanceID))); // Configure event receive action. this.receiveAction = (() => { BrokeredMessage msg = null; this.retryPolicy.ExecuteAction(() => { // Make sure we are not told to stop receiving while we are retrying. if (!cts.IsCancellationRequested) { if (EventReceiver.TryReceive(Settings.EventWaitTimeout, out msg)) { try { // Make sure we are not told to stop receiving while we were waiting for a new message. if (!cts.IsCancellationRequested) { // Extract the event data from brokered message. InterRoleCommunicationEvent e = msg.GetBody <InterRoleCommunicationEvent>(); // Notify all registered subscribers. NotifySubscribers(e); // Mark brokered message as complete. msg.Complete(this.retryPolicy); } else { msg.Defer(this.retryPolicy); } } catch (Exception ex) { // Abandons a brokered message and unlocks the message. msg.Abandon(this.retryPolicy); // Log an error. TraceManager.ServiceComponent.TraceError(ex); } } } }); }); // Configure event receive complete action. this.endReceive = ((ar) => { this.receiveAction.EndInvoke(ar); if (!cts.IsCancellationRequested) { this.receiveHandle = this.receiveAction.BeginInvoke(this.endReceive, null); } }); // Configure event send action. this.sendAction = ((e) => { this.retryPolicy.ExecuteAction(() => { EventSender.Send(e); }); }); // Configure event send complete action. this.endSend = ((ar) => { sendAction.EndInvoke(ar); }); } else { throw new CloudApplicationException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.SpecifiedServiceBusEndpointNotFound, WellKnownEndpointName.InterRoleCommunication, ServiceBusConfigurationSettings.SectionName)); } }
public override void Update() { DebugHacks(); if (Input.IsKeyPressed(Stride.Input.Keys.R)) { foreach (var entity in Entity.Scene.Children[0].Entities) { entity.Scene = null; } Entity.Scene.Children.RemoveAt(0); Loader.LoadLevel(currentLevel + 1); PopulateTasks(); } if (state == UIState.InGame) { var timeLeft = TurnSystem.RemainingTime; // is the game over Result result = tasksCompleted.TryReceive() ? Result.Success : timeLeft.Ticks < 0 ? Result.Failure : Result.None; if (result != Result.None) { // update GameResult page var cyclesLeft = 5 - robotBrain.Cycles; var starsNum = result == Result.Success ? Math.Max(1, cyclesLeft) : 0; var message = result == Result.Failure ? "The robot became sentient and took over the world!" : "You have succesfully completed all tasks"; var root = GameResult.RootElement as Panel; var description = root.Children[1] as TextBlock; var stars = (root.Children[2] as Panel).Children.Cast <ImageElement>().ToArray(); description.Text = message; for (int i = 0; i < stars.Length; i++) { if (stars[i].Source == null) { stars[i].Source = new SpriteFromSheet { Sheet = UISheet, CurrentFrame = 10 } } ; stars[i].Visibility = i < starsNum ? Visibility.Visible : Visibility.Hidden; } // Unlock next level if (result == Result.Success) { completedLevels = Math.Max(completedLevels, currentLevel + 1); } UI.Page = GameResult; TurnSystem.Disable(Entity.Scene); state = UIState.GameResult; } else { // update Game UI var nextUserAction = inputController.NextAction.GetActionType(); var nextRobotAction = robotBrain.NextAction.GetActionType(); var grid = GamePage.RootElement as Grid; var actions = ((grid.Children[0] as Panel).Children[0] as Panel).Children.Cast <Border>().ToArray(); var timer = grid.Children[2] as TextBlock; var taskEntries = ((grid.Children.Last() as Panel).Children.Skip(1).Select(c => ((c as Panel).Children[0] as ToggleButton, (c as Panel).Children[1] as TextBlock))).ToArray(); timer.Text = timeLeft.ToString("mm\\:ss"); for (int i = 0; i < taskEntries.Length; i++) { if (i >= tasks.Count) { taskEntries[i].Item1.Parent.Visibility = Visibility.Collapsed; continue; } taskEntries[i].Item1.Parent.Visibility = Visibility.Visible; taskEntries[i].Item1.State = tasks[i].Completed ? ToggleState.Checked : ToggleState.UnChecked; taskEntries[i].Item2.Text = TaskText(tasks[i].Type); taskEntries[i].Item2.WrapText = true; taskEntries[i].Item2.Width = 350; } UpdateActions(actions[0], ActionType.Movement, nextUserAction, nextRobotAction, 0); UpdateActions(actions[1], ActionType.Hold, nextUserAction, nextRobotAction, 2); UpdateActions(actions[2], ActionType.Laser, nextUserAction, nextRobotAction, 4); UpdateActions(actions[3], ActionType.Light, nextUserAction, nextRobotAction, 6); } } }